Procuremen.php 497 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199
  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. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen']),
  244. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesman']),
  245. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  246. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqappendsalesmen']),
  247. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesuppliers']),
  248. 'rfqissue' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue']),
  249. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesendmail']),
  250. 'rfqquotes' => $this->hasProcuremenPerm(['rfqlist', 'rfqquotes', 'rfqissue']),
  251. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers']),
  252. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  253. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  254. ];
  255. $this->assignconfig('procuremenAuth', $authMap);
  256. }
  257. /**
  258. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  259. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  260. *
  261. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  262. */
  263. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  264. {
  265. static $mprocCfgLoaded = false;
  266. if (!$mprocCfgLoaded) {
  267. $mprocCfgLoaded = true;
  268. if (is_file(APP_PATH . 'extra/mproc.php')) {
  269. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  270. }
  271. }
  272. $eid = (int)$purchaseOrderDetailId;
  273. $base = $this->resolveMprocMobilePublicBaseUrl();
  274. if ($base === '') {
  275. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  276. }
  277. $path = trim((string)Config::get('mproc.mobile_index_path'));
  278. if ($path === '') {
  279. $path = '/index.php/index/index/index';
  280. } else {
  281. $path = '/' . ltrim($path, '/');
  282. }
  283. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  284. if ($eid > 0) {
  285. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  286. }
  287. return $base . $path . '?main_tab=orders';
  288. }
  289. /**
  290. * 邮件/短信外链:须为带点的公网域名
  291. */
  292. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  293. {
  294. $u = trim((string)$baseUrl);
  295. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  296. return false;
  297. }
  298. $host = parse_url($u, PHP_URL_HOST);
  299. if (!is_string($host) || $host === '') {
  300. return false;
  301. }
  302. if (strcasecmp($host, 'localhost') === 0) {
  303. return false;
  304. }
  305. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  306. return false;
  307. }
  308. if (strpos($host, '.') === false) {
  309. return false;
  310. }
  311. return true;
  312. }
  313. /**
  314. * 解析用于协助邮件/短信的手机端站点根
  315. */
  316. protected function resolveMprocMobilePublicBaseUrl()
  317. {
  318. $candidates = [];
  319. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  320. $candidates[] = trim((string)Config::get('site.indexurl'));
  321. $cdn = trim((string)Config::get('site.cdnurl'));
  322. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  323. $candidates[] = rtrim($cdn, '/');
  324. }
  325. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  326. $candidates[] = $reqBase;
  327. foreach ($candidates as $c) {
  328. if ($c === '') {
  329. continue;
  330. }
  331. $c = rtrim($c, '/');
  332. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  333. return $c;
  334. }
  335. }
  336. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  337. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  338. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  339. return $reqBase;
  340. }
  341. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  342. return '';
  343. }
  344. /**
  345. * 获取 Redis 中 procuremen_redis
  346. */
  347. protected function ProcuremenRedis(): array
  348. {
  349. if ($this->procuremenRedisCache !== null) {
  350. return $this->procuremenRedisCache;
  351. }
  352. try {
  353. $redis = redis();
  354. $raw = $redis->get('procuremen_redis');
  355. if ($raw === false || $raw === '') {
  356. $this->procuremenRedisCache = [];
  357. return $this->procuremenRedisCache;
  358. }
  359. $decoded = json_decode($raw, true);
  360. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  361. $this->procuremenRedisCache = [];
  362. return $this->procuremenRedisCache;
  363. }
  364. $this->procuremenRedisCache = $decoded['data'];
  365. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  366. if ($this->loadProcuremenSidebarYmList() === []) {
  367. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  368. }
  369. return $this->procuremenRedisCache;
  370. } catch (\Throwable $e) {
  371. $this->procuremenRedisCache = [];
  372. return $this->procuremenRedisCache;
  373. }
  374. }
  375. /**
  376. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  377. *
  378. * @return array<int, array<string, mixed>>
  379. */
  380. protected function procuremenFetchErpPoolFromDb(): array
  381. {
  382. try {
  383. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  384. $endTime = date('Y-m-d 23:59:59');
  385. $list = Db::table('scydgy')
  386. ->alias('a')
  387. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  388. ->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')
  389. ->where([
  390. 'a.bwjg' => 1,
  391. 'a.iEndBz' => 0,
  392. 'a.iType' => 0,
  393. 'a.iStatus' => 10,
  394. ])
  395. ->where('a.dStamp', '>=', $startTime)
  396. ->where('a.dStamp', '<=', $endTime)
  397. ->order('a.dStamp', 'desc')
  398. ->select();
  399. if (!is_array($list)) {
  400. return [];
  401. }
  402. try {
  403. $redis = redis();
  404. $payload = [
  405. 'code' => 200,
  406. 'msg' => 'success',
  407. 'data' => $list,
  408. ];
  409. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  410. $this->procuremenRedisCache = $list;
  411. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  412. $this->clearPickMonthPoolCaches();
  413. $this->warmPickMonthPoolCachesFromPool($list);
  414. } catch (\Throwable $e) {
  415. }
  416. return $list;
  417. } catch (\Throwable $e) {
  418. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  419. return [];
  420. }
  421. }
  422. /**
  423. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  424. *
  425. * @return array<int, array<string, mixed>>
  426. */
  427. protected function procuremenEnsureRedisPool(): array
  428. {
  429. $pool = $this->ProcuremenRedis();
  430. if (is_array($pool) && $pool !== []) {
  431. return $pool;
  432. }
  433. static $warmed = false;
  434. if ($warmed) {
  435. return is_array($pool) ? $pool : [];
  436. }
  437. $warmed = true;
  438. return $this->procuremenFetchErpPoolFromDb();
  439. }
  440. /**
  441. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  442. *
  443. * @param array<string, mixed> $row
  444. */
  445. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  446. {
  447. $t = $this->procuremenRowListSortTime($row, $primary);
  448. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  449. return null;
  450. }
  451. $mo = (int)$m[2];
  452. if ($mo < 1 || $mo > 12) {
  453. return null;
  454. }
  455. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  456. }
  457. /**
  458. * @param array<int, array{year:string, months:array}> $sidebar
  459. * @return array<int, array{year:string, months:array}>
  460. */
  461. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  462. {
  463. $ym = trim($ym);
  464. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  465. return $sidebar;
  466. }
  467. foreach ($sidebar as $block) {
  468. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  469. continue;
  470. }
  471. foreach ($block['months'] as $item) {
  472. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  473. return $sidebar;
  474. }
  475. }
  476. }
  477. $y = substr($ym, 0, 4);
  478. $mo = (int)substr($ym, 5, 2);
  479. $sidebar[] = [
  480. 'year' => $y,
  481. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  482. ];
  483. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  484. }
  485. /**
  486. * @param array<int, array{year:string, months:array}> $sidebar
  487. * @return string[]
  488. */
  489. protected function flattenProcuremenSidebarYms(array $sidebar): array
  490. {
  491. $yms = [];
  492. foreach ($sidebar as $block) {
  493. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  494. continue;
  495. }
  496. foreach ($block['months'] as $item) {
  497. if (!is_array($item)) {
  498. continue;
  499. }
  500. $ym = trim((string)($item['ym'] ?? ''));
  501. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  502. $yms[$ym] = true;
  503. }
  504. }
  505. }
  506. return array_keys($yms);
  507. }
  508. /**
  509. * 左侧菜单(协助初选)
  510. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  511. */
  512. protected function GetIndexYearMonths()
  513. {
  514. $ymList = $this->ensureProcuremenPickSidebarYmList();
  515. if ($ymList === []) {
  516. $def = date('Y-m');
  517. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  518. }
  519. return $this->buildYearMonthSidebar($ymList);
  520. }
  521. /**
  522. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  523. *
  524. * @return string[]
  525. */
  526. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  527. {
  528. static $memo = null;
  529. if (!$forceRefresh && is_array($memo)) {
  530. return $memo;
  531. }
  532. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  533. if ($fromDb !== []) {
  534. $this->saveProcuremenSidebarYmList($fromDb);
  535. $memo = $fromDb;
  536. return $memo;
  537. }
  538. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  539. $cached = $this->loadProcuremenSidebarYmList();
  540. if ($cached !== []) {
  541. $memo = $cached;
  542. return $memo;
  543. }
  544. $memo = [date('Y-m')];
  545. return $memo;
  546. }
  547. /**
  548. * @return string[] 形如 2026-07
  549. */
  550. protected function loadProcuremenSidebarYmList(): array
  551. {
  552. try {
  553. $raw = redis()->get('procuremen_redis_yms');
  554. if ($raw === false || $raw === null || $raw === '') {
  555. return [];
  556. }
  557. $decoded = json_decode((string)$raw, true);
  558. if (!is_array($decoded)) {
  559. return [];
  560. }
  561. $out = [];
  562. foreach ($decoded as $ym) {
  563. $ym = trim((string)$ym);
  564. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  565. $out[$ym] = true;
  566. }
  567. }
  568. return array_keys($out);
  569. } catch (\Throwable $e) {
  570. return [];
  571. }
  572. }
  573. /**
  574. * @param string[] $ymList
  575. */
  576. protected function saveProcuremenSidebarYmList(array $ymList): void
  577. {
  578. $out = [];
  579. foreach ($ymList as $ym) {
  580. $ym = trim((string)$ym);
  581. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  582. $out[$ym] = true;
  583. }
  584. }
  585. if ($out === []) {
  586. return;
  587. }
  588. try {
  589. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  590. } catch (\Throwable $e) {
  591. }
  592. }
  593. /**
  594. * @param array<int, array<string, mixed>> $pool
  595. * @return string[]
  596. */
  597. protected function extractYearMonthsFromPoolRows(array $pool): array
  598. {
  599. $ymSet = [];
  600. foreach ($pool as $r) {
  601. if (!is_array($r)) {
  602. continue;
  603. }
  604. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  605. continue;
  606. }
  607. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  608. if ($ym !== null) {
  609. $ymSet[$ym] = true;
  610. }
  611. }
  612. return array_keys($ymSet);
  613. }
  614. /**
  615. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  616. *
  617. * @return string[]
  618. */
  619. protected function queryProcuremenPickSidebarYmListLight(): array
  620. {
  621. try {
  622. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  623. $endTime = date('Y-m-d 23:59:59');
  624. $sql = 'SELECT DISTINCT DATE_FORMAT('
  625. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  626. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  627. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  628. . ' FROM scydgy a'
  629. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  630. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  631. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  632. $rows = Db::query($sql, [$startTime, $endTime]);
  633. if (!is_array($rows)) {
  634. return [];
  635. }
  636. $out = [];
  637. foreach ($rows as $r) {
  638. $ym = trim((string)($r['ym'] ?? ''));
  639. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  640. $out[$ym] = true;
  641. }
  642. }
  643. return array_keys($out);
  644. } catch (\Throwable $e) {
  645. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  646. return [];
  647. }
  648. }
  649. /**
  650. * @return string[] 含当月在内的近 N 个自然月
  651. */
  652. protected function buildRecentCalendarYmList(int $months = 12): array
  653. {
  654. $months = max(1, min(24, $months));
  655. $out = [];
  656. $base = strtotime(date('Y-m-01'));
  657. for ($i = 0; $i < $months; $i++) {
  658. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  659. }
  660. return $out;
  661. }
  662. /**
  663. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  664. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  665. *
  666. * @return array<int, array<string, mixed>>
  667. */
  668. protected function loadPickPoolForYm(string $ym): array
  669. {
  670. $ym = trim($ym);
  671. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  672. return [];
  673. }
  674. $hit = $this->readPickMonthPoolCache($ym);
  675. if ($hit !== null) {
  676. return $hit;
  677. }
  678. return $this->queryPickPoolForYmFromDb($ym);
  679. }
  680. /**
  681. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  682. */
  683. protected function readPickMonthPoolCache(string $ym): ?array
  684. {
  685. try {
  686. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  687. if ($raw === false || $raw === null || $raw === '') {
  688. return null;
  689. }
  690. $decoded = json_decode((string)$raw, true);
  691. if (!is_array($decoded)) {
  692. return null;
  693. }
  694. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  695. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  696. return $decoded['rows'];
  697. }
  698. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  699. if ($decoded === []) {
  700. try {
  701. redis()->del('procuremen_pick_pool:' . $ym);
  702. } catch (\Throwable $e) {
  703. }
  704. return null;
  705. }
  706. if (isset($decoded[0]) && is_array($decoded[0])) {
  707. return $decoded;
  708. }
  709. return null;
  710. } catch (\Throwable $e) {
  711. return null;
  712. }
  713. }
  714. /**
  715. * @param array<int, array<string, mixed>> $rows
  716. */
  717. protected function writePickMonthPoolCache(string $ym, array $rows): void
  718. {
  719. try {
  720. redis()->setex(
  721. 'procuremen_pick_pool:' . $ym,
  722. 600,
  723. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  724. );
  725. } catch (\Throwable $e) {
  726. }
  727. }
  728. /**
  729. * @param array<int, array<string, mixed>> $pool
  730. * @return array<int, array<string, mixed>>
  731. */
  732. protected function filterPoolRowsByYm(array $pool, string $ym): array
  733. {
  734. $out = [];
  735. foreach ($pool as $r) {
  736. if (!is_array($r)) {
  737. continue;
  738. }
  739. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  740. continue;
  741. }
  742. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  743. $out[] = $r;
  744. }
  745. }
  746. return $out;
  747. }
  748. /**
  749. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  750. *
  751. * @return array<int, array<string, mixed>>
  752. */
  753. protected function queryPickPoolForYmFromDb(string $ym): array
  754. {
  755. $monthStart = $ym . '-01 00:00:00';
  756. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  757. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  758. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  759. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  760. try {
  761. $list = Db::table('scydgy')
  762. ->alias('a')
  763. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  764. ->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')
  765. ->where([
  766. 'a.bwjg' => 1,
  767. 'a.iEndBz' => 0,
  768. 'a.iType' => 0,
  769. 'a.iStatus' => 10,
  770. ])
  771. ->where('a.dStamp', '>=', $queryStart)
  772. ->where('a.dStamp', '<=', $queryEnd)
  773. ->order('a.dStamp', 'desc')
  774. ->select();
  775. } catch (\Throwable $e) {
  776. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  777. return [];
  778. }
  779. if (!is_array($list)) {
  780. $list = [];
  781. }
  782. $out = $this->filterPoolRowsByYm($list, $ym);
  783. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  784. $this->writePickMonthPoolCache($ym, $out);
  785. try {
  786. $yms = $this->loadProcuremenSidebarYmList();
  787. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  788. $yms[] = $ym;
  789. $this->saveProcuremenSidebarYmList($yms);
  790. }
  791. } catch (\Throwable $e) {
  792. }
  793. return $out;
  794. }
  795. /**
  796. * 整包写入后拆成按月小缓存,供初选列表秒开
  797. *
  798. * @param array<int, array<string, mixed>> $pool
  799. */
  800. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  801. {
  802. if ($pool === []) {
  803. return;
  804. }
  805. $byYm = [];
  806. foreach ($pool as $r) {
  807. if (!is_array($r)) {
  808. continue;
  809. }
  810. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  811. continue;
  812. }
  813. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  814. if ($rowYm === null) {
  815. continue;
  816. }
  817. $byYm[$rowYm][] = $r;
  818. }
  819. if ($byYm === []) {
  820. return;
  821. }
  822. try {
  823. $redis = redis();
  824. foreach ($byYm as $rowYm => $rows) {
  825. $redis->setex(
  826. 'procuremen_pick_pool:' . $rowYm,
  827. 600,
  828. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  829. );
  830. }
  831. try {
  832. $redis->del('procuremen_pick_hidden_scydgy_v1');
  833. } catch (\Throwable $e) {
  834. }
  835. } catch (\Throwable $e) {
  836. }
  837. }
  838. /**
  839. * 刷新整包后清理近月缓存,避免脏读
  840. */
  841. protected function clearPickMonthPoolCaches(int $months = 24): void
  842. {
  843. try {
  844. $redis = redis();
  845. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  846. try {
  847. $redis->del('procuremen_pick_pool:' . $ym);
  848. } catch (\Throwable $e) {
  849. }
  850. }
  851. } catch (\Throwable $e) {
  852. }
  853. $this->invalidatePickHiddenScydgyCache();
  854. }
  855. /**
  856. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  857. */
  858. protected function invalidatePickHiddenScydgyCache(): void
  859. {
  860. $this->pickHiddenScydgySetCache = null;
  861. try {
  862. redis()->del('procuremen_pick_hidden_scydgy_v1');
  863. } catch (\Throwable $e) {
  864. }
  865. }
  866. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  867. protected function procuremenReleaseSessionLock(): void
  868. {
  869. if (session_status() === PHP_SESSION_ACTIVE) {
  870. @session_write_close();
  871. }
  872. }
  873. /**
  874. * @param string[] $ymList 形如 2026-06
  875. * @return array<int, array{year:string, months:array}>
  876. */
  877. protected function buildYearMonthSidebar(array $ymList): array
  878. {
  879. rsort($ymList, SORT_STRING);
  880. $byYear = [];
  881. foreach ($ymList as $ym) {
  882. $y = substr($ym, 0, 4);
  883. $mo = (int)substr($ym, 5, 2);
  884. if (!isset($byYear[$y])) {
  885. $byYear[$y] = [];
  886. }
  887. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  888. }
  889. krsort($byYear, SORT_NUMERIC);
  890. foreach ($byYear as $y => $items) {
  891. usort($byYear[$y], function ($a, $b) {
  892. return strcmp($b['ym'], $a['ym']);
  893. });
  894. }
  895. $sidebar = [];
  896. foreach ($byYear as $y => $months) {
  897. $sidebar[] = ['year' => $y, 'months' => $months];
  898. }
  899. return $sidebar;
  900. }
  901. /**
  902. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  903. */
  904. protected function GetIssuedOrderYearMonths(string $stage): array
  905. {
  906. $ymSet = [];
  907. try {
  908. $query = Db::table('purchase_order');
  909. $this->applyPurchaseOrderNotDeletedWhere($query);
  910. if ($stage === 'audit') {
  911. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  912. } elseif ($stage === 'confirm') {
  913. $this->applyPurchaseOrderConfirmStageWhere($query);
  914. } else {
  915. return $this->GetIndexYearMonths();
  916. }
  917. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  918. if (is_array($rows)) {
  919. foreach ($rows as $r) {
  920. if (!is_array($r)) {
  921. continue;
  922. }
  923. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  924. if ($ym !== null) {
  925. $ymSet[$ym] = true;
  926. }
  927. }
  928. }
  929. } catch (\Throwable $e) {
  930. $ymSet = [];
  931. }
  932. $ymList = array_keys($ymSet);
  933. if ($ymList === []) {
  934. $def = $this->resolveProcuremenDefaultYm($stage);
  935. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  936. }
  937. return $this->buildYearMonthSidebar($ymList);
  938. }
  939. /**
  940. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  941. */
  942. protected function resolveProcuremenDefaultYm(string $stage): string
  943. {
  944. if ($stage === 'pick') {
  945. $yms = $this->ensureProcuremenPickSidebarYmList();
  946. if ($yms !== []) {
  947. rsort($yms, SORT_STRING);
  948. return $yms[0];
  949. }
  950. return date('Y-m');
  951. }
  952. try {
  953. $query = Db::table('purchase_order');
  954. $this->applyPurchaseOrderNotDeletedWhere($query);
  955. if ($stage === 'audit') {
  956. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  957. } elseif ($stage === 'confirm') {
  958. $this->applyPurchaseOrderConfirmStageWhere($query);
  959. } else {
  960. return date('Y-m');
  961. }
  962. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  963. if ($latest === null || $latest === '') {
  964. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  965. }
  966. $t = $this->formatProcuremenDetailTime($latest);
  967. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  968. return $m[1] . '-' . $m[2];
  969. }
  970. } catch (\Throwable $e) {
  971. }
  972. return date('Y-m');
  973. }
  974. protected function applyPurchaseOrderNotDeletedWhere($query): void
  975. {
  976. $query->whereRaw(
  977. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  978. );
  979. }
  980. /**
  981. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  982. */
  983. protected function applyPurchaseOrderConfirmStageWhere($query): void
  984. {
  985. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  986. $quoted = [];
  987. foreach ($vals as $v) {
  988. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  989. }
  990. if ($quoted === []) {
  991. $query->whereRaw('1 = 0');
  992. return;
  993. }
  994. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  995. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  996. }
  997. /**
  998. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  999. *
  1000. * @param array<string, mixed> $row
  1001. * @return array<string, mixed>
  1002. */
  1003. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1004. {
  1005. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1006. $pick = trim((string)($row['pick_time'] ?? ''));
  1007. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1008. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1009. $t = trim((string)($row[$key] ?? ''));
  1010. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1011. $row['pick_time'] = $t;
  1012. break;
  1013. }
  1014. }
  1015. }
  1016. return $row;
  1017. }
  1018. /**
  1019. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1020. */
  1021. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1022. {
  1023. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1024. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1025. }
  1026. if ($pool === []) {
  1027. $def = $this->resolveProcuremenDefaultYm($stage);
  1028. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1029. }
  1030. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1031. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1032. return false;
  1033. }
  1034. $monthStart = $ym . '-01 00:00:00';
  1035. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1036. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1037. return $probe !== [];
  1038. };
  1039. if ($tryYm($requestedYm)) {
  1040. return $requestedYm;
  1041. }
  1042. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1043. if ($tryYm($fallback)) {
  1044. return $fallback;
  1045. }
  1046. $bestYm = '';
  1047. $bestTime = '';
  1048. foreach ($pool as $row) {
  1049. if (!is_array($row)) {
  1050. continue;
  1051. }
  1052. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1053. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1054. continue;
  1055. }
  1056. $ymRow = $m[1];
  1057. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1058. $bestTime = $t;
  1059. $bestYm = $ymRow;
  1060. }
  1061. }
  1062. if ($bestYm !== '') {
  1063. return $bestYm;
  1064. }
  1065. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1066. }
  1067. protected function isPurchaseOrderDetailVoid(array $row): bool
  1068. {
  1069. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1070. return true;
  1071. }
  1072. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1073. }
  1074. /**
  1075. * 仅当前有效下发明细(排除废弃归档)
  1076. */
  1077. protected function applyActivePurchaseOrderDetailWhere($query): void
  1078. {
  1079. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1080. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1081. }
  1082. /**
  1083. * @param array<string, mixed> $detailRow
  1084. */
  1085. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1086. {
  1087. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1088. return false;
  1089. }
  1090. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1091. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1092. }
  1093. /**
  1094. * 废弃退回初选:下发明细标记归档,不物理删除
  1095. *
  1096. * @param array<int, int|string> $scydgyIds
  1097. */
  1098. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1099. {
  1100. $ids = [];
  1101. foreach ($scydgyIds as $sid) {
  1102. $n = (int)$sid;
  1103. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1104. $ids[$n] = true;
  1105. }
  1106. }
  1107. if ($ids === []) {
  1108. return;
  1109. }
  1110. $void = ProcuremenStatus::POD_VOID;
  1111. Db::table('purchase_order_detail')
  1112. ->where('scydgy_id', 'in', array_keys($ids))
  1113. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1114. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1115. ->update([
  1116. 'status' => $void,
  1117. 'status_name' => $void,
  1118. ]);
  1119. }
  1120. /**
  1121. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1122. */
  1123. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1124. {
  1125. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1126. $norm = function (string $col) use ($p): string {
  1127. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1128. };
  1129. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1130. $parts = [];
  1131. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1132. if ($key === 'createtime') {
  1133. $parts[] = $createtime;
  1134. } else {
  1135. $parts[] = $norm($key);
  1136. }
  1137. }
  1138. return 'COALESCE(' . implode(', ', $parts) . ')';
  1139. }
  1140. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1141. {
  1142. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1143. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1144. }
  1145. /**
  1146. * @return array<int, array<string, mixed>>
  1147. */
  1148. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1149. {
  1150. $this->ensurePurchaseOrderCzlyqColumn();
  1151. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1152. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1153. try {
  1154. $query = Db::table('purchase_order')->field($fields);
  1155. $this->applyPurchaseOrderNotDeletedWhere($query);
  1156. if ($stage === 'audit') {
  1157. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1158. } elseif ($stage === 'confirm') {
  1159. $this->applyPurchaseOrderConfirmStageWhere($query);
  1160. } else {
  1161. return [];
  1162. }
  1163. $query->order('pick_time', 'desc')->order('id', 'desc');
  1164. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1165. $monthStart = $ym . '-01 00:00:00';
  1166. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1167. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1168. }
  1169. $rows = $query->select();
  1170. } catch (\Throwable $e) {
  1171. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1172. $rows = [];
  1173. }
  1174. return is_array($rows) ? $rows : [];
  1175. }
  1176. /**
  1177. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1178. */
  1179. protected function resolveProcuremenListStage(): string
  1180. {
  1181. $tab = trim((string)$this->request->request('wff_tab', ''));
  1182. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1183. return $tab;
  1184. }
  1185. $action = strtolower((string)$this->request->action());
  1186. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1187. return $action;
  1188. }
  1189. return 'pick';
  1190. }
  1191. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1192. {
  1193. $this->procuremenReleaseSessionLock();
  1194. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1195. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1196. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1197. $indexPhpRoot = $rootTrue . '/index.php';
  1198. }
  1199. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1200. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1201. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1202. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1203. $this->view->assign('defaultYm', $defaultYm);
  1204. $this->view->assign('sidebarYearMonths', $sidebar);
  1205. $this->view->assign('procuremenStage', $stage);
  1206. $this->view->assign('procuremenPageTitle', $pageTitle);
  1207. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1208. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1209. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1210. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1211. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1212. }
  1213. /**
  1214. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1215. *
  1216. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1217. */
  1218. protected function buildProcuremenFilterOptions(string $stage): array
  1219. {
  1220. $buckets = [
  1221. 'czlyq' => [],
  1222. 'CCLBMMC' => [],
  1223. 'cywyxm' => [],
  1224. 'CGYMC' => [],
  1225. ];
  1226. $maxPerField = 300;
  1227. try {
  1228. if ($stage === 'pick') {
  1229. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1230. return $buckets;
  1231. }
  1232. if (in_array($stage, ['audit', 'confirm'], true)) {
  1233. $this->ensurePurchaseOrderCzlyqColumn();
  1234. foreach (array_keys($buckets) as $field) {
  1235. try {
  1236. $query = Db::table('purchase_order')->field($field);
  1237. $this->applyPurchaseOrderNotDeletedWhere($query);
  1238. if ($stage === 'audit') {
  1239. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1240. } else {
  1241. $this->applyPurchaseOrderConfirmStageWhere($query);
  1242. }
  1243. $query->where($field, '<>', '')->whereNotNull($field);
  1244. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1245. if (!is_array($vals)) {
  1246. continue;
  1247. }
  1248. foreach ($vals as $v) {
  1249. $v = trim((string)$v);
  1250. if ($v !== '') {
  1251. $buckets[$field][$v] = $v;
  1252. }
  1253. }
  1254. } catch (\Throwable $e) {
  1255. // 单字段失败不影响其它
  1256. }
  1257. }
  1258. }
  1259. } catch (\Throwable $e) {
  1260. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1261. }
  1262. foreach ($buckets as &$set) {
  1263. if ($set !== []) {
  1264. ksort($set, SORT_STRING);
  1265. }
  1266. }
  1267. unset($set);
  1268. return $buckets;
  1269. }
  1270. /**
  1271. * filter JSON 是否含有效条件
  1272. *
  1273. * @param array<string, mixed> $filterArr
  1274. */
  1275. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1276. {
  1277. foreach ($filterArr as $v) {
  1278. if (is_array($v)) {
  1279. if (array_filter($v, function ($x) {
  1280. return $x !== '' && $x !== null;
  1281. })) {
  1282. return true;
  1283. }
  1284. } elseif ($v !== '' && $v !== null) {
  1285. return true;
  1286. }
  1287. }
  1288. return false;
  1289. }
  1290. /**
  1291. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1292. *
  1293. * @param array<string, mixed> $filterArr
  1294. * @param array<string, mixed> $opArr
  1295. */
  1296. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1297. {
  1298. if ($search !== '') {
  1299. return false;
  1300. }
  1301. foreach ($filterArr as $fk => $fv) {
  1302. if (is_array($fv)) {
  1303. continue;
  1304. }
  1305. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1306. continue;
  1307. }
  1308. if ($fv === null) {
  1309. continue;
  1310. }
  1311. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1312. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1313. if ($sym === '' || $sym === '=') {
  1314. continue;
  1315. }
  1316. return false;
  1317. }
  1318. return true;
  1319. }
  1320. /**
  1321. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1322. *
  1323. * @param array<int, mixed> $rows
  1324. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1325. */
  1326. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1327. {
  1328. $buckets = [
  1329. 'czlyq' => [],
  1330. 'CCLBMMC' => [],
  1331. 'cywyxm' => [],
  1332. 'CGYMC' => [],
  1333. ];
  1334. foreach ($rows as $r) {
  1335. if (!is_array($r)) {
  1336. continue;
  1337. }
  1338. foreach ($buckets as $field => &$set) {
  1339. if (count($set) >= $maxPerField) {
  1340. continue;
  1341. }
  1342. $v = trim((string)($r[$field] ?? ''));
  1343. if ($v !== '') {
  1344. $set[$v] = $v;
  1345. }
  1346. }
  1347. unset($set);
  1348. $full = true;
  1349. foreach ($buckets as $set) {
  1350. if (count($set) < $maxPerField) {
  1351. $full = false;
  1352. break;
  1353. }
  1354. }
  1355. if ($full) {
  1356. break;
  1357. }
  1358. }
  1359. foreach ($buckets as &$set) {
  1360. if ($set !== []) {
  1361. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1362. $normalized = [];
  1363. foreach ($set as $k => $v) {
  1364. $s = trim((string)(is_scalar($v) ? $v : $k));
  1365. if ($s === '') {
  1366. continue;
  1367. }
  1368. $normalized[$s] = $s;
  1369. }
  1370. ksort($normalized, SORT_STRING);
  1371. $set = $normalized;
  1372. }
  1373. }
  1374. unset($set);
  1375. return $buckets;
  1376. }
  1377. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1378. public function pick()
  1379. {
  1380. $this->request->filter(['strip_tags', 'trim']);
  1381. if (!$this->request->isAjax()) {
  1382. $this->assignProcuremenListPage('pick', '协助下发');
  1383. return $this->view->fetch('procuremen/index');
  1384. }
  1385. return $this->index();
  1386. }
  1387. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1388. public function audit()
  1389. {
  1390. $this->request->filter(['strip_tags', 'trim']);
  1391. if (!$this->request->isAjax()) {
  1392. $this->assignProcuremenListPage('audit', '确认供应商');
  1393. return $this->view->fetch('procuremen/index');
  1394. }
  1395. return $this->index();
  1396. }
  1397. /** 采购确认(定标) */
  1398. public function confirm()
  1399. {
  1400. $this->request->filter(['strip_tags', 'trim']);
  1401. if (!$this->request->isAjax()) {
  1402. $this->assignProcuremenListPage('confirm', '采购确认');
  1403. return $this->view->fetch('procuremen/index');
  1404. }
  1405. return $this->index();
  1406. }
  1407. /**
  1408. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1409. */
  1410. public function index()
  1411. {
  1412. $this->request->filter(['strip_tags', 'trim']);
  1413. if (!$this->request->isAjax()) {
  1414. $this->assignProcuremenListPage('pick', '协助下发');
  1415. return $this->view->fetch('procuremen/index');
  1416. }
  1417. if ($this->request->request('keyField')) {
  1418. return $this->selectpage();
  1419. }
  1420. $this->procuremenReleaseSessionLock();
  1421. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1422. $limit = max(10, min(500, (int)$limit));
  1423. $ym = $this->request->request('ym', '');
  1424. $ym = is_string($ym) ? trim($ym) : '';
  1425. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1426. $wffTab = $this->resolveProcuremenListStage();
  1427. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1428. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1429. ? $this->resolveProcuremenDefaultYm($wffTab)
  1430. : date('Y-m');
  1431. }
  1432. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1433. $ym = date('Y-m');
  1434. }
  1435. $monthStart = $ym . '-01 00:00:00';
  1436. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1437. $search = trim((string)$this->request->get('search', ''));
  1438. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1439. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1440. if (!is_array($filterArr)) {
  1441. $filterArr = [];
  1442. }
  1443. if (!is_array($opArr)) {
  1444. $opArr = [];
  1445. }
  1446. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1447. $bidOpenStatusFilter = '';
  1448. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1449. if (!array_key_exists($bidFk, $filterArr)) {
  1450. continue;
  1451. }
  1452. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1453. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1454. }
  1455. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1456. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1457. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1458. try {
  1459. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1460. if ($wffTab === 'audit') {
  1461. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1462. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1463. );
  1464. } elseif ($wffTab === 'confirm') {
  1465. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1466. if ($dbRows === []) {
  1467. try {
  1468. $dbRows = Db::table('purchase_order')
  1469. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1470. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1471. ->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%\')')
  1472. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1473. ->order('pick_time', 'desc')->order('id', 'desc')
  1474. ->select();
  1475. } catch (\Throwable $e) {
  1476. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1477. $dbRows = [];
  1478. }
  1479. }
  1480. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1481. if ($pool === []) {
  1482. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1483. }
  1484. } else {
  1485. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1486. if ($applyMonthRange) {
  1487. $pool = $this->loadPickPoolForYm($ym);
  1488. } else {
  1489. $pool = $this->procuremenEnsureRedisPool();
  1490. }
  1491. if (!is_array($pool)) {
  1492. $pool = [];
  1493. }
  1494. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1495. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1496. if ($pool !== [] && $hideSet !== []) {
  1497. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1498. if (!is_array($r)) {
  1499. return false;
  1500. }
  1501. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1502. return $id <= 0 || !isset($hideSet[$id]);
  1503. }));
  1504. }
  1505. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1506. if ($pool === []) {
  1507. return json([
  1508. 'total' => 0,
  1509. 'rows' => [],
  1510. 'activeYm' => $ym,
  1511. 'filterOptions' => (
  1512. (int)$offset === 0
  1513. && !$hasActiveSearch
  1514. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1515. )
  1516. ? $this->extractProcuremenFilterOptionsFromRows([])
  1517. : new \stdClass(),
  1518. ]);
  1519. }
  1520. }
  1521. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1522. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1523. $monthStart = $ym . '-01 00:00:00';
  1524. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1525. }
  1526. $filtered = $this->filterProcuremenIndexPool(
  1527. $pool,
  1528. $monthStart,
  1529. $monthEnd,
  1530. $applyMonthRange,
  1531. $search,
  1532. $filterArr,
  1533. $opArr,
  1534. $listTimePrimary
  1535. );
  1536. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1537. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1538. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1539. }
  1540. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1541. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1542. }
  1543. $sortField = 'ID';
  1544. if (is_string($sort) && $sort !== '') {
  1545. $parts = explode(',', $sort);
  1546. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1547. if ($sortField === '') {
  1548. $sortField = 'ID';
  1549. }
  1550. }
  1551. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1552. $nFiltered = count($filtered);
  1553. if ($nFiltered > 1) {
  1554. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1555. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1556. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1557. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1558. if ($ta === $tb) {
  1559. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1560. }
  1561. if ($ta === '') {
  1562. return 1;
  1563. }
  1564. if ($tb === '') {
  1565. return -1;
  1566. }
  1567. return strcmp($ta, $tb) * $ord;
  1568. });
  1569. } elseif ($sortField === 'ID') {
  1570. $sortKeys = [];
  1571. foreach ($filtered as $i => $row) {
  1572. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1573. }
  1574. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1575. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1576. } elseif ($sortField === 'CCYDH') {
  1577. usort($filtered, function ($a, $b) use ($ord) {
  1578. $sa = trim((string)($a['CCYDH'] ?? ''));
  1579. $sb = trim((string)($b['CCYDH'] ?? ''));
  1580. if ($sa === $sb) {
  1581. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1582. }
  1583. if ($sa === '') {
  1584. return 1;
  1585. }
  1586. if ($sb === '') {
  1587. return -1;
  1588. }
  1589. return strcmp($sa, $sb) * $ord;
  1590. });
  1591. } else {
  1592. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1593. $va = $a[$sortField] ?? null;
  1594. $vb = $b[$sortField] ?? null;
  1595. $sa = (string)$va;
  1596. $sb = (string)$vb;
  1597. if ($sa === $sb) {
  1598. return 0;
  1599. }
  1600. return strcmp($sa, $sb) * $ord;
  1601. });
  1602. }
  1603. }
  1604. $offset = max(0, (int)$offset);
  1605. $limit = max(1, (int)$limit);
  1606. $rows = array_slice($filtered, $offset, $limit);
  1607. foreach ($rows as &$rw) {
  1608. if (!is_array($rw)) {
  1609. continue;
  1610. }
  1611. $rid = (int)($rw['ID'] ?? 0);
  1612. $rw['_iss_out'] = ($wffTab !== 'pick');
  1613. }
  1614. unset($rw);
  1615. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1616. $idList = [];
  1617. foreach ($rows as $rw) {
  1618. if (!is_array($rw)) {
  1619. continue;
  1620. }
  1621. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1622. foreach ($rw['_order_merge_rows'] as $mr) {
  1623. $mid = (int)($mr['ID'] ?? 0);
  1624. if ($this->isValidScydgyRowId($mid)) {
  1625. $idList[$mid] = true;
  1626. }
  1627. }
  1628. }
  1629. $id = (int)($rw['ID'] ?? 0);
  1630. if ($this->isValidScydgyRowId($id)) {
  1631. $idList[$id] = true;
  1632. }
  1633. }
  1634. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1635. foreach ($rows as &$rw) {
  1636. if (!is_array($rw)) {
  1637. continue;
  1638. }
  1639. $mergeIds = [];
  1640. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1641. foreach ($rw['_order_merge_rows'] as $mr) {
  1642. $mid = (int)($mr['ID'] ?? 0);
  1643. if ($this->isValidScydgyRowId($mid)) {
  1644. $mergeIds[$mid] = true;
  1645. }
  1646. }
  1647. }
  1648. $rid = (int)($rw['ID'] ?? 0);
  1649. if ($this->isValidScydgyRowId($rid)) {
  1650. $mergeIds[$rid] = true;
  1651. }
  1652. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1653. $rw['po_detail_count'] = $s['cnt'];
  1654. $rw['po_amount_fill_cnt'] = $s['amt'];
  1655. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1656. }
  1657. unset($rw);
  1658. }
  1659. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1660. $idList = [];
  1661. foreach ($rows as $rw) {
  1662. if (!is_array($rw)) {
  1663. continue;
  1664. }
  1665. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1666. foreach ($rw['_order_merge_rows'] as $mr) {
  1667. $mid = (int)($mr['ID'] ?? 0);
  1668. if ($this->isValidScydgyRowId($mid)) {
  1669. $idList[$mid] = true;
  1670. }
  1671. }
  1672. }
  1673. $id = (int)($rw['ID'] ?? 0);
  1674. if ($this->isValidScydgyRowId($id)) {
  1675. $idList[$id] = true;
  1676. }
  1677. }
  1678. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1679. $bidOpenSet = [];
  1680. $manualPickSet = [];
  1681. if ($wffTab === 'audit') {
  1682. $ccydhList = [];
  1683. foreach ($rows as $rw0) {
  1684. if (!is_array($rw0)) {
  1685. continue;
  1686. }
  1687. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1688. if ($c0 !== '') {
  1689. $ccydhList[] = $c0;
  1690. }
  1691. }
  1692. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1693. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1694. }
  1695. foreach ($rows as &$rw) {
  1696. if (!is_array($rw)) {
  1697. continue;
  1698. }
  1699. $mergeIds = [];
  1700. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1701. foreach ($rw['_order_merge_rows'] as $mr) {
  1702. $mid = (int)($mr['ID'] ?? 0);
  1703. if ($this->isValidScydgyRowId($mid)) {
  1704. $mergeIds[$mid] = true;
  1705. }
  1706. }
  1707. }
  1708. $rid = (int)($rw['ID'] ?? 0);
  1709. if ($this->isValidScydgyRowId($rid)) {
  1710. $mergeIds[$rid] = true;
  1711. }
  1712. $buckets = [];
  1713. foreach (array_keys($mergeIds) as $mid) {
  1714. if (isset($quoteBucket[$mid])) {
  1715. $buckets[] = $quoteBucket[$mid];
  1716. }
  1717. }
  1718. $supplierText = $buckets !== []
  1719. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1720. : '';
  1721. if ($wffTab === 'confirm') {
  1722. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1723. if ($picked === '') {
  1724. // 兜底:从合并工序行取
  1725. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1726. foreach ($rw['_order_merge_rows'] as $mr) {
  1727. if (!is_array($mr)) {
  1728. continue;
  1729. }
  1730. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1731. if ($pn !== '') {
  1732. $picked = $pn;
  1733. break;
  1734. }
  1735. }
  1736. }
  1737. }
  1738. $rw['picked_supplier_name'] = $picked;
  1739. } else {
  1740. $rw['notify_supplier_text'] = $supplierText;
  1741. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1742. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1743. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1744. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1745. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1746. if ($verified) {
  1747. $rw['bid_open_status_text'] = '已开标';
  1748. } elseif ($manualPicked) {
  1749. $rw['bid_open_status_text'] = '已指定供应商';
  1750. } else {
  1751. $rw['bid_open_status_text'] = '待开标';
  1752. }
  1753. }
  1754. }
  1755. unset($rw);
  1756. }
  1757. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1758. $this->enrichProcuremenListMilestoneTimes($rows);
  1759. $this->syncCollapsedOrderQtyPriceForList($rows);
  1760. }
  1761. if ($wffTab === 'all' && count($rows) > 0) {
  1762. $this->mergePurchaseOrder($rows);
  1763. }
  1764. if ($wffTab === 'pick' && count($rows) > 0) {
  1765. $this->mergePurchaseOrder($rows);
  1766. }
  1767. foreach ($rows as &$rwClean) {
  1768. if (is_array($rwClean)) {
  1769. unset($rwClean['_order_merge_rows']);
  1770. if (array_key_exists('NGZL', $rwClean)) {
  1771. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1772. }
  1773. }
  1774. }
  1775. unset($rwClean);
  1776. return json([
  1777. 'total' => count($filtered),
  1778. 'rows' => $rows,
  1779. 'activeYm' => $ym,
  1780. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1781. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1782. ? $this->ensureProcuremenPickSidebarYmList()
  1783. : [],
  1784. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1785. 'filterOptions' => (
  1786. (int)$offset === 0
  1787. && !$hasActiveSearch
  1788. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1789. )
  1790. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1791. : new \stdClass(),
  1792. ]);
  1793. } catch (\Throwable $e) {
  1794. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1795. return json([
  1796. 'total' => 0,
  1797. 'rows' => [],
  1798. ]);
  1799. }
  1800. }
  1801. /**
  1802. * @param array<int, array<string, mixed>> $pool
  1803. * @return int[]
  1804. */
  1805. protected function extractScydgyIdsFromPool(array $pool): array
  1806. {
  1807. $ids = [];
  1808. foreach ($pool as $r) {
  1809. if (!is_array($r)) {
  1810. continue;
  1811. }
  1812. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1813. if ($id > 0) {
  1814. $ids[$id] = $id;
  1815. }
  1816. }
  1817. return array_values($ids);
  1818. }
  1819. /**
  1820. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1821. *
  1822. * @param int[] $scydgyIds
  1823. * @return array<int, true>
  1824. */
  1825. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1826. {
  1827. $hideSet = [];
  1828. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1829. return $id > 0;
  1830. }));
  1831. if ($scydgyIds === []) {
  1832. return $hideSet;
  1833. }
  1834. // 分批,避免 whereIn 过长
  1835. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1836. try {
  1837. $poIds = Db::table('purchase_order')
  1838. ->where('scydgy_id', 'in', $chunk)
  1839. ->where(function ($q) {
  1840. $q->whereIn('wflow_status', array_merge(
  1841. ProcuremenStatus::wflowPendingConfirmValues(),
  1842. ProcuremenStatus::wflowPendingApprovalValues()
  1843. ))
  1844. ->whereOr(function ($q1) {
  1845. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1846. })
  1847. ->whereOr(function ($q2) {
  1848. $q2->whereNotNull('pick_time')
  1849. ->where('pick_time', '<>', '')
  1850. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1851. })
  1852. ->whereOr(function ($q3) {
  1853. $q3->whereNotNull('mod_rq')
  1854. ->where('mod_rq', '<>', '')
  1855. ->where('mod_rq', 'not like', '0000-00-00%');
  1856. });
  1857. })
  1858. ->column('scydgy_id');
  1859. if (is_array($poIds)) {
  1860. foreach ($poIds as $pid) {
  1861. $k = (int)$pid;
  1862. if ($k !== 0) {
  1863. $hideSet[$k] = true;
  1864. }
  1865. }
  1866. }
  1867. } catch (\Throwable $e) {
  1868. }
  1869. try {
  1870. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1871. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1872. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1873. if (is_array($detIds)) {
  1874. foreach ($detIds as $pid) {
  1875. $k = (int)$pid;
  1876. if ($this->isValidScydgyRowId($k)) {
  1877. $hideSet[$k] = true;
  1878. }
  1879. }
  1880. }
  1881. } catch (\Throwable $e) {
  1882. }
  1883. }
  1884. return $hideSet;
  1885. }
  1886. /**
  1887. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1888. *
  1889. * @return array<int, true>
  1890. */
  1891. protected function loadPickHiddenScydgySet(): array
  1892. {
  1893. if ($this->pickHiddenScydgySetCache !== null) {
  1894. return $this->pickHiddenScydgySetCache;
  1895. }
  1896. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1897. try {
  1898. $raw = redis()->get($cacheKey);
  1899. if ($raw !== false && $raw !== null && $raw !== '') {
  1900. $ids = json_decode((string)$raw, true);
  1901. if (is_array($ids)) {
  1902. $hideSet = [];
  1903. foreach ($ids as $pid) {
  1904. $k = (int)$pid;
  1905. if ($k !== 0) {
  1906. $hideSet[$k] = true;
  1907. }
  1908. }
  1909. $this->pickHiddenScydgySetCache = $hideSet;
  1910. return $hideSet;
  1911. }
  1912. }
  1913. } catch (\Throwable $e) {
  1914. }
  1915. $hideSet = [];
  1916. try {
  1917. $poIds = Db::table('purchase_order')
  1918. ->where(function ($q) {
  1919. $q->whereIn('wflow_status', array_merge(
  1920. ProcuremenStatus::wflowPendingConfirmValues(),
  1921. ProcuremenStatus::wflowPendingApprovalValues()
  1922. ))
  1923. ->whereOr(function ($q1) {
  1924. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1925. })
  1926. ->whereOr(function ($q2) {
  1927. $q2->whereNotNull('pick_time')
  1928. ->where('pick_time', '<>', '')
  1929. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1930. })
  1931. ->whereOr(function ($q3) {
  1932. $q3->whereNotNull('mod_rq')
  1933. ->where('mod_rq', '<>', '')
  1934. ->where('mod_rq', 'not like', '0000-00-00%');
  1935. });
  1936. })
  1937. ->column('scydgy_id');
  1938. if (is_array($poIds)) {
  1939. foreach ($poIds as $pid) {
  1940. $k = (int)$pid;
  1941. if ($k !== 0) {
  1942. $hideSet[$k] = true;
  1943. }
  1944. }
  1945. }
  1946. } catch (\Throwable $e) {
  1947. }
  1948. try {
  1949. $detIdsQuery = Db::table('purchase_order_detail');
  1950. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1951. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1952. if (is_array($detIds)) {
  1953. foreach ($detIds as $pid) {
  1954. $k = (int)$pid;
  1955. if ($this->isValidScydgyRowId($k)) {
  1956. $hideSet[$k] = true;
  1957. }
  1958. }
  1959. }
  1960. } catch (\Throwable $e) {
  1961. }
  1962. $this->pickHiddenScydgySetCache = $hideSet;
  1963. try {
  1964. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  1965. } catch (\Throwable $e) {
  1966. }
  1967. return $hideSet;
  1968. }
  1969. /**
  1970. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1971. *
  1972. * @return array<int, array<string, mixed>>
  1973. */
  1974. protected function loadPickManualOrderRows(): array
  1975. {
  1976. try {
  1977. $dbRows = Db::table('purchase_order')
  1978. ->where('scydgy_id', '<', 0)
  1979. ->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%\')')
  1980. ->order('scydgy_id', 'asc')
  1981. ->select();
  1982. } catch (\Throwable $e) {
  1983. try {
  1984. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1985. } catch (\Throwable $e2) {
  1986. return [];
  1987. }
  1988. }
  1989. if (!is_array($dbRows) || $dbRows === []) {
  1990. return [];
  1991. }
  1992. $detailSidSet = [];
  1993. try {
  1994. $negIds = [];
  1995. foreach ($dbRows as $dbRow) {
  1996. if (!is_array($dbRow)) {
  1997. continue;
  1998. }
  1999. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2000. if ($sid < 0) {
  2001. $negIds[$sid] = true;
  2002. }
  2003. }
  2004. if ($negIds !== []) {
  2005. $detQuery = Db::table('purchase_order_detail')
  2006. ->where('scydgy_id', 'in', array_keys($negIds));
  2007. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2008. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2009. if (is_array($detRows)) {
  2010. foreach ($detRows as $did) {
  2011. $detailSidSet[(int)$did] = true;
  2012. }
  2013. }
  2014. }
  2015. } catch (\Throwable $e) {
  2016. }
  2017. $pool = [];
  2018. foreach ($dbRows as $dbRow) {
  2019. if (!is_array($dbRow)) {
  2020. continue;
  2021. }
  2022. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2023. if ($sid >= 0) {
  2024. continue;
  2025. }
  2026. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2027. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2028. continue;
  2029. }
  2030. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2031. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2032. continue;
  2033. }
  2034. if (isset($detailSidSet[$sid])) {
  2035. continue;
  2036. }
  2037. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2038. $r['_is_manual'] = 1;
  2039. $pool[] = $r;
  2040. }
  2041. return $pool;
  2042. }
  2043. /**
  2044. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2045. */
  2046. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2047. {
  2048. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2049. foreach ($keys as $k) {
  2050. $t = trim((string)($row[$k] ?? ''));
  2051. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2052. return $t;
  2053. }
  2054. }
  2055. return '';
  2056. }
  2057. /**
  2058. * 分配手工新增工序行 ID(负数递减)
  2059. */
  2060. protected function allocateManualScydgyId(): int
  2061. {
  2062. try {
  2063. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2064. $min = (int)$min;
  2065. return $min < 0 ? $min - 1 : -1;
  2066. } catch (\Throwable $e) {
  2067. return -1;
  2068. }
  2069. }
  2070. /**
  2071. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  2072. */
  2073. protected function allocateManualOrderCcydh(): string
  2074. {
  2075. $prefix = 'YW' . date('Ymd');
  2076. $maxSeq = 0;
  2077. try {
  2078. $rows = Db::table('purchase_order')
  2079. ->where('CCYDH', 'like', $prefix . '%')
  2080. ->column('CCYDH');
  2081. if (is_array($rows)) {
  2082. foreach ($rows as $ccydh) {
  2083. $ccydh = trim((string)$ccydh);
  2084. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  2085. $maxSeq = max($maxSeq, (int)$m[1]);
  2086. }
  2087. }
  2088. }
  2089. } catch (\Throwable $e) {
  2090. }
  2091. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  2092. }
  2093. /**
  2094. * purchase_order.mod_rq 是否有有效软删除时间
  2095. */
  2096. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2097. {
  2098. $t = trim((string)$modRq);
  2099. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2100. }
  2101. /**
  2102. * 列表行 → purchase_order 写入字段
  2103. *
  2104. * @return array<string, mixed>
  2105. */
  2106. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2107. {
  2108. return [
  2109. 'scydgy_id' => $scydgyId,
  2110. 'CCYDH' => $row['CCYDH'] ?? null,
  2111. 'CYJMC' => $row['CYJMC'] ?? null,
  2112. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2113. 'CDXMC' => $row['CDXMC'] ?? null,
  2114. 'CGYBH' => $row['CGYBH'] ?? null,
  2115. 'CGYMC' => $row['CGYMC'] ?? null,
  2116. 'CDW' => $row['CDW'] ?? null,
  2117. 'czlyq' => $row['czlyq'] ?? null,
  2118. 'NGZL' => $row['NGZL'] ?? null,
  2119. 'CDF' => $row['CDF'] ?? null,
  2120. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2121. 'MBZ' => $row['MBZ'] ?? null,
  2122. 'bwjg' => $row['bwjg'] ?? null,
  2123. 'iStatus' => $row['iStatus'] ?? null,
  2124. 'dStamp' => $row['dStamp'] ?? null,
  2125. 'dputrecord' => $row['dputrecord'] ?? null,
  2126. 'cywyxm' => $row['cywyxm'] ?? null,
  2127. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2128. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2129. ];
  2130. }
  2131. /**
  2132. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2133. *
  2134. * @return array{po:?array<string,mixed>, hidden:bool}
  2135. */
  2136. protected function resolvePickRowPoContext(int $sid): array
  2137. {
  2138. $po = null;
  2139. try {
  2140. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2141. if (is_array($found)) {
  2142. $po = $found;
  2143. }
  2144. } catch (\Throwable $e) {
  2145. }
  2146. $hideSet = $this->loadPickHiddenScydgySet();
  2147. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2148. }
  2149. /**
  2150. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2151. */
  2152. protected function assertPickRowCanDelete(int $sid, array $row): void
  2153. {
  2154. $ctx = $this->resolvePickRowPoContext($sid);
  2155. $po = $ctx['po'];
  2156. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2157. return;
  2158. }
  2159. if (is_array($po)) {
  2160. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2161. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2162. }
  2163. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2164. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2165. }
  2166. }
  2167. if ($ctx['hidden']) {
  2168. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2169. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2170. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2171. }
  2172. }
  2173. /**
  2174. * 初选直接完结前校验
  2175. */
  2176. protected function assertPickRowCanComplete(int $sid, array $row): void
  2177. {
  2178. $ctx = $this->resolvePickRowPoContext($sid);
  2179. $po = $ctx['po'];
  2180. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2181. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2182. }
  2183. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2184. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2185. }
  2186. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2187. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2188. }
  2189. }
  2190. /**
  2191. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2192. */
  2193. protected function softDeleteProcuremenPickRow(array $row): void
  2194. {
  2195. $sid = $this->extractScydgyRowId($row);
  2196. if (!$this->isValidScydgyRowId($sid)) {
  2197. throw new \InvalidArgumentException('无效的行主键');
  2198. }
  2199. $this->assertPickRowCanDelete($sid, $row);
  2200. $po = $this->resolvePickRowPoContext($sid)['po'];
  2201. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2202. return;
  2203. }
  2204. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2205. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2206. }
  2207. $now = date('Y-m-d H:i:s');
  2208. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2209. if (is_array($exists)) {
  2210. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2211. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2212. } else {
  2213. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2214. $data['mod_rq'] = $now;
  2215. $data['createtime'] = $now;
  2216. Db::table('purchase_order')->insert($data);
  2217. $poIdLog = (int)Db::getLastInsID();
  2218. }
  2219. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2220. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2221. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2222. if ($gymcLog !== '') {
  2223. $logTail .= ' / ' . $gymcLog;
  2224. }
  2225. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2226. }
  2227. /**
  2228. * 手工新增协助工序(写入 purchase_order)
  2229. *
  2230. * @param array<string, mixed> $params
  2231. * @return int scydgy_id
  2232. */
  2233. protected function saveManualPickOrder(array $params): int
  2234. {
  2235. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2236. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2237. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  2238. if ($ccydh === '') {
  2239. $ccydh = $this->allocateManualOrderCcydh();
  2240. }
  2241. $now = date('Y-m-d H:i:s');
  2242. $sid = $this->allocateManualScydgyId();
  2243. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2244. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2245. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2246. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2247. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2248. $data = [
  2249. 'scydgy_id' => $sid,
  2250. 'CCYDH' => $ccydh,
  2251. 'CYJMC' => $cyjmc,
  2252. 'CGYMC' => $cgymc,
  2253. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2254. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2255. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2256. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2257. 'cGzzxMc' => $supplierName,
  2258. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2259. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2260. 'notify_salesman' => $notifySalesman,
  2261. 'rfq_salesman_notified' => 0,
  2262. 'rfq_salesman_notify_time' => null,
  2263. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2264. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2265. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2266. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2267. 'createtime' => $now,
  2268. 'dStamp' => $now,
  2269. 'dputrecord' => $now,
  2270. ];
  2271. Db::table('purchase_order')->insert($data);
  2272. $poId = (int)Db::getLastInsID();
  2273. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2274. return $sid;
  2275. }
  2276. protected function formatProcuremenRowLabel(array $row): string
  2277. {
  2278. $dh = trim((string)($row['CCYDH'] ?? ''));
  2279. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2280. if ($dh !== '' && $gymc !== '') {
  2281. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2282. }
  2283. if ($dh !== '') {
  2284. return '订单「' . $dh . '」';
  2285. }
  2286. if ($gymc !== '') {
  2287. return '工序「' . $gymc . '」';
  2288. }
  2289. $id = $this->extractScydgyRowId($row);
  2290. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2291. }
  2292. /**
  2293. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2294. */
  2295. protected function extractScydgyRowId(array $row): int
  2296. {
  2297. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2298. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2299. return (int)$row['scydgy_id'];
  2300. }
  2301. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2302. return (int)$row['SCYDGY_ID'];
  2303. }
  2304. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2305. }
  2306. protected function isValidScydgyRowId(int $id): bool
  2307. {
  2308. return ProcuremenGuard::isValidScydgyId($id);
  2309. }
  2310. protected function isManualScydgyRowId(int $id): bool
  2311. {
  2312. return $id < 0;
  2313. }
  2314. /**
  2315. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2316. *
  2317. * @param int[] $scydgyIds
  2318. * @return array<int, string[]>
  2319. */
  2320. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2321. {
  2322. $out = [];
  2323. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2324. if ($scydgyIds === []) {
  2325. return $out;
  2326. }
  2327. try {
  2328. $rows = Db::table('purchase_order_detail')
  2329. ->where('scydgy_id', 'in', $scydgyIds)
  2330. ->field('scydgy_id,company_name')
  2331. ->order('company_name', 'asc')
  2332. ->select();
  2333. } catch (\Throwable $e) {
  2334. $rows = [];
  2335. }
  2336. if (!is_array($rows)) {
  2337. return $out;
  2338. }
  2339. foreach ($rows as $r) {
  2340. if (!is_array($r)) {
  2341. continue;
  2342. }
  2343. $sid = (int)($r['scydgy_id'] ?? 0);
  2344. $cn = trim((string)($r['company_name'] ?? ''));
  2345. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2346. continue;
  2347. }
  2348. if (!isset($out[$sid])) {
  2349. $out[$sid] = [];
  2350. }
  2351. if (!in_array($cn, $out[$sid], true)) {
  2352. $out[$sid][] = $cn;
  2353. }
  2354. }
  2355. return $out;
  2356. }
  2357. /**
  2358. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2359. *
  2360. * @param string[] $names
  2361. */
  2362. protected function formatNotifySupplierDisplay(array $names): string
  2363. {
  2364. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2365. return trim((string)$n);
  2366. }, $names))));
  2367. if ($names === []) {
  2368. return '';
  2369. }
  2370. sort($names, SORT_STRING);
  2371. return implode("\n", $names);
  2372. }
  2373. /**
  2374. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2375. *
  2376. * @param int[] $scydgyIds
  2377. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2378. */
  2379. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2380. {
  2381. $out = [];
  2382. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2383. if ($scydgyIds === []) {
  2384. return $out;
  2385. }
  2386. try {
  2387. $rows = Db::table('purchase_order_detail')
  2388. ->where('scydgy_id', 'in', $scydgyIds)
  2389. ->field('scydgy_id,company_name,amount')
  2390. ->select();
  2391. } catch (\Throwable $e) {
  2392. $rows = [];
  2393. }
  2394. if (!is_array($rows)) {
  2395. return $out;
  2396. }
  2397. foreach ($rows as $r) {
  2398. if (!is_array($r)) {
  2399. continue;
  2400. }
  2401. $sid = (int)($r['scydgy_id'] ?? 0);
  2402. $cn = trim((string)($r['company_name'] ?? ''));
  2403. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2404. continue;
  2405. }
  2406. if (!isset($out[$sid])) {
  2407. $out[$sid] = ['all' => [], 'quoted' => []];
  2408. }
  2409. $out[$sid]['all'][$cn] = true;
  2410. $am = trim((string)($r['amount'] ?? ''));
  2411. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2412. $out[$sid]['quoted'][$cn] = true;
  2413. }
  2414. }
  2415. return $out;
  2416. }
  2417. /**
  2418. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2419. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2420. */
  2421. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2422. {
  2423. $merged = ['all' => [], 'quoted' => []];
  2424. foreach ($buckets as $b) {
  2425. if (!is_array($b)) {
  2426. continue;
  2427. }
  2428. foreach ($b['all'] ?? [] as $cn => $_) {
  2429. $merged['all'][$cn] = true;
  2430. }
  2431. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2432. $merged['quoted'][$cn] = true;
  2433. }
  2434. }
  2435. return $merged;
  2436. }
  2437. /**
  2438. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2439. */
  2440. protected function formatQuotedSupplierLines(array $bucket): string
  2441. {
  2442. $all = array_keys($bucket['all'] ?? []);
  2443. if ($all === []) {
  2444. return '';
  2445. }
  2446. sort($all, SORT_STRING);
  2447. $lines = [];
  2448. foreach ($all as $cn) {
  2449. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2450. $lines[] = $cn . '(' . $status . ')';
  2451. }
  2452. return implode("\n", $lines);
  2453. }
  2454. /**
  2455. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2456. */
  2457. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2458. {
  2459. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2460. $this->view->engine->layout(false);
  2461. try {
  2462. $bodyHtml = $this->view->fetch($view);
  2463. $this->view->assign('dialogBody', $bodyHtml);
  2464. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2465. return $this->view->fetch('procuremen/dialog_lite_shell');
  2466. } finally {
  2467. if ($restoreLayout) {
  2468. $this->view->engine->layout($restoreLayout);
  2469. }
  2470. }
  2471. }
  2472. /**
  2473. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2474. */
  2475. protected function resolveBundleSysRq(array $bundle): string
  2476. {
  2477. foreach ($bundle['pos'] ?? [] as $po) {
  2478. if (!is_array($po)) {
  2479. continue;
  2480. }
  2481. $sr = trim((string)($po['sys_rq'] ?? ''));
  2482. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2483. return $sr;
  2484. }
  2485. }
  2486. return '';
  2487. }
  2488. /**
  2489. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2490. */
  2491. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2492. {
  2493. $raw = trim((string)$sysRq);
  2494. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2495. return true;
  2496. }
  2497. $ts = strtotime(str_replace('T', ' ', $raw));
  2498. if ($ts === false || $ts <= 0) {
  2499. return true;
  2500. }
  2501. return time() >= $ts;
  2502. }
  2503. /**
  2504. * 开标前校验:必须已过报价截止时间
  2505. *
  2506. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2507. */
  2508. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2509. {
  2510. $sysRq = $this->resolveBundleSysRq($bundle);
  2511. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2512. $this->error('未到招标截止日期');
  2513. }
  2514. }
  2515. /**
  2516. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2517. *
  2518. * @param array<string, mixed> $d
  2519. * @param string $deliveryYmd
  2520. */
  2521. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2522. {
  2523. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2524. return max(0, (int)$d['lead_days']);
  2525. }
  2526. if ($deliveryYmd === '') {
  2527. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2528. }
  2529. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2530. return null;
  2531. }
  2532. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2533. $t2 = strtotime($m[1] . ' 00:00:00');
  2534. if ($t1 === false || $t2 === false) {
  2535. return null;
  2536. }
  2537. return max(0, (int)round(($t2 - $t1) / 86400));
  2538. }
  2539. /**
  2540. * @param int|null $days
  2541. */
  2542. protected function formatProcuremenLeadDaysText($days): string
  2543. {
  2544. if ($days === null || $days === '') {
  2545. return '未填写';
  2546. }
  2547. if (!is_numeric($days)) {
  2548. return '未填写';
  2549. }
  2550. return ((int)$days) . '天';
  2551. }
  2552. /**
  2553. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2554. *
  2555. * @param array<string, mixed> $line
  2556. */
  2557. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2558. {
  2559. $amountFilled = !empty($line['amount_filled']);
  2560. $deliveryFilled = !empty($line['delivery_filled']);
  2561. $leadFilled = !empty($line['lead_days_filled']);
  2562. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2563. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2564. $line['amount_show'] = '';
  2565. if (array_key_exists('amount_text', $line)) {
  2566. $line['amount_text'] = $line['unit_price_text'];
  2567. }
  2568. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2569. $line['delivery_show'] = $deliveryText;
  2570. if (array_key_exists('delivery_text', $line)) {
  2571. $line['delivery_text'] = $deliveryText;
  2572. }
  2573. $line['delivery_ymd'] = '';
  2574. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2575. $line['lead_days_show'] = $leadText;
  2576. $line['lead_days_text'] = $leadText;
  2577. $line['lead_days'] = '';
  2578. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2579. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2580. $line['subtotal_num'] = null;
  2581. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2582. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2583. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2584. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2585. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2586. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2587. $line['amount_filled'] = false;
  2588. $line['delivery_filled'] = false;
  2589. $line['lead_days_filled'] = false;
  2590. $line['is_quoted'] = false;
  2591. if (array_key_exists('quote_label', $line)) {
  2592. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2593. }
  2594. }
  2595. protected function ensurePurchaseOrderBidOpenTable(): void
  2596. {
  2597. static $ready = false;
  2598. if ($ready) {
  2599. return;
  2600. }
  2601. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2602. try {
  2603. if (Cache::get($cacheKey)) {
  2604. $ready = true;
  2605. return;
  2606. }
  2607. } catch (\Throwable $e) {
  2608. }
  2609. try {
  2610. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2611. $ready = true;
  2612. try {
  2613. Cache::set($cacheKey, 1, 86400);
  2614. } catch (\Throwable $e) {
  2615. }
  2616. } catch (\Throwable $e) {
  2617. Db::execute(
  2618. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2619. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2620. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2621. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2622. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2623. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2624. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2625. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2626. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2627. `createtime` datetime DEFAULT NULL,
  2628. PRIMARY KEY (`id`),
  2629. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2630. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2631. );
  2632. $ready = true;
  2633. try {
  2634. Cache::set($cacheKey, 1, 86400);
  2635. } catch (\Throwable $e2) {
  2636. }
  2637. }
  2638. }
  2639. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2640. {
  2641. $ccydh = trim($ccydh);
  2642. if ($ccydh === '') {
  2643. return false;
  2644. }
  2645. $this->ensurePurchaseOrderBidOpenTable();
  2646. try {
  2647. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2648. return is_array($row);
  2649. } catch (\Throwable $e) {
  2650. return false;
  2651. }
  2652. }
  2653. /**
  2654. * 批量查询订单是否已开标验证
  2655. *
  2656. * @param array<int, string> $ccydhs
  2657. * @return array<string, bool> ccydh => true
  2658. */
  2659. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2660. {
  2661. $set = [];
  2662. $list = [];
  2663. foreach ($ccydhs as $c) {
  2664. $c = trim((string)$c);
  2665. if ($c !== '') {
  2666. $list[$c] = true;
  2667. }
  2668. }
  2669. if ($list === []) {
  2670. return $set;
  2671. }
  2672. $this->ensurePurchaseOrderBidOpenTable();
  2673. try {
  2674. $rows = Db::table('purchase_order_bid_open')
  2675. ->where('ccydh', 'in', array_keys($list))
  2676. ->field('ccydh')
  2677. ->select();
  2678. foreach ($rows as $row) {
  2679. if (!is_array($row)) {
  2680. continue;
  2681. }
  2682. $c = trim((string)($row['ccydh'] ?? ''));
  2683. if ($c !== '') {
  2684. $set[$c] = true;
  2685. }
  2686. }
  2687. } catch (\Throwable $e) {
  2688. return [];
  2689. }
  2690. return $set;
  2691. }
  2692. /**
  2693. * 批量查询订单是否已指定供应商(免开标)
  2694. *
  2695. * @param array<int, string> $ccydhs
  2696. * @return array<string, bool> ccydh => true
  2697. */
  2698. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2699. {
  2700. $set = [];
  2701. $list = [];
  2702. foreach ($ccydhs as $c) {
  2703. $c = trim((string)$c);
  2704. if ($c !== '') {
  2705. $list[$c] = true;
  2706. }
  2707. }
  2708. if ($list === []) {
  2709. return $set;
  2710. }
  2711. $this->ensurePurchaseOrderManualPickColumns();
  2712. try {
  2713. $rows = Db::table('purchase_order')
  2714. ->where('CCYDH', 'in', array_keys($list))
  2715. ->where('manual_pick', 1)
  2716. ->field('CCYDH')
  2717. ->select();
  2718. foreach ($rows as $row) {
  2719. if (!is_array($row)) {
  2720. continue;
  2721. }
  2722. $c = trim((string)($row['CCYDH'] ?? ''));
  2723. if ($c !== '') {
  2724. $set[$c] = true;
  2725. }
  2726. }
  2727. } catch (\Throwable $e) {
  2728. return [];
  2729. }
  2730. return $set;
  2731. }
  2732. /**
  2733. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2734. *
  2735. * @param array<int, array<string, mixed>> $pool
  2736. * @return array<int, array<string, mixed>>
  2737. */
  2738. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2739. {
  2740. $status = trim($status);
  2741. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2742. return $pool;
  2743. }
  2744. $ccydhList = [];
  2745. foreach ($pool as $rw) {
  2746. if (!is_array($rw)) {
  2747. continue;
  2748. }
  2749. $c = trim((string)($rw['CCYDH'] ?? ''));
  2750. if ($c !== '') {
  2751. $ccydhList[] = $c;
  2752. }
  2753. }
  2754. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2755. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2756. $out = [];
  2757. foreach ($pool as $rw) {
  2758. if (!is_array($rw)) {
  2759. continue;
  2760. }
  2761. $c = trim((string)($rw['CCYDH'] ?? ''));
  2762. if ($c !== '' && isset($bidOpenSet[$c])) {
  2763. $t = '已开标';
  2764. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2765. $t = '已指定供应商';
  2766. } else {
  2767. $t = '待开标';
  2768. }
  2769. if ($t === $status) {
  2770. $out[] = $rw;
  2771. }
  2772. }
  2773. return $out;
  2774. }
  2775. /**
  2776. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2777. *
  2778. * @param array<string, mixed> $group
  2779. */
  2780. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2781. {
  2782. if ($quoteVisible) {
  2783. $group['remark_quote_pending'] = 0;
  2784. return;
  2785. }
  2786. $group['remark'] = '';
  2787. $group['remark_quote_pending'] = 0;
  2788. }
  2789. /**
  2790. * @param array{ccydh?:string} $bundle
  2791. */
  2792. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2793. {
  2794. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2795. }
  2796. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2797. {
  2798. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2799. return true;
  2800. }
  2801. return $this->isProcuremenManualPickedForBundle($bundle);
  2802. }
  2803. /**
  2804. * 确保 purchase_order 自选供应商字段
  2805. */
  2806. protected function ensurePurchaseOrderManualPickColumns(): void
  2807. {
  2808. static $done = false;
  2809. if ($done) {
  2810. return;
  2811. }
  2812. $done = true;
  2813. $adds = [
  2814. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2815. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2816. ];
  2817. foreach ($adds as $col => $ddl) {
  2818. try {
  2819. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2820. if (!is_array($cols) || $cols === []) {
  2821. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2822. }
  2823. } catch (\Throwable $e) {
  2824. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2825. }
  2826. }
  2827. }
  2828. /**
  2829. * 是否已自选供应商(免开标查看报价)
  2830. *
  2831. * @param array{pos?:array} $bundle
  2832. */
  2833. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2834. {
  2835. $this->ensurePurchaseOrderManualPickColumns();
  2836. foreach ($bundle['pos'] ?? [] as $poRow) {
  2837. if (!is_array($poRow)) {
  2838. continue;
  2839. }
  2840. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2841. return true;
  2842. }
  2843. }
  2844. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2845. if ($ccydh === '') {
  2846. return false;
  2847. }
  2848. try {
  2849. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2850. return $v !== null && $v !== false && (int)$v > 0;
  2851. } catch (\Throwable $e) {
  2852. return false;
  2853. }
  2854. }
  2855. /**
  2856. * @param array{pos?:array} $bundle
  2857. * @return array{company:string,reason:string}
  2858. */
  2859. protected function resolveProcuremenManualPickInfo(array $bundle): array
  2860. {
  2861. $this->ensurePurchaseOrderManualPickColumns();
  2862. foreach ($bundle['pos'] ?? [] as $poRow) {
  2863. if (!is_array($poRow)) {
  2864. continue;
  2865. }
  2866. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  2867. continue;
  2868. }
  2869. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  2870. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  2871. return ['company' => $cn, 'reason' => $reason];
  2872. }
  2873. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2874. if ($ccydh === '') {
  2875. return ['company' => '', 'reason' => ''];
  2876. }
  2877. try {
  2878. $row = Db::table('purchase_order')
  2879. ->where('CCYDH', $ccydh)
  2880. ->where('manual_pick', 1)
  2881. ->field('pick_company_name,manual_pick_reason')
  2882. ->order('id', 'asc')
  2883. ->find();
  2884. } catch (\Throwable $e) {
  2885. $row = null;
  2886. }
  2887. if (!is_array($row)) {
  2888. return ['company' => '', 'reason' => ''];
  2889. }
  2890. return [
  2891. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  2892. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  2893. ];
  2894. }
  2895. protected function loadBidOpenAdminUser(int $adminId): ?array
  2896. {
  2897. if ($adminId <= 0) {
  2898. return null;
  2899. }
  2900. try {
  2901. $row = Db::name('admin')->where('id', $adminId)->find();
  2902. } catch (\Throwable $e) {
  2903. return null;
  2904. }
  2905. if (!is_array($row)) {
  2906. return null;
  2907. }
  2908. $status = strtolower(trim((string)($row['status'] ?? '')));
  2909. if ($status !== '' && $status !== 'normal') {
  2910. return null;
  2911. }
  2912. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2913. return null;
  2914. }
  2915. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2916. if (!preg_match('/^1\d{10}$/', $phone)) {
  2917. return null;
  2918. }
  2919. $name = trim((string)($row['nickname'] ?? ''));
  2920. if ($name === '') {
  2921. $name = trim((string)($row['username'] ?? ''));
  2922. }
  2923. return [
  2924. 'id' => (int)$row['id'],
  2925. 'username' => trim((string)($row['username'] ?? '')),
  2926. 'nickname' => $name,
  2927. 'mobile' => $phone,
  2928. ];
  2929. }
  2930. /**
  2931. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2932. */
  2933. protected function bidOpenVerifierAuthGroupRootId(): int
  2934. {
  2935. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2936. return $id > 0 ? $id : 10;
  2937. }
  2938. /**
  2939. * @return int[]
  2940. */
  2941. protected function loadBidOpenVerifierAuthGroupIds(): array
  2942. {
  2943. static $memo = [];
  2944. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2945. if (isset($memo[$rootId])) {
  2946. return $memo[$rootId];
  2947. }
  2948. try {
  2949. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2950. } catch (\Throwable $e) {
  2951. $memo[$rootId] = [$rootId];
  2952. return $memo[$rootId];
  2953. }
  2954. if (!is_array($groups) || $groups === []) {
  2955. $memo[$rootId] = [$rootId];
  2956. return $memo[$rootId];
  2957. }
  2958. $groupList = [];
  2959. foreach ($groups as $g) {
  2960. if (is_array($g)) {
  2961. $groupList[] = $g;
  2962. }
  2963. }
  2964. if ($groupList === []) {
  2965. $memo[$rootId] = [$rootId];
  2966. return $memo[$rootId];
  2967. }
  2968. $tree = \fast\Tree::instance();
  2969. $tree->init($groupList);
  2970. $ids = $tree->getChildrenIds($rootId, true);
  2971. if (!is_array($ids) || $ids === []) {
  2972. $memo[$rootId] = [$rootId];
  2973. return $memo[$rootId];
  2974. }
  2975. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2976. return $memo[$rootId];
  2977. }
  2978. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2979. {
  2980. if ($adminId <= 0) {
  2981. return false;
  2982. }
  2983. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2984. if ($groupIds === []) {
  2985. return false;
  2986. }
  2987. try {
  2988. return (bool)Db::name('auth_group_access')
  2989. ->where('uid', $adminId)
  2990. ->where('group_id', 'in', $groupIds)
  2991. ->count();
  2992. } catch (\Throwable $e) {
  2993. return false;
  2994. }
  2995. }
  2996. /**
  2997. * @return array<int, array<string, mixed>>
  2998. */
  2999. protected function listBidOpenVerifierCandidates(): array
  3000. {
  3001. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3002. if ($groupIds === []) {
  3003. return [];
  3004. }
  3005. try {
  3006. $adminIds = Db::name('auth_group_access')
  3007. ->where('group_id', 'in', $groupIds)
  3008. ->column('uid');
  3009. } catch (\Throwable $e) {
  3010. $adminIds = [];
  3011. }
  3012. $adminIds = is_array($adminIds)
  3013. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3014. : [];
  3015. if ($adminIds === []) {
  3016. return [];
  3017. }
  3018. try {
  3019. $rows = Db::name('admin')
  3020. ->where('status', 'normal')
  3021. ->where('id', 'in', $adminIds)
  3022. ->where('mobile', '<>', '')
  3023. ->order('id', 'asc')
  3024. ->select();
  3025. } catch (\Throwable $e) {
  3026. return [];
  3027. }
  3028. if (!is_array($rows)) {
  3029. return [];
  3030. }
  3031. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3032. $out = [];
  3033. foreach ($rows as $row) {
  3034. if (!is_array($row)) {
  3035. continue;
  3036. }
  3037. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3038. if ($one === null) {
  3039. continue;
  3040. }
  3041. $out[] = [
  3042. 'id' => $one['id'],
  3043. 'username' => $one['username'],
  3044. 'nickname' => $one['nickname'],
  3045. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3046. 'mobile' => mask_phone($one['mobile']),
  3047. 'mobile_plain' => (string)$one['mobile'],
  3048. ];
  3049. }
  3050. return $out;
  3051. }
  3052. /**
  3053. * @param int[] $adminIds
  3054. * @return array<int, string>
  3055. */
  3056. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3057. {
  3058. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3059. if ($adminIds === []) {
  3060. return [];
  3061. }
  3062. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3063. try {
  3064. $rows = Db::name('auth_group_access')
  3065. ->alias('aga')
  3066. ->join('auth_group ag', 'aga.group_id = ag.id')
  3067. ->where('aga.uid', 'in', $adminIds)
  3068. ->where('aga.group_id', 'in', $groupIds)
  3069. ->field('aga.uid,ag.name')
  3070. ->order('aga.uid', 'asc')
  3071. ->order('aga.group_id', 'asc')
  3072. ->select();
  3073. } catch (\Throwable $e) {
  3074. return [];
  3075. }
  3076. if (!is_array($rows)) {
  3077. return [];
  3078. }
  3079. $out = [];
  3080. foreach ($rows as $row) {
  3081. if (!is_array($row)) {
  3082. continue;
  3083. }
  3084. $uid = (int)($row['uid'] ?? 0);
  3085. $name = trim((string)($row['name'] ?? ''));
  3086. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3087. continue;
  3088. }
  3089. $out[$uid] = $name;
  3090. }
  3091. return $out;
  3092. }
  3093. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3094. {
  3095. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3096. }
  3097. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3098. {
  3099. return 'procuremen_bidopen_wait_' . $adminId;
  3100. }
  3101. protected function renderBidOpenVerifySms(string $code): string
  3102. {
  3103. $tpl = '';
  3104. try {
  3105. $row = $this->loadNotifyTemplateRow('bid_open');
  3106. if (is_array($row)) {
  3107. $tpl = trim((string)($row['content'] ?? ''));
  3108. }
  3109. } catch (\Throwable $e) {
  3110. $tpl = '';
  3111. }
  3112. if ($tpl === '') {
  3113. $tpl = '【可集达】您的短信验证码是{code}';
  3114. }
  3115. return str_replace('{code}', $code, $tpl);
  3116. }
  3117. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3118. {
  3119. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3120. }
  3121. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3122. {
  3123. $code = trim($code);
  3124. if (!preg_match('/^\d{6}$/', $code)) {
  3125. return false;
  3126. }
  3127. $mock = Config::get('mproc.mock_sms_code');
  3128. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3129. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3130. return true;
  3131. }
  3132. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3133. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3134. return false;
  3135. }
  3136. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3137. return true;
  3138. }
  3139. /**
  3140. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3141. */
  3142. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3143. {
  3144. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3145. if ($ccydh === '') {
  3146. throw new \InvalidArgumentException('订单号无效');
  3147. }
  3148. $this->ensurePurchaseOrderBidOpenTable();
  3149. list($operatorId, $operatorName) = $this->GetUseName();
  3150. $now = date('Y-m-d H:i:s');
  3151. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3152. $payload = [
  3153. 'ccydh' => $ccydh,
  3154. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3155. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3156. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3157. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3158. 'operator_id' => (int)$operatorId,
  3159. 'operator_name' => trim((string)$operatorName),
  3160. 'createtime' => $now,
  3161. ];
  3162. if (is_array($exists)) {
  3163. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3164. } else {
  3165. Db::table('purchase_order_bid_open')->insert($payload);
  3166. }
  3167. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3168. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3169. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3170. (int)$payload['verifier1_id'],
  3171. (int)$payload['verifier2_id'],
  3172. ]);
  3173. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3174. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3175. }
  3176. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3177. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3178. }
  3179. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3180. $seenSid = [];
  3181. foreach ($bundle['pos'] ?? [] as $poRow) {
  3182. if (!is_array($poRow)) {
  3183. continue;
  3184. }
  3185. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3186. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3187. continue;
  3188. }
  3189. $seenSid[$sid] = true;
  3190. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3191. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3192. }
  3193. if ($seenSid === []) {
  3194. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3195. if ($this->isValidScydgyRowId($anchor)) {
  3196. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3197. }
  3198. }
  3199. // 开标通过后计算并写入供应商服务评分
  3200. try {
  3201. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3202. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3203. } catch (\Throwable $e) {
  3204. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3205. }
  3206. }
  3207. /**
  3208. * 报价行展示字段默认值(模板安全访问)
  3209. *
  3210. * @param array<string, mixed> $line
  3211. * @return array<string, mixed>
  3212. */
  3213. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3214. {
  3215. if (!array_key_exists('amount_quote_pending', $line)) {
  3216. $line['amount_quote_pending'] = 0;
  3217. }
  3218. if (!array_key_exists('delivery_quote_pending', $line)) {
  3219. $line['delivery_quote_pending'] = 0;
  3220. }
  3221. if (!array_key_exists('quote_before_deadline', $line)) {
  3222. $line['quote_before_deadline'] = 0;
  3223. }
  3224. if (!array_key_exists('amount_filled', $line)) {
  3225. $line['amount_filled'] = 0;
  3226. }
  3227. if (!array_key_exists('delivery_filled', $line)) {
  3228. $line['delivery_filled'] = 0;
  3229. }
  3230. if (!array_key_exists('lead_days_filled', $line)) {
  3231. $line['lead_days_filled'] = 0;
  3232. }
  3233. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3234. $line['lead_days_quote_pending'] = 0;
  3235. }
  3236. if (!array_key_exists('lead_days_show', $line)) {
  3237. $line['lead_days_show'] = '未填写';
  3238. }
  3239. if (!array_key_exists('lead_days_text', $line)) {
  3240. $line['lead_days_text'] = $line['lead_days_show'];
  3241. }
  3242. return $line;
  3243. }
  3244. /**
  3245. * 审核弹窗:按供应商汇总报价明细
  3246. *
  3247. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3248. * @return array<int, array<string, mixed>>
  3249. */
  3250. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3251. {
  3252. $sids = [];
  3253. foreach ($bundle['pos'] ?? [] as $po) {
  3254. if (!is_array($po)) {
  3255. continue;
  3256. }
  3257. $sid = (int)($po['scydgy_id'] ?? 0);
  3258. if ($this->isValidScydgyRowId($sid)) {
  3259. $sids[$sid] = true;
  3260. }
  3261. }
  3262. if ($sids === []) {
  3263. return [];
  3264. }
  3265. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3266. $gymcMap = [];
  3267. $qtyBySid = [];
  3268. $orderedSids = [];
  3269. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3270. if (!is_array($mr)) {
  3271. continue;
  3272. }
  3273. $gid = $this->extractScydgyRowId($mr);
  3274. if ($this->isValidScydgyRowId($gid)) {
  3275. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3276. $orderedSids[] = $gid;
  3277. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3278. if ($qty === '') {
  3279. $qty = trim((string)($mr['NGZL'] ?? ''));
  3280. }
  3281. $qtyBySid[$gid] = $qty;
  3282. }
  3283. }
  3284. foreach ($bundle['pos'] ?? [] as $po) {
  3285. if (!is_array($po)) {
  3286. continue;
  3287. }
  3288. $gid = (int)($po['scydgy_id'] ?? 0);
  3289. if ($this->isValidScydgyRowId($gid)) {
  3290. $nm = trim((string)($po['CGYMC'] ?? ''));
  3291. if ($nm !== '') {
  3292. $gymcMap[$gid] = $nm;
  3293. }
  3294. if (!in_array($gid, $orderedSids, true)) {
  3295. $orderedSids[] = $gid;
  3296. }
  3297. }
  3298. }
  3299. try {
  3300. $detailsQuery = Db::table('purchase_order_detail')
  3301. ->where('scydgy_id', 'in', array_keys($sids));
  3302. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3303. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3304. } catch (\Throwable $e) {
  3305. try {
  3306. $detailsQuery = Db::table('purchase_order_detail')
  3307. ->where('scydgy_id', 'in', array_keys($sids));
  3308. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3309. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3310. } catch (\Throwable $e2) {
  3311. $details = [];
  3312. }
  3313. }
  3314. if (!is_array($details)) {
  3315. $details = [];
  3316. }
  3317. $byCompany = [];
  3318. foreach ($details as $d) {
  3319. if (!is_array($d)) {
  3320. continue;
  3321. }
  3322. $cn = trim((string)($d['company_name'] ?? ''));
  3323. if ($cn === '') {
  3324. continue;
  3325. }
  3326. if (!isset($byCompany[$cn])) {
  3327. $ph = trim((string)($d['phone'] ?? ''));
  3328. $username = trim((string)($d['username'] ?? ''));
  3329. if ($username === '') {
  3330. $username = $this->resolveCustomerContactName($ph, $cn);
  3331. }
  3332. $byCompany[$cn] = [
  3333. 'name' => $cn,
  3334. 'email' => trim((string)($d['email'] ?? '')),
  3335. 'phone' => $ph,
  3336. 'username' => $username,
  3337. 'remark' => '',
  3338. 'has_quote' => false,
  3339. 'lines_map' => [],
  3340. ];
  3341. }
  3342. if ($byCompany[$cn]['remark'] === '') {
  3343. $rm = '';
  3344. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3345. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3346. $rm = trim((string)$d[$rk]);
  3347. break;
  3348. }
  3349. }
  3350. if ($rm !== '') {
  3351. $byCompany[$cn]['remark'] = $rm;
  3352. }
  3353. }
  3354. $sid = (int)($d['scydgy_id'] ?? 0);
  3355. $am = trim((string)($d['amount'] ?? ''));
  3356. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3357. if ($gymc === '') {
  3358. $gymc = '工序';
  3359. }
  3360. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3361. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3362. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3363. $deliveryShow = $deliveryRaw;
  3364. }
  3365. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3366. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3367. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3368. $subtotal = null;
  3369. if ($amountNum !== null) {
  3370. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3371. }
  3372. $unitPriceText = $amountFilled
  3373. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3374. : '未填写';
  3375. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3376. $leadFilled = ($leadDays !== null);
  3377. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3378. $lineRow = [
  3379. 'cgymc' => $gymc,
  3380. 'amount' => $am,
  3381. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3382. 'amount_filled' => $amountFilled,
  3383. 'unit_price_text' => $unitPriceText,
  3384. 'delivery' => $deliveryRaw,
  3385. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3386. 'delivery_filled' => $deliveryFilled,
  3387. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3388. 'lead_days' => $leadFilled ? $leadDays : '',
  3389. 'lead_days_filled'=> $leadFilled,
  3390. 'lead_days_show' => $leadText,
  3391. 'lead_days_text' => $leadText,
  3392. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3393. 'subtotal_num' => $subtotal,
  3394. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3395. 'is_quoted' => $amountFilled,
  3396. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3397. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3398. ];
  3399. if (!$quoteVisible) {
  3400. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3401. }
  3402. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3403. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3404. }
  3405. foreach ($byCompany as $cn => $g) {
  3406. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3407. $lines = [];
  3408. $usedSids = [];
  3409. foreach ($orderedSids as $sid) {
  3410. if (!isset($linesMap[$sid])) {
  3411. continue;
  3412. }
  3413. $lines[] = $linesMap[$sid];
  3414. $usedSids[$sid] = true;
  3415. }
  3416. foreach ($linesMap as $sid => $ln) {
  3417. if (isset($usedSids[$sid])) {
  3418. continue;
  3419. }
  3420. $lines[] = $ln;
  3421. }
  3422. $total = count($lines);
  3423. $quoted = 0;
  3424. $groupTotal = 0.0;
  3425. $groupHasTotal = false;
  3426. if ($quoteVisible) {
  3427. foreach ($lines as $ln) {
  3428. $am = trim((string)($ln['amount'] ?? ''));
  3429. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3430. $quoted++;
  3431. }
  3432. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3433. $groupTotal += (float)$ln['subtotal_num'];
  3434. $groupHasTotal = true;
  3435. }
  3436. }
  3437. }
  3438. unset($byCompany[$cn]['lines_map']);
  3439. $byCompany[$cn]['lines'] = $lines;
  3440. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3441. $byCompany[$cn]['line_count'] = $total;
  3442. $byCompany[$cn]['has_total'] = $total > 0;
  3443. $byCompany[$cn]['has_remark'] = $total > 0;
  3444. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3445. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3446. // 工序行 + 备注行 + 总计行
  3447. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3448. }
  3449. $groups = array_values($byCompany);
  3450. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3451. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3452. }
  3453. /**
  3454. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3455. *
  3456. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3457. * @return array<int, array<string, mixed>>
  3458. */
  3459. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3460. {
  3461. $sids = [];
  3462. $poIdMap = [];
  3463. foreach ($bundle['pos'] ?? [] as $po) {
  3464. if (!is_array($po)) {
  3465. continue;
  3466. }
  3467. $sid = (int)($po['scydgy_id'] ?? 0);
  3468. if ($this->isValidScydgyRowId($sid)) {
  3469. $sids[$sid] = true;
  3470. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3471. }
  3472. }
  3473. if ($sids === []) {
  3474. return [];
  3475. }
  3476. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3477. $gymcMap = [];
  3478. $qtyBySid = [];
  3479. $orderedSids = [];
  3480. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3481. if (!is_array($mr)) {
  3482. continue;
  3483. }
  3484. $gid = $this->extractScydgyRowId($mr);
  3485. if ($this->isValidScydgyRowId($gid)) {
  3486. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3487. $orderedSids[] = $gid;
  3488. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3489. if ($qty === '') {
  3490. $qty = trim((string)($mr['NGZL'] ?? ''));
  3491. }
  3492. $qtyBySid[$gid] = $qty;
  3493. }
  3494. }
  3495. foreach ($bundle['pos'] ?? [] as $po) {
  3496. if (!is_array($po)) {
  3497. continue;
  3498. }
  3499. $gid = (int)($po['scydgy_id'] ?? 0);
  3500. if ($this->isValidScydgyRowId($gid)) {
  3501. $nm = trim((string)($po['CGYMC'] ?? ''));
  3502. if ($nm !== '') {
  3503. $gymcMap[$gid] = $nm;
  3504. }
  3505. }
  3506. }
  3507. try {
  3508. $details = Db::table('purchase_order_detail')
  3509. ->where('scydgy_id', 'in', array_keys($sids))
  3510. ->order('company_name', 'asc')
  3511. ->order('id', 'asc')
  3512. ->select();
  3513. } catch (\Throwable $e) {
  3514. try {
  3515. $details = Db::table('purchase_order_detail')
  3516. ->where('scydgy_id', 'in', array_keys($sids))
  3517. ->order('company_name', 'asc')
  3518. ->order('ID', 'asc')
  3519. ->select();
  3520. } catch (\Throwable $e2) {
  3521. $details = [];
  3522. }
  3523. }
  3524. if (!is_array($details)) {
  3525. $details = [];
  3526. }
  3527. $byCompany = [];
  3528. foreach ($details as $d) {
  3529. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3530. continue;
  3531. }
  3532. $cn = trim((string)($d['company_name'] ?? ''));
  3533. if ($cn === '') {
  3534. continue;
  3535. }
  3536. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3537. $sid = (int)($d['scydgy_id'] ?? 0);
  3538. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3539. continue;
  3540. }
  3541. if (!isset($byCompany[$cn])) {
  3542. $ph = trim((string)($d['phone'] ?? ''));
  3543. $username = trim((string)($d['username'] ?? ''));
  3544. if ($username === '') {
  3545. $username = $this->resolveCustomerContactName($ph, $cn);
  3546. }
  3547. $byCompany[$cn] = [
  3548. 'name' => $cn,
  3549. 'email' => trim((string)($d['email'] ?? '')),
  3550. 'phone' => $ph,
  3551. 'username' => $username,
  3552. 'remark' => '',
  3553. 'pick_lines' => [],
  3554. 'detail_picks' => [],
  3555. ];
  3556. }
  3557. if ($byCompany[$cn]['remark'] === '') {
  3558. $rm = '';
  3559. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3560. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3561. $rm = trim((string)$d[$rk]);
  3562. break;
  3563. }
  3564. }
  3565. if ($rm !== '') {
  3566. $byCompany[$cn]['remark'] = $rm;
  3567. }
  3568. }
  3569. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3570. if ($gymc === '') {
  3571. $gymc = '工序';
  3572. }
  3573. $am = trim((string)($d['amount'] ?? ''));
  3574. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3575. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3576. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3577. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3578. $deliveryShow = $deliveryRaw;
  3579. }
  3580. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3581. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3582. $subtotal = null;
  3583. if ($amountNum !== null) {
  3584. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3585. }
  3586. $unitPriceText = $amountFilled
  3587. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3588. : '未填写';
  3589. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3590. $leadFilled = ($leadDays !== null);
  3591. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3592. $pickLine = [
  3593. 'cgymc' => $gymc,
  3594. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3595. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3596. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3597. 'amount_filled' => $amountFilled,
  3598. 'delivery_filled' => $deliveryFilled,
  3599. 'unit_price_text' => $unitPriceText,
  3600. 'lead_days' => $leadFilled ? $leadDays : '',
  3601. 'lead_days_filled'=> $leadFilled,
  3602. 'lead_days_show' => $leadText,
  3603. 'lead_days_text' => $leadText,
  3604. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3605. 'subtotal_num' => $subtotal,
  3606. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3607. 'is_quoted' => $amountFilled,
  3608. ];
  3609. if (!$quoteVisible) {
  3610. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3611. }
  3612. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3613. $byCompany[$cn]['detail_picks'][$sid] = [
  3614. 'scydgy_id' => $sid,
  3615. 'detail_id' => $detailId,
  3616. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3617. 'cgymc' => $gymc,
  3618. ];
  3619. }
  3620. $out = [];
  3621. foreach ($byCompany as $g) {
  3622. $pickLinesMap = $g['pick_lines'] ?? [];
  3623. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3624. continue;
  3625. }
  3626. $pickLines = [];
  3627. $usedLineSids = [];
  3628. foreach ($orderedSids as $sid) {
  3629. if (!isset($pickLinesMap[$sid])) {
  3630. continue;
  3631. }
  3632. $pickLines[] = $pickLinesMap[$sid];
  3633. $usedLineSids[$sid] = true;
  3634. }
  3635. foreach ($pickLinesMap as $sid => $ln) {
  3636. if (isset($usedLineSids[$sid])) {
  3637. continue;
  3638. }
  3639. $pickLines[] = $ln;
  3640. }
  3641. $groupTotal = 0.0;
  3642. $groupHasTotal = false;
  3643. if ($quoteVisible) {
  3644. foreach ($pickLines as $ln) {
  3645. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3646. $groupTotal += (float)$ln['subtotal_num'];
  3647. $groupHasTotal = true;
  3648. }
  3649. }
  3650. }
  3651. $lineCount = count($pickLines);
  3652. $g['pick_lines'] = $pickLines;
  3653. $g['line_count'] = $lineCount;
  3654. $g['has_total'] = $lineCount > 0;
  3655. $g['has_remark'] = $lineCount > 0;
  3656. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3657. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3658. // 工序行 + 备注行 + 总计行
  3659. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3660. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3661. $detailPicks = [];
  3662. $usedPickSids = [];
  3663. foreach ($orderedSids as $sid) {
  3664. if (!isset($detailPicksMap[$sid])) {
  3665. continue;
  3666. }
  3667. $detailPicks[] = $detailPicksMap[$sid];
  3668. $usedPickSids[$sid] = true;
  3669. }
  3670. foreach ($detailPicksMap as $sid => $dp) {
  3671. if (isset($usedPickSids[$sid])) {
  3672. continue;
  3673. }
  3674. $detailPicks[] = $dp;
  3675. }
  3676. $g['detail_picks'] = $detailPicks;
  3677. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3678. unset($g['detail_picks']);
  3679. $out[] = $g;
  3680. }
  3681. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3682. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3683. }
  3684. /**
  3685. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3686. * @return array<int, int[]> scydgy_id => detail_id[]
  3687. */
  3688. protected function mapDetailIdsByScydgyId(array $details): array
  3689. {
  3690. $out = [];
  3691. foreach ($details as $d) {
  3692. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3693. continue;
  3694. }
  3695. $sid = (int)($d['scydgy_id'] ?? 0);
  3696. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3697. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3698. continue;
  3699. }
  3700. if (!isset($out[$sid])) {
  3701. $out[$sid] = [];
  3702. }
  3703. $out[$sid][] = $pk;
  3704. }
  3705. foreach ($out as $sid => $ids) {
  3706. $out[$sid] = array_values(array_unique($ids));
  3707. }
  3708. return $out;
  3709. }
  3710. /**
  3711. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3712. *
  3713. * @param array<string, mixed> $dbRow
  3714. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3715. */
  3716. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3717. {
  3718. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3719. $r = [
  3720. 'ID' => $sid,
  3721. 'scydgy_id' => $sid,
  3722. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3723. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3724. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3725. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3726. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3727. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3728. 'CDW' => $dbRow['CDW'] ?? '',
  3729. 'czlyq' => $dbRow['czlyq'] ?? '',
  3730. 'NGZL' => $dbRow['NGZL'] ?? '',
  3731. 'CDF' => $dbRow['CDF'] ?? '',
  3732. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3733. 'MBZ' => $dbRow['MBZ'] ?? '',
  3734. 'bwjg' => $dbRow['bwjg'] ?? '',
  3735. 'iStatus' => $dbRow['iStatus'] ?? '',
  3736. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3737. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3738. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3739. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3740. 'dStamp' => $dbRow['dStamp'] ?? '',
  3741. 'pick_time' => $dbRow['pick_time'] ?? '',
  3742. ];
  3743. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3744. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3745. if ($sid > 0 && isset($dStampMap[$sid])) {
  3746. $t = trim((string)$dStampMap[$sid]);
  3747. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3748. $r['dStamp'] = $dStampMap[$sid];
  3749. }
  3750. }
  3751. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3752. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3753. $ct = $dbRow['createtime'];
  3754. if (is_numeric($ct) && (int)$ct > 946684800) {
  3755. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3756. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3757. $r['dStamp'] = trim($ct);
  3758. }
  3759. }
  3760. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3761. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3762. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3763. $fallback = trim((string)($r['dStamp'] ?? ''));
  3764. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3765. $r['dputrecord'] = $fallback;
  3766. }
  3767. }
  3768. if (array_key_exists('id', $dbRow)) {
  3769. $r['purchase_order_id'] = (int)$dbRow['id'];
  3770. }
  3771. if ($sid < 0) {
  3772. $r['_is_manual'] = 1;
  3773. }
  3774. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3775. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3776. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3777. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3778. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3779. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3780. $r['pick_time'] = $pickFallback;
  3781. break;
  3782. }
  3783. }
  3784. }
  3785. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3786. if ($pickNm !== '') {
  3787. $r['pick_company_name'] = $pickNm;
  3788. $r['picked_supplier_name'] = $pickNm;
  3789. }
  3790. return $r;
  3791. }
  3792. /**
  3793. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3794. *
  3795. * @return array<int, array<string, mixed>>
  3796. */
  3797. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3798. {
  3799. $pool = [];
  3800. if (!is_array($dbRows) || $dbRows === []) {
  3801. return $pool;
  3802. }
  3803. $dStampMap = [];
  3804. $sidList = [];
  3805. foreach ($dbRows as $tmpRow) {
  3806. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3807. $sid = (int)$tmpRow['scydgy_id'];
  3808. if ($sid > 0) {
  3809. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3810. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3811. $sidList[$sid] = true;
  3812. }
  3813. }
  3814. }
  3815. }
  3816. if ($sidList !== []) {
  3817. try {
  3818. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3819. } catch (\Throwable $e) {
  3820. $dStampMap = [];
  3821. }
  3822. }
  3823. foreach ($dbRows as $dbRow) {
  3824. if (!is_array($dbRow)) {
  3825. continue;
  3826. }
  3827. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3828. }
  3829. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3830. $needCcydh = [];
  3831. foreach ($pool as $row) {
  3832. if (!is_array($row)) {
  3833. continue;
  3834. }
  3835. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3836. continue;
  3837. }
  3838. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3839. if ($ccydh !== '') {
  3840. $needCcydh[$ccydh] = true;
  3841. }
  3842. }
  3843. if ($needCcydh !== []) {
  3844. $czMap = [];
  3845. try {
  3846. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3847. } catch (\Throwable $e) {
  3848. $czMap = [];
  3849. }
  3850. if (is_array($czMap) && $czMap !== []) {
  3851. foreach ($pool as &$row) {
  3852. if (!is_array($row)) {
  3853. continue;
  3854. }
  3855. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3856. continue;
  3857. }
  3858. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3859. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3860. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3861. }
  3862. }
  3863. unset($row);
  3864. }
  3865. }
  3866. return $pool;
  3867. }
  3868. /**
  3869. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3870. *
  3871. * @param int[] $scydgyIds
  3872. * @return array<int, array<string, mixed>>
  3873. */
  3874. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3875. {
  3876. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3877. if ($scydgyIds === []) {
  3878. return [];
  3879. }
  3880. try {
  3881. $list = Db::table('purchase_order_detail')
  3882. ->where('scydgy_id', 'in', $scydgyIds)
  3883. ->field('scydgy_id,company_name,amount,delivery')
  3884. ->select();
  3885. } catch (\Throwable $e) {
  3886. $list = [];
  3887. }
  3888. return is_array($list) ? $list : [];
  3889. }
  3890. /**
  3891. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3892. *
  3893. * @param int[] $scydgyIds
  3894. * @param array<int, array<string, mixed>> $allRows
  3895. * @return array{cnt:int, amt:int, deliv:int}
  3896. */
  3897. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3898. {
  3899. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3900. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3901. if ($scydgyIds === [] || $allRows === []) {
  3902. return $out;
  3903. }
  3904. $idSet = array_flip($scydgyIds);
  3905. $all = [];
  3906. $withAmt = [];
  3907. $withDeliv = [];
  3908. foreach ($allRows as $r) {
  3909. if (!is_array($r)) {
  3910. continue;
  3911. }
  3912. $sid = (int)($r['scydgy_id'] ?? 0);
  3913. if (!isset($idSet[$sid])) {
  3914. continue;
  3915. }
  3916. $cn = trim((string)($r['company_name'] ?? ''));
  3917. if ($cn === '') {
  3918. continue;
  3919. }
  3920. $all[$cn] = true;
  3921. $am = $r['amount'] ?? null;
  3922. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3923. $withAmt[$cn] = true;
  3924. }
  3925. $dv = $r['delivery'] ?? null;
  3926. if ($dv !== null && trim((string)$dv) !== '') {
  3927. $withDeliv[$cn] = true;
  3928. }
  3929. }
  3930. return [
  3931. 'cnt' => count($all),
  3932. 'amt' => count($withAmt),
  3933. 'deliv' => count($withDeliv),
  3934. ];
  3935. }
  3936. /**
  3937. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  3938. *
  3939. * @param array<string, mixed> $row
  3940. */
  3941. protected function resolveProcuremenThisQuantity(array $row): string
  3942. {
  3943. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  3944. if ($q !== '') {
  3945. return $q;
  3946. }
  3947. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  3948. if (!is_scalar($ngzl)) {
  3949. return '';
  3950. }
  3951. $s = trim((string)$ngzl);
  3952. if ($s === '') {
  3953. return '';
  3954. }
  3955. if (is_numeric($s) && (float)$s === 0.0) {
  3956. return '';
  3957. }
  3958. return $s;
  3959. }
  3960. /**
  3961. * @param array<string, mixed> $row
  3962. */
  3963. protected function resolveProcuremenCeilingPrice(array $row): string
  3964. {
  3965. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  3966. }
  3967. /**
  3968. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  3969. *
  3970. * @param array<int, mixed> $parts
  3971. */
  3972. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  3973. {
  3974. $out = [];
  3975. foreach ($parts as $p) {
  3976. $s = trim((string)$p);
  3977. if ($s !== '') {
  3978. $out[] = $s;
  3979. }
  3980. }
  3981. return $out === [] ? '' : implode($sep, $out);
  3982. }
  3983. /**
  3984. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  3985. *
  3986. * @param array<int, array<string, mixed>> $rows
  3987. */
  3988. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  3989. {
  3990. if ($rows === []) {
  3991. return;
  3992. }
  3993. $idList = [];
  3994. foreach ($rows as $rw) {
  3995. if (!is_array($rw)) {
  3996. continue;
  3997. }
  3998. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3999. foreach ($rw['_order_merge_rows'] as $mr) {
  4000. if (!is_array($mr)) {
  4001. continue;
  4002. }
  4003. $mid = (int)($mr['ID'] ?? 0);
  4004. if ($this->isValidScydgyRowId($mid)) {
  4005. $idList[$mid] = true;
  4006. }
  4007. }
  4008. }
  4009. $id = (int)($rw['ID'] ?? 0);
  4010. if ($this->isValidScydgyRowId($id)) {
  4011. $idList[$id] = true;
  4012. }
  4013. }
  4014. if ($idList === []) {
  4015. return;
  4016. }
  4017. try {
  4018. $list = Db::table('purchase_order')
  4019. ->where('scydgy_id', 'in', array_keys($idList))
  4020. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4021. ->select();
  4022. } catch (\Throwable $e) {
  4023. return;
  4024. }
  4025. if (!is_array($list)) {
  4026. return;
  4027. }
  4028. $byId = [];
  4029. foreach ($list as $dbRow) {
  4030. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4031. continue;
  4032. }
  4033. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4034. }
  4035. foreach ($rows as &$rw) {
  4036. if (!is_array($rw)) {
  4037. continue;
  4038. }
  4039. $mergeRows = [];
  4040. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4041. $mergeRows = $rw['_order_merge_rows'];
  4042. } else {
  4043. $mergeRows = [$rw];
  4044. }
  4045. $qtyList = [];
  4046. $priceList = [];
  4047. $picked = '';
  4048. foreach ($mergeRows as $mr) {
  4049. if (!is_array($mr)) {
  4050. continue;
  4051. }
  4052. $sid = (int)($mr['ID'] ?? 0);
  4053. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4054. $src = $mr;
  4055. if (is_array($db)) {
  4056. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4057. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4058. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4059. if ($qDb !== '') {
  4060. $src['This_quantity'] = $qDb;
  4061. }
  4062. if ($pDb !== '') {
  4063. $src['ceilingPrice'] = $pDb;
  4064. }
  4065. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4066. $src['NGZL'] = $ngzlDb;
  4067. }
  4068. if ($picked === '') {
  4069. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4070. }
  4071. }
  4072. if ($picked === '') {
  4073. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4074. }
  4075. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4076. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4077. }
  4078. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4079. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4080. if ($picked !== '') {
  4081. $rw['pick_company_name'] = $picked;
  4082. $rw['picked_supplier_name'] = $picked;
  4083. }
  4084. }
  4085. unset($rw);
  4086. }
  4087. /**
  4088. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4089. *
  4090. * @param int[] $scydgyIds
  4091. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4092. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4093. */
  4094. protected function OrderDetailSummary(array $scydgyIds)
  4095. {
  4096. $out = [];
  4097. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4098. if ($scydgyIds === []) {
  4099. return $out;
  4100. }
  4101. $list = [];
  4102. try {
  4103. $list = Db::table('purchase_order_detail')
  4104. ->where('scydgy_id', 'in', $scydgyIds)
  4105. ->field('id,scydgy_id,amount,delivery')
  4106. ->select();
  4107. } catch (\Throwable $e) {
  4108. $list = [];
  4109. }
  4110. if (!is_array($list)) {
  4111. return $out;
  4112. }
  4113. foreach ($list as $r) {
  4114. if (!is_array($r)) {
  4115. continue;
  4116. }
  4117. $ids = (int)($r['scydgy_id'] ?? 0);
  4118. if (!$this->isValidScydgyRowId($ids)) {
  4119. continue;
  4120. }
  4121. if (!isset($out[$ids])) {
  4122. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4123. }
  4124. $out[$ids]['cnt']++;
  4125. $am = $r['amount'] ?? null;
  4126. if ($am !== null && $am !== '') {
  4127. if (!(is_string($am) && trim($am) === '')) {
  4128. $out[$ids]['amt']++;
  4129. }
  4130. }
  4131. $dv = $r['delivery'] ?? null;
  4132. if ($dv !== null && trim((string)$dv) !== '') {
  4133. $out[$ids]['deliv']++;
  4134. }
  4135. }
  4136. return $out;
  4137. }
  4138. /**
  4139. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4140. *
  4141. * @return array
  4142. */
  4143. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4144. {
  4145. $strContains = function ($haystack, $needle) {
  4146. if ($needle === '') {
  4147. return false;
  4148. }
  4149. $haystack = (string)$haystack;
  4150. if (function_exists('mb_stripos')) {
  4151. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4152. }
  4153. return stripos($haystack, $needle) !== false;
  4154. };
  4155. $stripAlias = function ($f) {
  4156. return preg_replace('/^[ab]\./i', '', (string)$f);
  4157. };
  4158. $searchColNames = [];
  4159. foreach (explode(',', $this->searchFields) as $colRaw) {
  4160. $c = $stripAlias(trim($colRaw));
  4161. if ($c !== '') {
  4162. $searchColNames[] = $c;
  4163. }
  4164. }
  4165. // 等值条件先行(表头下拉),减少后续日期解析量
  4166. $eqFilters = [];
  4167. $otherFilters = [];
  4168. foreach ($filterArr as $fk => $fv) {
  4169. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4170. continue;
  4171. }
  4172. if (is_array($fv)) {
  4173. continue;
  4174. }
  4175. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4176. continue;
  4177. }
  4178. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4179. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4180. $field = $stripAlias($fk);
  4181. if ($sym === '=' || $sym === '') {
  4182. $eqFilters[$field] = trim((string)$fv);
  4183. } else {
  4184. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4185. }
  4186. }
  4187. $ymTarget = '';
  4188. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4189. $ymTarget = $ymM[1];
  4190. }
  4191. $filtered = [];
  4192. foreach ($pool as $r) {
  4193. if (!is_array($r)) {
  4194. continue;
  4195. }
  4196. foreach ($eqFilters as $field => $fv) {
  4197. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4198. continue 2;
  4199. }
  4200. }
  4201. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4202. // 初选池不应含手工单;若混入则直接剔除
  4203. if ($isManual) {
  4204. continue;
  4205. }
  4206. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4207. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4208. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4209. continue;
  4210. }
  4211. if ($applyMonthRange) {
  4212. $mo = (int)$m[2];
  4213. if ($mo < 1 || $mo > 12) {
  4214. continue;
  4215. }
  4216. if ($ymTarget !== '') {
  4217. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4218. if ($ymRow !== $ymTarget) {
  4219. continue;
  4220. }
  4221. } else {
  4222. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4223. $rowMonthStart = $ymRow . '-01 00:00:00';
  4224. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4225. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4226. continue;
  4227. }
  4228. }
  4229. }
  4230. if ($search !== '') {
  4231. $hitSearch = false;
  4232. foreach ($searchColNames as $c) {
  4233. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4234. if ($cell !== '' && $strContains($cell, $search)) {
  4235. $hitSearch = true;
  4236. break;
  4237. }
  4238. }
  4239. if (!$hitSearch) {
  4240. continue;
  4241. }
  4242. }
  4243. foreach ($otherFilters as $item) {
  4244. $fv = $item['fv'];
  4245. $sym = $item['sym'];
  4246. $field = $item['field'];
  4247. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4248. $cellStr = trim((string)$cell);
  4249. switch ($sym) {
  4250. case '<>':
  4251. if ((string)$cell === (string)$fv) {
  4252. continue 3;
  4253. }
  4254. break;
  4255. case 'LIKE':
  4256. case 'NOT LIKE':
  4257. $needle = trim((string)$fv);
  4258. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4259. if ($sym === 'LIKE' && !$hit) {
  4260. continue 3;
  4261. }
  4262. if ($sym === 'NOT LIKE' && $hit) {
  4263. continue 3;
  4264. }
  4265. break;
  4266. case 'BETWEEN':
  4267. case 'RANGE':
  4268. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4269. if (count($parts) < 2) {
  4270. $parts = is_string($fv) ? explode(',', $fv) : [];
  4271. }
  4272. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4273. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4274. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4275. continue 3;
  4276. }
  4277. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4278. continue 3;
  4279. }
  4280. break;
  4281. case '>':
  4282. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4283. continue 3;
  4284. }
  4285. break;
  4286. case '>=':
  4287. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4288. continue 3;
  4289. }
  4290. break;
  4291. case '<':
  4292. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4293. continue 3;
  4294. }
  4295. break;
  4296. case '<=':
  4297. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4298. continue 3;
  4299. }
  4300. break;
  4301. default:
  4302. if ((string)$cell !== (string)$fv) {
  4303. continue 3;
  4304. }
  4305. break;
  4306. }
  4307. }
  4308. $filtered[] = $r;
  4309. }
  4310. return $filtered;
  4311. }
  4312. /**
  4313. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4314. */
  4315. public function snapshotToProcure()
  4316. {
  4317. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4318. $this->error(__('Invalid parameters'));
  4319. }
  4320. $row = json_decode($this->request->post('row_json', ''), true);
  4321. if (!is_array($row)) {
  4322. $this->error(__('Invalid parameters'));
  4323. }
  4324. try {
  4325. $ids = $this->extractScydgyRowId($row);
  4326. if (!$this->isValidScydgyRowId($ids)) {
  4327. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4328. }
  4329. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4330. $data = [
  4331. 'scydgy_id' => $ids,
  4332. 'CCYDH' => $row['CCYDH'] ?? null,
  4333. 'CYJMC' => $row['CYJMC'] ?? null,
  4334. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4335. 'CDXMC' => $row['CDXMC'] ?? null,
  4336. 'CGYBH' => $row['CGYBH'] ?? null,
  4337. 'CGYMC' => $row['CGYMC'] ?? null,
  4338. 'CDW' => $row['CDW'] ?? null,
  4339. 'czlyq' => $row['czlyq'] ?? null,
  4340. 'NGZL' => $row['NGZL'] ?? null,
  4341. 'CDF' => $row['CDF'] ?? null,
  4342. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4343. 'MBZ' => $row['MBZ'] ?? null,
  4344. 'bwjg' => $row['bwjg'] ?? null,
  4345. 'iStatus' => $row['iStatus'] ?? null,
  4346. 'dStamp' => $row['dStamp'] ?? null,
  4347. 'dputrecord' => $row['dputrecord'] ?? null,
  4348. 'cywyxm' => $row['cywyxm'] ?? null,
  4349. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4350. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4351. ];
  4352. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4353. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4354. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  4355. $this->success('操作成功');
  4356. return;
  4357. }
  4358. if ($exists) {
  4359. $upd = $data;
  4360. unset($upd['scydgy_id'], $upd['status']);
  4361. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4362. } else {
  4363. // 新增:不写 status(空/走库默认);仅写创建时间
  4364. $data['createtime'] = date('Y-m-d H:i:s');
  4365. Db::table('purchase_order')->insert($data);
  4366. }
  4367. } catch (\Throwable $e) {
  4368. $this->error($e->getMessage());
  4369. }
  4370. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4371. $this->success('操作成功');
  4372. }
  4373. /**
  4374. * 未发列表
  4375. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  4376. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4377. */
  4378. public function completeDirectly()
  4379. {
  4380. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4381. $this->error(__('参数错误'));
  4382. }
  4383. if (!$this->procuremenCanComplete()) {
  4384. $this->error(__('You have no permission'));
  4385. }
  4386. $row = json_decode($this->request->post('row_json', ''), true);
  4387. if (!is_array($row)) {
  4388. $this->error(__('Invalid parameters'));
  4389. }
  4390. $finishRaw = $this->request->post('finish', '1');
  4391. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4392. $poIdLog = null;
  4393. try {
  4394. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4395. $ids = $this->extractScydgyRowId($row);
  4396. if (!$this->isValidScydgyRowId($ids)) {
  4397. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4398. }
  4399. if ($asComplete) {
  4400. $this->assertPickRowCanComplete($ids, $row);
  4401. }
  4402. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4403. $data = [
  4404. 'scydgy_id' => $ids,
  4405. 'CCYDH' => $row['CCYDH'] ?? null,
  4406. 'CYJMC' => $row['CYJMC'] ?? null,
  4407. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4408. 'CDXMC' => $row['CDXMC'] ?? null,
  4409. 'CGYBH' => $row['CGYBH'] ?? null,
  4410. 'CGYMC' => $row['CGYMC'] ?? null,
  4411. 'CDW' => $row['CDW'] ?? null,
  4412. 'czlyq' => $row['czlyq'] ?? null,
  4413. 'NGZL' => $row['NGZL'] ?? null,
  4414. 'CDF' => $row['CDF'] ?? null,
  4415. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4416. 'MBZ' => $row['MBZ'] ?? null,
  4417. 'bwjg' => $row['bwjg'] ?? null,
  4418. 'iStatus' => $row['iStatus'] ?? null,
  4419. 'dStamp' => $row['dStamp'] ?? null,
  4420. 'dputrecord' => $row['dputrecord'] ?? null,
  4421. 'cywyxm' => $row['cywyxm'] ?? null,
  4422. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4423. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4424. ];
  4425. if ($asComplete) {
  4426. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4427. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4428. }
  4429. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4430. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4431. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  4432. $this->success('操作成功');
  4433. return;
  4434. }
  4435. if ($exists) {
  4436. $upd = $data;
  4437. unset($upd['scydgy_id']);
  4438. if (!$asComplete) {
  4439. unset($upd['status']);
  4440. }
  4441. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4442. } else {
  4443. // 新增:不写 status;完结时 $data 已含 status=1
  4444. $data['createtime'] = date('Y-m-d H:i:s');
  4445. Db::table('purchase_order')->insert($data);
  4446. }
  4447. } catch (\Throwable $e) {
  4448. $this->error($e->getMessage());
  4449. }
  4450. try {
  4451. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4452. if (is_array($rpo)) {
  4453. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4454. $poIdLog = $tid > 0 ? $tid : null;
  4455. }
  4456. } catch (\Throwable $e) {
  4457. $poIdLog = null;
  4458. }
  4459. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4460. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4461. if ($asComplete) {
  4462. $this->addOrderLog(
  4463. $ids,
  4464. 'mark_complete',
  4465. '点击「完结」,已标记为已完结',
  4466. $poIdLog
  4467. );
  4468. try {
  4469. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4470. if ($pdfPublicPath === '') {
  4471. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4472. }
  4473. } catch (\Throwable $e) {
  4474. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4475. }
  4476. } else {
  4477. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4478. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4479. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4480. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  4481. $this->addOrderLog(
  4482. $ids,
  4483. 'save_qty_price',
  4484. '保存本次数量、最高限价:' . $detail,
  4485. $poIdLog
  4486. );
  4487. }
  4488. $this->pickHiddenScydgySetCache = null;
  4489. $this->success("操作成功");
  4490. }
  4491. /**
  4492. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  4493. *
  4494. * @param array<int, array> $rows 引用传递当前页行
  4495. */
  4496. protected function mergePurchaseOrder(array &$rows)
  4497. {
  4498. if ($rows === []) {
  4499. return;
  4500. }
  4501. $ids = [];
  4502. foreach ($rows as $rw) {
  4503. if (!is_array($rw)) {
  4504. continue;
  4505. }
  4506. $id = (int)($rw['ID'] ?? 0);
  4507. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4508. if ($this->isValidScydgyRowId($id)) {
  4509. $ids[$id] = true;
  4510. }
  4511. }
  4512. $idList = array_keys($ids);
  4513. if ($idList === []) {
  4514. return;
  4515. }
  4516. try {
  4517. $list = Db::table('purchase_order')
  4518. ->where('scydgy_id', 'in', $idList)
  4519. ->field('scydgy_id,This_quantity,ceilingPrice')
  4520. ->select();
  4521. } catch (\Throwable $e) {
  4522. return;
  4523. }
  4524. if (!is_array($list)) {
  4525. return;
  4526. }
  4527. $byId = [];
  4528. foreach ($list as $dbRow) {
  4529. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4530. continue;
  4531. }
  4532. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4533. }
  4534. foreach ($rows as &$rw) {
  4535. if (!is_array($rw)) {
  4536. continue;
  4537. }
  4538. $sid = (int)($rw['ID'] ?? 0);
  4539. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4540. continue;
  4541. }
  4542. $db = $byId[$sid];
  4543. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  4544. if (array_key_exists('This_quantity', $db)) {
  4545. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4546. }
  4547. if (array_key_exists('ceilingPrice', $db)) {
  4548. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4549. } elseif (array_key_exists('ceiling_price', $db)) {
  4550. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4551. }
  4552. }
  4553. unset($rw);
  4554. }
  4555. /**
  4556. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4557. */
  4558. public function purchaseConfirmPick()
  4559. {
  4560. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4561. $this->error(__('Invalid parameters'));
  4562. }
  4563. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4564. $this->error(__('You have no permission'));
  4565. }
  4566. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4567. if ($batchRaw !== '') {
  4568. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4569. return;
  4570. }
  4571. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4572. $sid = (int)$scydgyId;
  4573. if (!$this->isValidScydgyRowId($sid)) {
  4574. $this->error('参数无效');
  4575. }
  4576. $parseIdList = function ($raw) {
  4577. if (is_array($raw)) {
  4578. $arr = $raw;
  4579. } else {
  4580. $decoded = json_decode((string)$raw, true);
  4581. $arr = is_array($decoded) ? $decoded : [];
  4582. }
  4583. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4584. };
  4585. $selectedRaw = $this->request->post('selected_ids', null);
  4586. if ($selectedRaw === null || $selectedRaw === '') {
  4587. $legacy = (int)$this->request->post('selected_id', 0);
  4588. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4589. } else {
  4590. $selectedIds = $parseIdList($selectedRaw);
  4591. }
  4592. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4593. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4594. try {
  4595. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4596. } catch (\InvalidArgumentException $e) {
  4597. $this->error($e->getMessage());
  4598. } catch (\Throwable $e) {
  4599. $this->error($e->getMessage());
  4600. }
  4601. $this->pickHiddenScydgySetCache = null;
  4602. $this->success('操作成功', '', $result);
  4603. }
  4604. /**
  4605. * 整单采购确认(多道工序一次提交)
  4606. */
  4607. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4608. {
  4609. $decoded = json_decode($batchRaw, true);
  4610. if (!is_array($decoded) || $decoded === []) {
  4611. $this->error('提交数据无效');
  4612. }
  4613. $picks = [];
  4614. foreach ($decoded as $item) {
  4615. if (!is_array($item)) {
  4616. continue;
  4617. }
  4618. $sid = (int)($item['scydgy_id'] ?? 0);
  4619. if (!$this->isValidScydgyRowId($sid)) {
  4620. continue;
  4621. }
  4622. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4623. if (!is_array($sel)) {
  4624. $sel = [(int)$sel];
  4625. }
  4626. $unsel = $item['unselected_ids'] ?? [];
  4627. if (!is_array($unsel)) {
  4628. $unsel = json_decode((string)$unsel, true);
  4629. $unsel = is_array($unsel) ? $unsel : [];
  4630. }
  4631. $picks[] = [
  4632. 'scydgy_id' => $sid,
  4633. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4634. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4635. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4636. ];
  4637. }
  4638. if ($picks === []) {
  4639. $this->error('提交数据无效');
  4640. }
  4641. Db::startTrans();
  4642. $results = [];
  4643. try {
  4644. foreach ($picks as $pick) {
  4645. $results[] = $this->runPurchaseConfirmPick(
  4646. (int)$pick['scydgy_id'],
  4647. $pick['selected_ids'],
  4648. $pick['unselected_ids'],
  4649. (int)$pick['purchase_order_id'],
  4650. false,
  4651. false
  4652. );
  4653. }
  4654. Db::commit();
  4655. } catch (\Throwable $e) {
  4656. Db::rollback();
  4657. $msg = $e->getMessage();
  4658. $this->error($msg !== '' ? $msg : '提交失败');
  4659. }
  4660. try {
  4661. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4662. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4663. } catch (\Throwable $e) {
  4664. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  4665. }
  4666. $this->pickHiddenScydgySetCache = null;
  4667. $this->success('操作成功', '', ['batch' => $results]);
  4668. }
  4669. /**
  4670. * @return array<string, mixed>
  4671. */
  4672. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4673. {
  4674. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4675. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4676. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4677. $scydgyId = (string)$sid;
  4678. if ($selectedIds === []) {
  4679. throw new \InvalidArgumentException('请至少勾选一条明细');
  4680. }
  4681. $inter = array_intersect($selectedIds, $unselectedIds);
  4682. if ($inter !== []) {
  4683. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4684. }
  4685. $allIds = $this->purchaseOrderDetail($sid);
  4686. if ($allIds === []) {
  4687. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4688. }
  4689. foreach ($selectedIds as $id) {
  4690. if (!in_array($id, $allIds, true)) {
  4691. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4692. }
  4693. }
  4694. foreach ($unselectedIds as $id) {
  4695. if (!in_array($id, $allIds, true)) {
  4696. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4697. }
  4698. }
  4699. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4700. sort($union, SORT_NUMERIC);
  4701. $expect = $allIds;
  4702. sort($expect, SORT_NUMERIC);
  4703. if ($union !== $expect) {
  4704. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4705. }
  4706. if ($manageTransaction) {
  4707. Db::startTrans();
  4708. }
  4709. try {
  4710. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4711. $aff = 0;
  4712. try {
  4713. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4714. } catch (\Throwable $e) {
  4715. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4716. }
  4717. if ($aff < 1) {
  4718. throw new \Exception('更新选中状态失败');
  4719. }
  4720. $poPayload = [
  4721. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4722. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4723. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4724. ];
  4725. if ($purchaseOrderId > 0) {
  4726. $poAff = (int)Db::table('purchase_order')
  4727. ->where('id', $purchaseOrderId)
  4728. ->where('scydgy_id', $sid)
  4729. ->update($poPayload);
  4730. if ($poAff < 1) {
  4731. throw new \Exception('主表订单不存在或与工序行不匹配');
  4732. }
  4733. } else {
  4734. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4735. if ($poAff < 1) {
  4736. throw new \Exception('未找到');
  4737. }
  4738. }
  4739. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4740. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4741. if ($manageTransaction) {
  4742. Db::commit();
  4743. }
  4744. } catch (\Throwable $e) {
  4745. if ($manageTransaction) {
  4746. Db::rollback();
  4747. }
  4748. throw $e;
  4749. }
  4750. $poIdFinal = $purchaseOrderId;
  4751. if ($poIdFinal <= 0) {
  4752. try {
  4753. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4754. if (is_array($rpo)) {
  4755. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4756. }
  4757. } catch (\Throwable $e) {
  4758. $poIdFinal = 0;
  4759. }
  4760. }
  4761. $pickNames = [];
  4762. foreach ($selectedIds as $pid) {
  4763. $dr = $this->purchaseOrderDetai($sid, $pid);
  4764. $nm = trim((string)($dr['company_name'] ?? ''));
  4765. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4766. }
  4767. $this->addOrderLog(
  4768. $sid,
  4769. 'purchase_confirm',
  4770. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4771. $poIdFinal > 0 ? $poIdFinal : null
  4772. );
  4773. if ($sendNotifications) {
  4774. try {
  4775. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4776. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4777. 'scydgy_id' => $sid,
  4778. 'selected_ids' => $selectedIds,
  4779. 'unselected_ids' => $unselectedIds,
  4780. 'purchase_order_id' => $purchaseOrderId,
  4781. ]]);
  4782. } catch (\Throwable $e) {
  4783. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4784. }
  4785. }
  4786. Log::write(sprintf(
  4787. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4788. $scydgyId,
  4789. $purchaseOrderId,
  4790. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4791. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4792. ), 'notice');
  4793. $pdfPublicPath = '';
  4794. try {
  4795. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4796. } catch (\Throwable $e) {
  4797. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4798. }
  4799. return [
  4800. 'scydgy_id' => $scydgyId,
  4801. 'purchase_order_id' => $purchaseOrderId,
  4802. 'selected_ids' => $selectedIds,
  4803. 'unselected_ids' => $unselectedIds,
  4804. 'purchase_confirm_pdf' => $pdfPublicPath,
  4805. ];
  4806. }
  4807. /**
  4808. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4809. *
  4810. * @param int[]|string[] $scydgyIds
  4811. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4812. */
  4813. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4814. {
  4815. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4816. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4817. if ($scydgyIds === []) {
  4818. return $empty;
  4819. }
  4820. $pos = [];
  4821. try {
  4822. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4823. } catch (\Throwable $e) {
  4824. $rows = [];
  4825. }
  4826. if (is_array($rows)) {
  4827. foreach ($rows as $po) {
  4828. if (is_array($po)) {
  4829. $pos[] = $po;
  4830. }
  4831. }
  4832. }
  4833. if ($pos === []) {
  4834. return $empty;
  4835. }
  4836. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4837. return [
  4838. 'ccydh' => $ccydh,
  4839. 'pos' => $pos,
  4840. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4841. ];
  4842. }
  4843. /**
  4844. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  4845. *
  4846. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4847. * @param array<int, array<string, mixed>> $picks
  4848. */
  4849. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4850. {
  4851. if ($picks === []) {
  4852. return;
  4853. }
  4854. $fallbackDetailId = 0;
  4855. $winners = [];
  4856. $losers = [];
  4857. foreach ($picks as $pick) {
  4858. if (!is_array($pick)) {
  4859. continue;
  4860. }
  4861. $sid = (int)($pick['scydgy_id'] ?? 0);
  4862. if (!$this->isValidScydgyRowId($sid)) {
  4863. continue;
  4864. }
  4865. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4866. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4867. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4868. $fallbackDetailId = (int)$selectedIds[0];
  4869. }
  4870. foreach ($selectedIds as $pid) {
  4871. $dr = $this->purchaseOrderDetai($sid, $pid);
  4872. if (!is_array($dr)) {
  4873. continue;
  4874. }
  4875. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4876. }
  4877. foreach ($unselectedIds as $pid) {
  4878. $dr = $this->purchaseOrderDetai($sid, $pid);
  4879. if (!is_array($dr)) {
  4880. continue;
  4881. }
  4882. $key = $this->notifySupplierDedupeKey($dr);
  4883. if (!isset($winners[$key])) {
  4884. $losers[$key] = $dr;
  4885. }
  4886. }
  4887. }
  4888. if ($winners === [] && $losers === []) {
  4889. return;
  4890. }
  4891. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4892. $sendSmsSafe = function ($phone, $content) {
  4893. $phone = trim((string)$phone);
  4894. if ($phone === '') {
  4895. return;
  4896. }
  4897. try {
  4898. $this->smsbao($phone, $content);
  4899. } catch (\Throwable $e) {
  4900. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4901. }
  4902. };
  4903. foreach ($winners as $dr) {
  4904. $cname = trim((string)($dr['company_name'] ?? ''));
  4905. $ph = trim((string)($dr['phone'] ?? ''));
  4906. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  4907. 'company_name' => $cname,
  4908. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4909. 'phone' => $ph,
  4910. ]));
  4911. $sendSmsSafe($ph, $sms);
  4912. }
  4913. foreach ($losers as $dr) {
  4914. $cname = trim((string)($dr['company_name'] ?? ''));
  4915. $ph = trim((string)($dr['phone'] ?? ''));
  4916. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  4917. 'company_name' => $cname,
  4918. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4919. 'phone' => $ph,
  4920. ]));
  4921. $sendSmsSafe($ph, $sms);
  4922. }
  4923. }
  4924. /**
  4925. * 短信去重键:优先手机号,否则公司名
  4926. */
  4927. protected function notifySupplierDedupeKey(array $detailRow): string
  4928. {
  4929. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  4930. if ($ph !== '') {
  4931. return 'p:' . $ph;
  4932. }
  4933. $cn = trim((string)($detailRow['company_name'] ?? ''));
  4934. return 'c:' . $cn;
  4935. }
  4936. /**
  4937. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  4938. *
  4939. * @param int[] $detailIds
  4940. */
  4941. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  4942. {
  4943. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  4944. if ($detailIds === []) {
  4945. return;
  4946. }
  4947. $payload = ['status_name' => $statusName];
  4948. try {
  4949. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  4950. } catch (\Throwable $e) {
  4951. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  4952. }
  4953. }
  4954. /**
  4955. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  4956. */
  4957. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  4958. {
  4959. try {
  4960. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  4961. } catch (\Throwable $e) {
  4962. return;
  4963. }
  4964. if (!is_array($rows)) {
  4965. return;
  4966. }
  4967. foreach ($rows as $dr) {
  4968. if (!is_array($dr)) {
  4969. continue;
  4970. }
  4971. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4972. if ($id <= 0) {
  4973. continue;
  4974. }
  4975. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  4976. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  4977. try {
  4978. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  4979. } catch (\Throwable $e) {
  4980. }
  4981. }
  4982. }
  4983. /**
  4984. * @param array<string, mixed> $detailRow
  4985. */
  4986. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  4987. {
  4988. $am = $detailRow['amount'] ?? null;
  4989. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  4990. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  4991. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  4992. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  4993. }
  4994. /**
  4995. * @return int[]
  4996. */
  4997. protected function purchaseOrderDetail(int $scydgyId): array
  4998. {
  4999. if (!$this->isValidScydgyRowId($scydgyId)) {
  5000. return [];
  5001. }
  5002. try {
  5003. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5004. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5005. $list = $listQuery->select();
  5006. } catch (\Throwable $e) {
  5007. return [];
  5008. }
  5009. if (!is_array($list)) {
  5010. return [];
  5011. }
  5012. $ids = [];
  5013. foreach ($list as $r) {
  5014. if (!is_array($r)) {
  5015. continue;
  5016. }
  5017. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5018. if ($pk > 0) {
  5019. $ids[] = $pk;
  5020. }
  5021. }
  5022. return array_values(array_unique($ids));
  5023. }
  5024. /**
  5025. * 获取当前登录用户信息 [id, 展示名]
  5026. */
  5027. protected function GetUseName(): array
  5028. {
  5029. $id = 0;
  5030. $name = '';
  5031. try {
  5032. if ($this->auth && $this->auth->isLogin()) {
  5033. $u = $this->auth->getUserInfo();
  5034. if (is_array($u)) {
  5035. $id = (int)($u['id'] ?? 0);
  5036. $name = trim((string)($u['nickname'] ?? ''));
  5037. if ($name === '') {
  5038. $name = trim((string)($u['username'] ?? ''));
  5039. }
  5040. }
  5041. }
  5042. } catch (\Throwable $e) {
  5043. }
  5044. if ($name === '') {
  5045. $name = '未知用户';
  5046. }
  5047. return [$id, $name];
  5048. }
  5049. /**
  5050. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5051. */
  5052. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5053. {
  5054. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5055. }
  5056. /**
  5057. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5058. *
  5059. * @param array<int, array<string, mixed>> $rows
  5060. */
  5061. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5062. {
  5063. $sidList = [];
  5064. foreach ($rows as $rw) {
  5065. if (!is_array($rw)) {
  5066. continue;
  5067. }
  5068. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5069. foreach ($rw['_order_merge_rows'] as $mr) {
  5070. $mid = (int)($mr['ID'] ?? 0);
  5071. if ($this->isValidScydgyRowId($mid)) {
  5072. $sidList[$mid] = true;
  5073. }
  5074. }
  5075. }
  5076. $id = (int)($rw['ID'] ?? 0);
  5077. if ($this->isValidScydgyRowId($id)) {
  5078. $sidList[$id] = true;
  5079. }
  5080. }
  5081. $sids = array_keys($sidList);
  5082. $issueBySid = [];
  5083. $confirmBySid = [];
  5084. $approveBySid = [];
  5085. if ($sids !== []) {
  5086. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5087. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5088. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5089. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5090. try {
  5091. $logs = Db::table('purchase_order_oper_log')
  5092. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5093. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5094. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5095. ->order('id', 'asc')
  5096. ->select();
  5097. } catch (\Throwable $e) {
  5098. $logs = [];
  5099. }
  5100. if (is_array($logs)) {
  5101. $issueSet = array_fill_keys($issueActs, true);
  5102. $confirmSet = array_fill_keys($confirmActs, true);
  5103. $approveSet = array_fill_keys($approveActs, true);
  5104. foreach ($logs as $lg) {
  5105. if (!is_array($lg)) {
  5106. continue;
  5107. }
  5108. $lg = ProcuremenOperLog::normalizeRow($lg);
  5109. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5110. if ($sid === 0) {
  5111. continue;
  5112. }
  5113. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5114. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5115. if ($t === '') {
  5116. continue;
  5117. }
  5118. if (isset($issueSet[$action])) {
  5119. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5120. $issueBySid[$sid] = $t;
  5121. }
  5122. }
  5123. if (isset($confirmSet[$action])) {
  5124. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5125. $confirmBySid[$sid] = $t;
  5126. }
  5127. }
  5128. if (isset($approveSet[$action])) {
  5129. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5130. $approveBySid[$sid] = $t;
  5131. }
  5132. }
  5133. }
  5134. }
  5135. }
  5136. foreach ($rows as &$rw) {
  5137. if (!is_array($rw)) {
  5138. continue;
  5139. }
  5140. $mergeSids = [];
  5141. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5142. foreach ($rw['_order_merge_rows'] as $mr) {
  5143. $mid = (int)($mr['ID'] ?? 0);
  5144. if ($this->isValidScydgyRowId($mid)) {
  5145. $mergeSids[] = $mid;
  5146. }
  5147. }
  5148. }
  5149. $rid = (int)($rw['ID'] ?? 0);
  5150. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5151. $mergeSids[] = $rid;
  5152. }
  5153. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5154. $issue = $pick;
  5155. $confirm = '';
  5156. $approve = '';
  5157. foreach ($mergeSids as $sid) {
  5158. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5159. $issue = $issueBySid[$sid];
  5160. }
  5161. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5162. $confirm = $confirmBySid[$sid];
  5163. }
  5164. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5165. $approve = $approveBySid[$sid];
  5166. }
  5167. }
  5168. if ($issue === '' && $pick !== '') {
  5169. $issue = $pick;
  5170. }
  5171. $rw['issue_time'] = $issue;
  5172. $rw['confirm_time'] = $confirm;
  5173. $rw['approve_time'] = $approve;
  5174. }
  5175. unset($rw);
  5176. }
  5177. /**
  5178. * 按主键取一条
  5179. */
  5180. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5181. {
  5182. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5183. return [];
  5184. }
  5185. try {
  5186. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5187. if (is_array($one)) {
  5188. return $one;
  5189. }
  5190. } catch (\Throwable $e) {
  5191. }
  5192. try {
  5193. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5194. if (is_array($one)) {
  5195. return $one;
  5196. }
  5197. } catch (\Throwable $e) {
  5198. }
  5199. return [];
  5200. }
  5201. /**
  5202. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5203. */
  5204. protected function formatProcuremenDetailTime($v): string
  5205. {
  5206. if ($v === null || $v === '') {
  5207. return '';
  5208. }
  5209. if (is_numeric($v) && (int)$v > 946684800) {
  5210. return date('Y-m-d H:i:s', (int)$v);
  5211. }
  5212. return ProcuremenTime::formatDisplayDateTime($v);
  5213. }
  5214. /**
  5215. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5216. */
  5217. protected function formatDeliveryYmd($v): string
  5218. {
  5219. if ($v === null || $v === '') {
  5220. return '';
  5221. }
  5222. $s = trim((string)$v);
  5223. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5224. return '';
  5225. }
  5226. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5227. return $m[1];
  5228. }
  5229. $ts = strtotime($s);
  5230. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5231. }
  5232. /**
  5233. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5234. */
  5235. protected function detailRowSupplierOperated(array $r): bool
  5236. {
  5237. $am = $r['amount'] ?? null;
  5238. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5239. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5240. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5241. return $okAmt || $okDel;
  5242. }
  5243. /**
  5244. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5245. */
  5246. protected function resolveDetailSupplierOperTime(array $r): string
  5247. {
  5248. if (!$this->detailRowSupplierOperated($r)) {
  5249. return '';
  5250. }
  5251. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5252. if ($t !== '') {
  5253. return $t;
  5254. }
  5255. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5256. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5257. continue;
  5258. }
  5259. $t = $this->formatProcuremenDetailTime($r[$col]);
  5260. if ($t !== '') {
  5261. return $t;
  5262. }
  5263. }
  5264. return '';
  5265. }
  5266. /**
  5267. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5268. */
  5269. protected function detailRowSupplierAccepted(array $r): bool
  5270. {
  5271. $am = $r['amount'] ?? null;
  5272. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5273. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5274. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5275. return $okAmt && $okDel;
  5276. }
  5277. /**
  5278. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5279. */
  5280. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5281. {
  5282. if ($detailCount > 0) {
  5283. return true;
  5284. }
  5285. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5286. return true;
  5287. }
  5288. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5289. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5290. return true;
  5291. }
  5292. return false;
  5293. }
  5294. /**
  5295. * 下发时间:优先 pick_time,其次首条下发明细时间
  5296. */
  5297. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5298. {
  5299. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5300. if ($issueTime !== '') {
  5301. return $issueTime;
  5302. }
  5303. foreach ($details as $dr) {
  5304. if (!is_array($dr)) {
  5305. continue;
  5306. }
  5307. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5308. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5309. $issueTime = $t;
  5310. }
  5311. }
  5312. if ($issueTime !== '') {
  5313. return $issueTime;
  5314. }
  5315. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5316. }
  5317. /**
  5318. * 直接点「完结」时间:优先操作记录 mark_complete
  5319. */
  5320. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5321. {
  5322. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5323. }
  5324. /**
  5325. * 操作记录时间(取指定 action 最近一条)
  5326. *
  5327. * @param string|array<int, string> $actions
  5328. */
  5329. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5330. {
  5331. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5332. }
  5333. /**
  5334. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5335. *
  5336. * @param array $main purchase_order 一行
  5337. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5338. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5339. */
  5340. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5341. {
  5342. $issueCnt = count($details);
  5343. $acceptCnt = 0;
  5344. $pickedName = '';
  5345. $pickedTime = '';
  5346. foreach ($details as $dr) {
  5347. if (!is_array($dr)) {
  5348. continue;
  5349. }
  5350. if ($this->detailRowSupplierAccepted($dr)) {
  5351. $acceptCnt++;
  5352. }
  5353. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5354. if ($pickedName === '') {
  5355. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5356. }
  5357. if ($pickedTime === '') {
  5358. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5359. if ($pickedTime === '') {
  5360. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5361. }
  5362. }
  5363. }
  5364. }
  5365. $hasMain = $main !== [];
  5366. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5367. if ($poTime === '') {
  5368. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5369. }
  5370. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5371. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5372. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5373. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5374. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5375. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5376. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5377. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5378. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5379. $inboundResult = '';
  5380. if ($scydgyId > 0) {
  5381. try {
  5382. $inRow = Db::table('purchase_order_inbound_score')
  5383. ->where('scydgy_id', $scydgyId)
  5384. ->field('result,updatetime,createtime')
  5385. ->find();
  5386. } catch (\Throwable $e) {
  5387. $inRow = null;
  5388. }
  5389. if (is_array($inRow) && $inRow !== []) {
  5390. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5391. if ($inboundScoreTime === '') {
  5392. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5393. }
  5394. }
  5395. }
  5396. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5397. $supplierTime = '';
  5398. if ($acceptCnt > 0) {
  5399. foreach ($details as $dr) {
  5400. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5401. continue;
  5402. }
  5403. $t = $this->resolveDetailSupplierOperTime($dr);
  5404. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5405. $supplierTime = $t;
  5406. }
  5407. }
  5408. }
  5409. $directComplete = ($mainCompleted && !$issued);
  5410. $doneTime = '';
  5411. if ($mainCompleted) {
  5412. if ($directComplete) {
  5413. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5414. }
  5415. if ($doneTime === '' && $inboundScoreTime !== '') {
  5416. $doneTime = $inboundScoreTime;
  5417. }
  5418. if ($doneTime === '') {
  5419. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5420. }
  5421. if ($doneTime === '') {
  5422. foreach ($details as $dr) {
  5423. if (!is_array($dr)) {
  5424. continue;
  5425. }
  5426. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5427. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5428. $doneTime = $t;
  5429. }
  5430. }
  5431. }
  5432. if ($doneTime === '') {
  5433. $doneTime = $poTime;
  5434. }
  5435. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5436. if ($doneTime === '' && $confirmApproveTime !== '') {
  5437. $doneTime = $confirmApproveTime;
  5438. }
  5439. }
  5440. if ($directComplete) {
  5441. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5442. $step1Done = $hasMain;
  5443. $step2Done = false;
  5444. $step3Done = false;
  5445. $step4Done = false;
  5446. $step5Done = false;
  5447. $stepInboundDone = $inboundScored;
  5448. $step6Done = $mainCompleted && $inboundScored;
  5449. } else {
  5450. $step1Done = $issued;
  5451. $step2Done = $issued;
  5452. $step3Done = $acceptCnt > 0;
  5453. $step4Done = $wflowPendingApproval;
  5454. if (!$step4Done) {
  5455. foreach ($details as $dr) {
  5456. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5457. $step4Done = true;
  5458. break;
  5459. }
  5460. }
  5461. }
  5462. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5463. $stepInboundDone = $inboundScored;
  5464. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5465. $step6Done = $mainCompleted && $inboundScored;
  5466. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5467. if ($mainCompleted && $issued) {
  5468. $step3Done = true;
  5469. $step4Done = true;
  5470. $step5Done = true;
  5471. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5472. if ($supplierTime === '') {
  5473. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5474. if ($fillT !== '') {
  5475. $supplierTime = $fillT;
  5476. }
  5477. }
  5478. if ($pickedTime === '') {
  5479. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5480. if ($fillT !== '') {
  5481. $pickedTime = $fillT;
  5482. }
  5483. }
  5484. if ($auditSelectTime === '') {
  5485. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5486. if ($fillT !== '') {
  5487. $auditSelectTime = $fillT;
  5488. }
  5489. }
  5490. if ($confirmApproveTime === '') {
  5491. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5492. if ($fillT !== '') {
  5493. $confirmApproveTime = $fillT;
  5494. }
  5495. }
  5496. }
  5497. }
  5498. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5499. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5500. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5501. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5502. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5503. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5504. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5505. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5506. $deadlineLines = [];
  5507. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5508. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5509. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5510. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5511. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5512. }
  5513. }
  5514. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5515. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5516. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5517. if ($deliveryDisp === '') {
  5518. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5519. }
  5520. if ($deliveryDisp !== '') {
  5521. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5522. }
  5523. }
  5524. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5525. $deadlineText = implode("\n", $deadlineLines);
  5526. $prefixOperTime = static function (string $t): string {
  5527. $t = trim($t);
  5528. if ($t === '' || $t === '—') {
  5529. return $t;
  5530. }
  5531. if (strpos($t, '操作时间') === 0) {
  5532. return $t;
  5533. }
  5534. return '操作时间:' . $t;
  5535. };
  5536. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5537. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5538. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5539. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5540. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5541. $steps = [
  5542. [
  5543. 'title' => '未发',
  5544. 'subtitle' => '',
  5545. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5546. 'done' => $step1Done,
  5547. ],
  5548. [
  5549. 'title' => '下发',
  5550. 'subtitle' => $deadlineText,
  5551. 'time' => $prefixOperTime($step2Time),
  5552. 'done' => $step2Done,
  5553. ],
  5554. [
  5555. 'title' => '供应商接单',
  5556. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5557. 'time' => '',
  5558. 'done' => $step3Done,
  5559. ],
  5560. [
  5561. 'title' => '待确认',
  5562. 'subtitle' => $step4Done
  5563. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5564. : ($issued ? '待选供应商' : ''),
  5565. 'time' => $prefixOperTime($step4Time),
  5566. 'done' => $step4Done,
  5567. ],
  5568. [
  5569. 'title' => '待审批',
  5570. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5571. 'time' => $prefixOperTime($step5Time),
  5572. 'done' => $step5Done,
  5573. ],
  5574. [
  5575. 'title' => '是否合格',
  5576. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5577. 'time' => $prefixOperTime($stepInboundTime),
  5578. 'done' => $stepInboundDone,
  5579. ],
  5580. [
  5581. 'title' => '已完结',
  5582. 'subtitle' => '',
  5583. 'time' => $prefixOperTime($step6Time),
  5584. 'done' => $step6Done,
  5585. ],
  5586. ];
  5587. $currentIdx = count($steps) - 1;
  5588. if ($directComplete) {
  5589. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5590. if (!$step6Done) {
  5591. foreach ($steps as $i => $s) {
  5592. if (($s['title'] ?? '') === '是否合格') {
  5593. $currentIdx = $i;
  5594. break;
  5595. }
  5596. }
  5597. }
  5598. } else {
  5599. foreach ($steps as $i => $s) {
  5600. if (!$s['done']) {
  5601. $currentIdx = $i;
  5602. break;
  5603. }
  5604. }
  5605. }
  5606. $nSteps = count($steps);
  5607. foreach ($steps as $idx => &$s) {
  5608. $s['current'] = ($idx === $currentIdx);
  5609. if ($idx === 0) {
  5610. $s['pdf_left_bg'] = '';
  5611. } else {
  5612. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5613. }
  5614. if ($idx >= $nSteps - 1) {
  5615. $s['pdf_right_bg'] = '';
  5616. } else {
  5617. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5618. }
  5619. }
  5620. unset($s);
  5621. $labelMap = [
  5622. 'CCYDH' => '订单号',
  5623. 'CYJMC' => '印件名称',
  5624. 'CCLBMMC' => '承揽部门',
  5625. 'CGYMC' => '工序名称',
  5626. 'CDW' => '单位',
  5627. 'czlyq' => '类型',
  5628. 'NGZL' => '工作量',
  5629. 'CDF' => '单价',
  5630. 'cGzzxMc' => '工作中心',
  5631. 'MBZ' => '备注',
  5632. 'This_quantity' => '本次数量',
  5633. 'ceilingPrice' => '最高限价',
  5634. ];
  5635. $orderSummary = [];
  5636. foreach ($labelMap as $key => $lab) {
  5637. if (!array_key_exists($key, $main)) {
  5638. continue;
  5639. }
  5640. $val = $main[$key];
  5641. if ($val === null) {
  5642. $val = '';
  5643. } elseif (!is_scalar($val)) {
  5644. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5645. } else {
  5646. $val = (string)$val;
  5647. }
  5648. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5649. }
  5650. $orderSummary[] = [
  5651. 'label' => '是否合格',
  5652. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5653. ];
  5654. $orderSummaryGrid = [];
  5655. $n = count($orderSummary);
  5656. for ($i = 0; $i < $n; $i += 2) {
  5657. $left = $orderSummary[$i];
  5658. $hasRight = ($i + 1) < $n;
  5659. $orderSummaryGrid[] = [
  5660. 'l1' => $left['label'],
  5661. 'v1' => $left['value'],
  5662. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5663. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5664. ];
  5665. }
  5666. return [
  5667. 'steps' => $steps,
  5668. 'orderSummary' => $orderSummary,
  5669. 'orderSummaryGrid' => $orderSummaryGrid,
  5670. 'inbound_result' => $inboundResult,
  5671. 'inbound_score_time'=> $inboundScoreTime,
  5672. 'detailRows' => $details,
  5673. ];
  5674. }
  5675. /**
  5676. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5677. *
  5678. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5679. */
  5680. protected function prepareProcuremenDetailsView(string $ids): array
  5681. {
  5682. $main = [];
  5683. try {
  5684. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5685. $main = is_array($one) ? $one : [];
  5686. } catch (\Throwable $e) {
  5687. $main = [];
  5688. }
  5689. $details = [];
  5690. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5691. if ($mergeRows === []) {
  5692. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5693. if ($mergeRows === [] && $main !== []) {
  5694. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5695. }
  5696. }
  5697. $detailSidList = [];
  5698. $anchorSid = (int)$ids;
  5699. if ($anchorSid !== 0) {
  5700. $detailSidList[$anchorSid] = true;
  5701. }
  5702. foreach ($mergeRows as $mr) {
  5703. if (!is_array($mr)) {
  5704. continue;
  5705. }
  5706. $sid = $this->extractScydgyRowId($mr);
  5707. if ($sid !== 0) {
  5708. $detailSidList[$sid] = true;
  5709. }
  5710. }
  5711. try {
  5712. if ($detailSidList !== []) {
  5713. $details = Db::table('purchase_order_detail')
  5714. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5715. ->order('id', 'asc')
  5716. ->select();
  5717. }
  5718. } catch (\Throwable $e) {
  5719. $details = [];
  5720. }
  5721. if (!is_array($details)) {
  5722. $details = [];
  5723. }
  5724. foreach ($details as &$r) {
  5725. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5726. $r['id'] = $r['ID'];
  5727. }
  5728. if (isset($r['createtime'])) {
  5729. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5730. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5731. } else {
  5732. $r['createtime_text'] = (string)$r['createtime'];
  5733. }
  5734. } else {
  5735. $r['createtime_text'] = '';
  5736. }
  5737. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5738. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5739. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5740. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5741. if (is_array($r)) {
  5742. $r = $this->maskSupplierContactFields($r);
  5743. }
  5744. }
  5745. unset($r);
  5746. $activeDetails = [];
  5747. foreach ($details as $r) {
  5748. if (is_array($r) && empty($r['is_void'])) {
  5749. $activeDetails[] = $r;
  5750. }
  5751. }
  5752. $operLogs = [];
  5753. try {
  5754. $operSidList = array_keys($detailSidList);
  5755. if ($operSidList === [] && (int)$ids !== 0) {
  5756. $operSidList = [(int)$ids];
  5757. }
  5758. if ($operSidList !== []) {
  5759. $operLogs = Db::table('purchase_order_oper_log')
  5760. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5761. ->order('id', 'asc')
  5762. ->select();
  5763. }
  5764. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5765. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5766. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5767. if ($poId > 0) {
  5768. $operLogs = Db::table('purchase_order_oper_log')
  5769. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5770. ->order('id', 'asc')
  5771. ->select();
  5772. }
  5773. }
  5774. } catch (\Throwable $e) {
  5775. $operLogs = [];
  5776. }
  5777. if (!is_array($operLogs)) {
  5778. $operLogs = [];
  5779. }
  5780. $operLogsRaw = $operLogs;
  5781. $processNameBySid = [];
  5782. foreach ($mergeRows as $mr) {
  5783. if (!is_array($mr)) {
  5784. continue;
  5785. }
  5786. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5787. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5788. if ($psid !== 0 && $gymc !== '') {
  5789. $processNameBySid[$psid] = $gymc;
  5790. }
  5791. }
  5792. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5793. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5794. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5795. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5796. if ($ccydh === '') {
  5797. foreach ($details as $r) {
  5798. if (!is_array($r)) {
  5799. continue;
  5800. }
  5801. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5802. if ($ccydh !== '') {
  5803. break;
  5804. }
  5805. }
  5806. }
  5807. $this->view->assign('ccydh', $ccydh);
  5808. $this->view->assign('steps', $bundle['steps']);
  5809. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5810. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5811. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5812. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5813. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5814. $this->view->assign('processCount', count($mergeRows));
  5815. $this->view->assign('detailRows', $details);
  5816. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5817. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5818. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5819. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5820. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5821. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5822. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5823. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5824. $this->view->assign('operLogs', $operLogs);
  5825. $sg = $quoteView['supplier_groups'] ?? [];
  5826. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  5827. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  5828. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  5829. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  5830. return [
  5831. 'ok' => $main !== [] || $details !== [],
  5832. 'ccydh' => $ccydh,
  5833. ];
  5834. }
  5835. /**
  5836. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  5837. */
  5838. public function details()
  5839. {
  5840. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5841. if (is_array($ids)) {
  5842. $ids = isset($ids[0]) ? $ids[0] : '';
  5843. }
  5844. $ids = trim((string)$ids);
  5845. if ($ids === '') {
  5846. $this->error(__('Invalid parameters'));
  5847. }
  5848. $this->assertManualOrderDetailsViewable((int)$ids);
  5849. $this->prepareProcuremenDetailsView($ids);
  5850. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  5851. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5852. $this->view->engine->layout(false);
  5853. try {
  5854. return $this->view->fetch('procuremen/details_dialog_shell');
  5855. } finally {
  5856. if ($restoreLayout) {
  5857. $this->view->engine->layout($restoreLayout);
  5858. }
  5859. }
  5860. }
  5861. /**
  5862. * 解析合并审核工序行(订单号须一致,且均未协助)
  5863. *
  5864. * @return array<int, array<string, mixed>>
  5865. */
  5866. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  5867. {
  5868. $primary = json_decode($rowJson, true);
  5869. if (!is_array($primary)) {
  5870. $this->error(__('Invalid parameters'));
  5871. }
  5872. $merge = json_decode($mergeRowsJson, true);
  5873. if (!is_array($merge) || $merge === []) {
  5874. $merge = [$primary];
  5875. }
  5876. $seen = [];
  5877. $out = [];
  5878. foreach ($merge as $r) {
  5879. if (!is_array($r)) {
  5880. continue;
  5881. }
  5882. $id = $this->extractScydgyRowId($r);
  5883. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  5884. continue;
  5885. }
  5886. $seen[$id] = true;
  5887. $out[] = $r;
  5888. }
  5889. if ($out === []) {
  5890. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  5891. }
  5892. $ccydh = null;
  5893. foreach ($out as $r) {
  5894. $dh = trim((string)($r['CCYDH'] ?? ''));
  5895. if ($ccydh === null) {
  5896. $ccydh = $dh;
  5897. } elseif ($dh !== $ccydh) {
  5898. $this->error('合并审核要求所选行的订单号一致');
  5899. }
  5900. }
  5901. $ids = [];
  5902. foreach ($out as $r) {
  5903. $id = $this->extractScydgyRowId($r);
  5904. if ($this->isValidScydgyRowId($id)) {
  5905. $ids[$id] = true;
  5906. }
  5907. }
  5908. $poBySid = [];
  5909. $detCntBySid = [];
  5910. if ($ids !== []) {
  5911. $idList = array_keys($ids);
  5912. try {
  5913. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  5914. if (is_array($poList)) {
  5915. foreach ($poList as $po) {
  5916. if (!is_array($po)) {
  5917. continue;
  5918. }
  5919. $sid = (int)($po['scydgy_id'] ?? 0);
  5920. if ($this->isValidScydgyRowId($sid)) {
  5921. $poBySid[$sid] = $po;
  5922. }
  5923. }
  5924. }
  5925. } catch (\Throwable $e) {
  5926. }
  5927. try {
  5928. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  5929. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  5930. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  5931. if (is_array($detRows)) {
  5932. foreach ($detRows as $dr) {
  5933. if (!is_array($dr)) {
  5934. continue;
  5935. }
  5936. $sid = (int)($dr['scydgy_id'] ?? 0);
  5937. if ($this->isValidScydgyRowId($sid)) {
  5938. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  5939. }
  5940. }
  5941. }
  5942. } catch (\Throwable $e) {
  5943. }
  5944. }
  5945. foreach ($out as $r) {
  5946. $id = $this->extractScydgyRowId($r);
  5947. if (!$this->isValidScydgyRowId($id)) {
  5948. continue;
  5949. }
  5950. $po = $poBySid[$id] ?? null;
  5951. if (!is_array($po)) {
  5952. continue;
  5953. }
  5954. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  5955. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5956. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  5957. }
  5958. $detCnt = (int)($detCntBySid[$id] ?? 0);
  5959. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  5960. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5961. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  5962. }
  5963. }
  5964. return $out;
  5965. }
  5966. /**
  5967. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  5968. */
  5969. protected function maskSupplierContactFields(array $item): array
  5970. {
  5971. if (array_key_exists('email', $item)) {
  5972. $item['email'] = mask_email((string)$item['email']);
  5973. }
  5974. if (array_key_exists('phone', $item)) {
  5975. $item['phone'] = mask_phone((string)$item['phone']);
  5976. }
  5977. return $item;
  5978. }
  5979. /**
  5980. * @param array<int, array<string, mixed>> $list
  5981. * @return array<int, array<string, mixed>>
  5982. */
  5983. protected function maskSupplierContactList(array $list): array
  5984. {
  5985. $out = [];
  5986. foreach ($list as $item) {
  5987. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  5988. }
  5989. return $out;
  5990. }
  5991. /**
  5992. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  5993. *
  5994. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  5995. * @return array<string, string>|null
  5996. */
  5997. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  5998. {
  5999. if (!is_array($row)) {
  6000. return null;
  6001. }
  6002. $norm = [];
  6003. foreach ($row as $k => $v) {
  6004. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6005. }
  6006. $row = $norm;
  6007. $st = $row['status'] ?? '';
  6008. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6009. return null;
  6010. }
  6011. $companyName = '';
  6012. foreach (['company_name', 'name'] as $nk) {
  6013. if (!empty($row[$nk])) {
  6014. $companyName = trim((string)$row[$nk]);
  6015. break;
  6016. }
  6017. }
  6018. if ($companyName === '') {
  6019. return null;
  6020. }
  6021. $username = '';
  6022. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6023. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6024. $username = trim((string)$row[$uk]);
  6025. break;
  6026. }
  6027. }
  6028. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6029. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6030. if ($phone === '' && isset($row['account'])) {
  6031. $phone = trim((string)$row['account']);
  6032. }
  6033. if ($phone === '' && isset($row['mobile'])) {
  6034. $phone = trim((string)$row['mobile']);
  6035. }
  6036. if ($requireContactChannels && $email === '' && $phone === '') {
  6037. return null;
  6038. }
  6039. $category = '';
  6040. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6041. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6042. $category = trim((string)$row[$ck]);
  6043. break;
  6044. }
  6045. }
  6046. return [
  6047. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6048. 'name' => $companyName,
  6049. 'company_name' => $companyName,
  6050. 'username' => $username,
  6051. 'email' => $email,
  6052. 'phone' => $phone,
  6053. 'category' => $category,
  6054. 'company_type' => $category,
  6055. ];
  6056. }
  6057. /**
  6058. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6059. */
  6060. protected function resolveCustomerContactById(string $id): ?array
  6061. {
  6062. $id = trim($id);
  6063. if ($id === '' || !ctype_digit($id)) {
  6064. return null;
  6065. }
  6066. try {
  6067. $row = Db::table('customer')->where('id', (int)$id)->find();
  6068. } catch (\Throwable $e) {
  6069. return null;
  6070. }
  6071. return $this->buildCustomerContactPayloadFromRow($row);
  6072. }
  6073. /**
  6074. * 按供应商名称解析联系信息(兼容旧提交数据)
  6075. *
  6076. * @param bool $requireContactChannels true 时须有邮箱或手机
  6077. */
  6078. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6079. {
  6080. $name = trim($name);
  6081. if ($name === '') {
  6082. return null;
  6083. }
  6084. try {
  6085. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6086. $row = Db::table('customer')
  6087. ->where('company_name', $name)
  6088. ->order('id', 'desc')
  6089. ->find();
  6090. } catch (\Throwable $e) {
  6091. return null;
  6092. }
  6093. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6094. }
  6095. /**
  6096. * 规范化下发/确认时勾选的供应商
  6097. *
  6098. * @param array<int, mixed> $companies
  6099. * @return array<int, array<string, string>>
  6100. */
  6101. protected function normalizePickCompanies(array $companies): array
  6102. {
  6103. $out = [];
  6104. foreach ($companies as $c) {
  6105. if (!is_array($c)) {
  6106. continue;
  6107. }
  6108. $resolved = null;
  6109. $cid = trim((string)($c['id'] ?? ''));
  6110. if ($cid !== '') {
  6111. $resolved = $this->resolveCustomerContactById($cid);
  6112. }
  6113. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6114. if ($resolved === null && $name !== '') {
  6115. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6116. }
  6117. if ($resolved === null) {
  6118. continue;
  6119. }
  6120. $out[] = $resolved;
  6121. }
  6122. return $out;
  6123. }
  6124. /**
  6125. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6126. *
  6127. * @param array<int, array<string, mixed>> $pool
  6128. * @return array<int, array<string, mixed>>
  6129. */
  6130. protected function collapseProcuremenPoolByOrder(array $pool): array
  6131. {
  6132. if ($pool === []) {
  6133. return [];
  6134. }
  6135. $groups = [];
  6136. foreach ($pool as $row) {
  6137. if (!is_array($row)) {
  6138. continue;
  6139. }
  6140. $dh = trim((string)($row['CCYDH'] ?? ''));
  6141. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6142. if (!isset($groups[$key])) {
  6143. $groups[$key] = [];
  6144. }
  6145. $groups[$key][] = $row;
  6146. }
  6147. $out = [];
  6148. foreach ($groups as $ccydh => $rows) {
  6149. if ($rows === []) {
  6150. continue;
  6151. }
  6152. usort($rows, function ($a, $b) {
  6153. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6154. });
  6155. $head = $rows[0];
  6156. $gymcList = [];
  6157. foreach ($rows as $r) {
  6158. $g = trim((string)($r['CGYMC'] ?? ''));
  6159. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6160. $gymcList[] = $g;
  6161. }
  6162. }
  6163. $merged = $head;
  6164. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6165. $merged['process_count'] = count($rows);
  6166. $merged['_order_merge_rows'] = $rows;
  6167. $qtyList = [];
  6168. $priceList = [];
  6169. foreach ($rows as $r) {
  6170. if (!is_array($r)) {
  6171. continue;
  6172. }
  6173. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6174. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6175. }
  6176. if (count($rows) > 1) {
  6177. $merged['CGYMC'] = implode('、', $gymcList);
  6178. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6179. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6180. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6181. } else {
  6182. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6183. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6184. }
  6185. // 已选供应商:取合并行中首个非空 pick_company_name
  6186. $pickedName = '';
  6187. foreach ($rows as $r) {
  6188. if (!is_array($r)) {
  6189. continue;
  6190. }
  6191. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6192. if ($pn !== '') {
  6193. $pickedName = $pn;
  6194. break;
  6195. }
  6196. }
  6197. if ($pickedName !== '') {
  6198. $merged['pick_company_name'] = $pickedName;
  6199. $merged['picked_supplier_name'] = $pickedName;
  6200. }
  6201. $mergedPickTime = '';
  6202. foreach ($rows as $r) {
  6203. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6204. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6205. $mergedPickTime = $t;
  6206. }
  6207. }
  6208. if ($mergedPickTime !== '') {
  6209. $merged['pick_time'] = $mergedPickTime;
  6210. }
  6211. $out[] = $merged;
  6212. }
  6213. usort($out, function ($a, $b) {
  6214. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6215. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6216. if ($ta === $tb) {
  6217. $ida = (int)($a['purchase_order_id'] ?? 0);
  6218. $idb = (int)($b['purchase_order_id'] ?? 0);
  6219. if ($ida !== $idb) {
  6220. return $idb <=> $ida;
  6221. }
  6222. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6223. }
  6224. if ($ta === '') {
  6225. return 1;
  6226. }
  6227. if ($tb === '') {
  6228. return -1;
  6229. }
  6230. return strcmp($tb, $ta);
  6231. });
  6232. return $out;
  6233. }
  6234. /**
  6235. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6236. *
  6237. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6238. */
  6239. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6240. {
  6241. $scydgyId = trim($scydgyId);
  6242. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6243. if ($scydgyId === '') {
  6244. return $empty;
  6245. }
  6246. try {
  6247. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6248. } catch (\Throwable $e) {
  6249. $anchor = null;
  6250. }
  6251. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6252. return $empty;
  6253. }
  6254. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6255. if ($ccydh === '') {
  6256. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6257. }
  6258. try {
  6259. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6260. } catch (\Throwable $e) {
  6261. $pos = [$anchor];
  6262. }
  6263. if (!is_array($pos) || $pos === []) {
  6264. $pos = [$anchor];
  6265. }
  6266. return [
  6267. 'ccydh' => $ccydh,
  6268. 'pos' => $pos,
  6269. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6270. ];
  6271. }
  6272. /**
  6273. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6274. */
  6275. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6276. {
  6277. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6278. return false;
  6279. }
  6280. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6281. return false;
  6282. }
  6283. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6284. return true;
  6285. }
  6286. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6287. $sid = (int)($po['scydgy_id'] ?? 0);
  6288. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6289. }
  6290. return false;
  6291. }
  6292. /**
  6293. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6294. *
  6295. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6296. */
  6297. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6298. {
  6299. $scydgyId = trim($scydgyId);
  6300. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6301. if ($scydgyId === '') {
  6302. return $empty;
  6303. }
  6304. try {
  6305. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6306. } catch (\Throwable $e) {
  6307. $anchor = null;
  6308. }
  6309. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6310. return $empty;
  6311. }
  6312. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6313. if ($ccydh === '') {
  6314. return [
  6315. 'ccydh' => '',
  6316. 'pos' => [$anchor],
  6317. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6318. ];
  6319. }
  6320. try {
  6321. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6322. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6323. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6324. } catch (\Throwable $e) {
  6325. $pos = [$anchor];
  6326. }
  6327. if (!is_array($pos) || $pos === []) {
  6328. $pos = [$anchor];
  6329. }
  6330. $pos = array_values(array_filter($pos, function ($po) {
  6331. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6332. }));
  6333. if ($pos === []) {
  6334. $pos = [$anchor];
  6335. }
  6336. return [
  6337. 'ccydh' => $ccydh,
  6338. 'pos' => $pos,
  6339. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6340. ];
  6341. }
  6342. /**
  6343. * @param array<int, array<string, mixed>> $purchaseOrders
  6344. * @return array<int, array<string, mixed>>
  6345. */
  6346. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6347. {
  6348. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6349. $byId = [];
  6350. foreach ($pool as $r) {
  6351. if (!is_array($r)) {
  6352. continue;
  6353. }
  6354. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6355. if ($this->isValidScydgyRowId($sid)) {
  6356. $byId[$sid] = $r;
  6357. }
  6358. }
  6359. $out = [];
  6360. foreach ($purchaseOrders as $po) {
  6361. if (!is_array($po)) {
  6362. continue;
  6363. }
  6364. $sid = (int)($po['scydgy_id'] ?? 0);
  6365. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6366. $out[] = $byId[$sid];
  6367. }
  6368. }
  6369. return $out;
  6370. }
  6371. /**
  6372. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6373. *
  6374. * @return array<int, array<string, mixed>>
  6375. */
  6376. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6377. {
  6378. $scydgyId = trim($scydgyId);
  6379. if ($scydgyId === '') {
  6380. return [];
  6381. }
  6382. try {
  6383. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6384. } catch (\Throwable $e) {
  6385. $anchor = null;
  6386. }
  6387. if (!is_array($anchor)) {
  6388. return [];
  6389. }
  6390. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6391. return [];
  6392. }
  6393. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6394. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6395. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6396. try {
  6397. $q = Db::table('purchase_order');
  6398. if ($ccydh !== '') {
  6399. $q->where('CCYDH', $ccydh);
  6400. } else {
  6401. $q->where('scydgy_id', $scydgyId);
  6402. }
  6403. if ($isValidPick) {
  6404. $q->where('pick_time', $pickTime);
  6405. }
  6406. $pos = $q->order('scydgy_id', 'asc')->select();
  6407. } catch (\Throwable $e) {
  6408. $pos = [$anchor];
  6409. }
  6410. if (!is_array($pos) || $pos === []) {
  6411. $pos = [$anchor];
  6412. }
  6413. $pos = array_values(array_filter($pos, function ($po) {
  6414. if (!is_array($po)) {
  6415. return false;
  6416. }
  6417. $mr = $po['mod_rq'] ?? null;
  6418. if ($mr === null || $mr === '') {
  6419. return true;
  6420. }
  6421. $mrs = trim((string)$mr);
  6422. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6423. }));
  6424. if ($pos === []) {
  6425. $pos = [$anchor];
  6426. }
  6427. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6428. if ($rows === []) {
  6429. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6430. }
  6431. return $rows;
  6432. }
  6433. /**
  6434. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6435. *
  6436. * @param array<int, array<string, mixed>> $mergeRows
  6437. * @return array<int, array<string, mixed>>
  6438. */
  6439. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6440. {
  6441. $list = array_values($mergeRows);
  6442. $n = count($list);
  6443. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6444. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6445. $mergeSame = $n > 1 && $orderKey0 !== '';
  6446. if ($mergeSame) {
  6447. foreach ($list as $rr) {
  6448. if (!is_array($rr)) {
  6449. $mergeSame = false;
  6450. break;
  6451. }
  6452. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6453. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6454. $mergeSame = false;
  6455. break;
  6456. }
  6457. }
  6458. }
  6459. $out = [];
  6460. foreach ($list as $idx => $r) {
  6461. if (!is_array($r)) {
  6462. continue;
  6463. }
  6464. $qty = $this->resolveProcuremenThisQuantity($r);
  6465. $price = $this->resolveProcuremenCeilingPrice($r);
  6466. $sid = $this->extractScydgyRowId($r);
  6467. $out[] = [
  6468. 'seq' => $idx + 1,
  6469. 'scydgy_id' => $sid,
  6470. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6471. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6472. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6473. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6474. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6475. 'NGZL' => $r['NGZL'] ?? '',
  6476. 'This_quantity' => $qty,
  6477. 'ceilingPrice' => $price,
  6478. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6479. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6480. 'show_order_cells' => !$mergeSame || $idx === 0,
  6481. 'order_rowspan' => $mergeSame ? $n : 1,
  6482. ];
  6483. }
  6484. return $out;
  6485. }
  6486. /**
  6487. * 解析金额/数量(去千分位等非数字字符)
  6488. */
  6489. protected function parseProcuremenMoneyNumber($value): ?float
  6490. {
  6491. if ($value === null || $value === '') {
  6492. return null;
  6493. }
  6494. if (is_numeric($value)) {
  6495. return (float)$value;
  6496. }
  6497. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6498. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6499. }
  6500. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6501. {
  6502. if ($amount === null) {
  6503. return '';
  6504. }
  6505. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6506. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6507. return $s === '' ? '0' : $s;
  6508. }
  6509. /**
  6510. * 列表/详情展示:工作量为 0 时显示空
  6511. */
  6512. protected function formatProcuremenWorkloadDisplay($value): string
  6513. {
  6514. if ($value === null || $value === '') {
  6515. return '';
  6516. }
  6517. $s = trim((string)$value);
  6518. if ($s === '') {
  6519. return '';
  6520. }
  6521. if (is_numeric($s) && (float)$s == 0) {
  6522. return '';
  6523. }
  6524. return $s;
  6525. }
  6526. /**
  6527. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6528. */
  6529. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6530. {
  6531. foreach ($details as $d) {
  6532. if (!is_array($d)) {
  6533. continue;
  6534. }
  6535. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6536. $cn = trim((string)($d['company_name'] ?? ''));
  6537. if ($cn !== '') {
  6538. return $cn;
  6539. }
  6540. }
  6541. }
  6542. return trim((string)($main['pick_company_name'] ?? ''));
  6543. }
  6544. /**
  6545. * 详情报价小计:单价 × 本工序本次数量
  6546. */
  6547. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6548. {
  6549. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6550. if ($unit === null) {
  6551. return null;
  6552. }
  6553. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6554. if ($qty === null || $qty <= 0) {
  6555. return null;
  6556. }
  6557. return $unit * $qty;
  6558. }
  6559. /**
  6560. * 详情页:工序小计 + 供应商分组报价与总计
  6561. *
  6562. * @param array<int, array<string, mixed>> $mergeRows
  6563. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6564. * @return array{
  6565. * process_rows: array,
  6566. * supplier_groups: array,
  6567. * order_total_text: string,
  6568. * order_total_has: bool,
  6569. * selected_company: string
  6570. * }
  6571. */
  6572. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6573. {
  6574. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6575. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6576. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6577. || ((int)($main['manual_pick'] ?? 0) === 1);
  6578. $qtyBySid = [];
  6579. $gymcBySid = [];
  6580. $orderedSids = [];
  6581. foreach ($mergeRows as $mr) {
  6582. if (!is_array($mr)) {
  6583. continue;
  6584. }
  6585. $sid = $this->extractScydgyRowId($mr);
  6586. if ($this->isValidScydgyRowId($sid)) {
  6587. $orderedSids[] = $sid;
  6588. }
  6589. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6590. if ($qty === '') {
  6591. $qty = trim((string)($mr['NGZL'] ?? ''));
  6592. }
  6593. $qtyBySid[$sid] = $qty;
  6594. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6595. }
  6596. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6597. $detailByCompanySid = [];
  6598. foreach ($details as $d) {
  6599. if (!is_array($d)) {
  6600. continue;
  6601. }
  6602. $cn = trim((string)($d['company_name'] ?? ''));
  6603. $sid = (int)($d['scydgy_id'] ?? 0);
  6604. if ($cn === '' || $sid === 0) {
  6605. continue;
  6606. }
  6607. if (!isset($detailByCompanySid[$cn])) {
  6608. $detailByCompanySid[$cn] = [];
  6609. }
  6610. $detailByCompanySid[$cn][$sid] = $d;
  6611. }
  6612. $supplierGroups = [];
  6613. foreach ($detailByCompanySid as $cn => $bySid) {
  6614. $lines = [];
  6615. $groupTotal = 0.0;
  6616. $groupHas = false;
  6617. $groupVoid = true;
  6618. $usedSids = [];
  6619. $appendLine = function (int $sid, array $d) use (
  6620. &$lines,
  6621. &$groupTotal,
  6622. &$groupHas,
  6623. &$groupVoid,
  6624. $qtyBySid,
  6625. $gymcBySid,
  6626. $quoteVisible
  6627. ) {
  6628. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6629. if (!$isVoid) {
  6630. $groupVoid = false;
  6631. }
  6632. $qtyStr = $qtyBySid[$sid] ?? '';
  6633. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6634. $am = trim((string)($d['amount'] ?? ''));
  6635. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6636. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6637. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6638. $sub = null;
  6639. if (!$isVoid && $amountNum !== null) {
  6640. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6641. }
  6642. $ct = $this->resolveDetailSupplierOperTime($d);
  6643. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6644. $leadFilled = ($leadDays !== null);
  6645. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6646. $line = [
  6647. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6648. 'amount' => $am,
  6649. 'unit_price_text' => $amountFilled
  6650. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6651. : '未填写',
  6652. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6653. 'delivery_ymd' => $deliveryYmd,
  6654. 'amount_filled' => $amountFilled,
  6655. 'delivery_filled' => $deliveryFilled,
  6656. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6657. 'lead_days' => $leadFilled ? $leadDays : '',
  6658. 'lead_days_filled'=> $leadFilled,
  6659. 'lead_days_show' => $leadText,
  6660. 'lead_days_text' => $leadText,
  6661. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6662. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6663. 'is_void' => $isVoid,
  6664. 'oper_time_text' => $ct,
  6665. ];
  6666. if (!$quoteVisible && !$isVoid) {
  6667. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6668. } elseif ($sub !== null) {
  6669. $groupTotal += $sub;
  6670. $groupHas = true;
  6671. }
  6672. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6673. };
  6674. foreach ($orderedSids as $sid) {
  6675. if (!isset($bySid[$sid])) {
  6676. continue;
  6677. }
  6678. $usedSids[$sid] = true;
  6679. $appendLine($sid, $bySid[$sid]);
  6680. }
  6681. foreach ($bySid as $sid => $d) {
  6682. if (isset($usedSids[$sid])) {
  6683. continue;
  6684. }
  6685. $appendLine((int)$sid, $d);
  6686. }
  6687. $firstDetail = null;
  6688. foreach ($bySid as $d) {
  6689. if (is_array($d)) {
  6690. $firstDetail = $d;
  6691. break;
  6692. }
  6693. }
  6694. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6695. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6696. if ($username === '' && $ph !== '') {
  6697. $username = $this->resolveCustomerContactName($ph, $cn);
  6698. }
  6699. $remark = '';
  6700. foreach ($bySid as $d) {
  6701. if (!is_array($d)) {
  6702. continue;
  6703. }
  6704. $rm = '';
  6705. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6706. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6707. $rm = trim((string)$d[$rk]);
  6708. break;
  6709. }
  6710. }
  6711. if ($rm !== '') {
  6712. $remark = $rm;
  6713. break;
  6714. }
  6715. }
  6716. $lineCount = count($lines);
  6717. $hasRemark = $lineCount > 0;
  6718. $supplierGroup = [
  6719. 'company_name' => $cn,
  6720. 'username' => $username,
  6721. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6722. 'phone' => $ph,
  6723. 'remark' => $remark,
  6724. 'has_remark' => $hasRemark,
  6725. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6726. 'is_void' => $groupVoid,
  6727. 'lines' => $lines,
  6728. 'line_count' => $lineCount,
  6729. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6730. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6731. 'has_total' => $lineCount > 0,
  6732. ];
  6733. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6734. $supplierGroups[] = $supplierGroup;
  6735. }
  6736. usort($supplierGroups, function ($a, $b) {
  6737. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6738. return ($a['is_void'] ?? false) ? 1 : -1;
  6739. }
  6740. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6741. return ($a['is_selected'] ?? false) ? -1 : 1;
  6742. }
  6743. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6744. });
  6745. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6746. return [
  6747. 'process_rows' => $processRows,
  6748. 'supplier_groups' => $supplierGroups,
  6749. 'order_total_text' => '',
  6750. 'order_total_has' => false,
  6751. 'selected_company' => $selectedCompany,
  6752. ];
  6753. }
  6754. /**
  6755. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  6756. */
  6757. protected function buildProcessLinesPlain(array $mergeRows): string
  6758. {
  6759. $lines = [];
  6760. $i = 1;
  6761. foreach ($mergeRows as $r) {
  6762. if (!is_array($r)) {
  6763. continue;
  6764. }
  6765. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6766. $dw = trim((string)($r['CDW'] ?? ''));
  6767. $gzl = trim((string)($r['NGZL'] ?? ''));
  6768. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6769. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  6770. if ($dw !== '') {
  6771. $parts[] = '单位:' . $dw;
  6772. }
  6773. if ($gzl !== '') {
  6774. $parts[] = '工作量:' . $gzl;
  6775. }
  6776. if ($qty !== '') {
  6777. $parts[] = '本次数量:' . $qty;
  6778. }
  6779. $lines[] = implode(' ', $parts);
  6780. $i++;
  6781. }
  6782. return implode("\n", $lines);
  6783. }
  6784. /**
  6785. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  6786. *
  6787. * @return array<string, string>
  6788. */
  6789. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  6790. {
  6791. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  6792. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  6793. }
  6794. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  6795. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  6796. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6797. $cyjmc = '';
  6798. foreach ($mergeRows as $mr) {
  6799. if (!is_array($mr)) {
  6800. continue;
  6801. }
  6802. if ($ccydh === '') {
  6803. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  6804. }
  6805. if ($cyjmc === '') {
  6806. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  6807. }
  6808. }
  6809. if ($pos !== []) {
  6810. $firstPo = $pos[0];
  6811. if (is_array($firstPo)) {
  6812. if ($ccydh === '') {
  6813. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  6814. }
  6815. if ($cyjmc === '') {
  6816. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  6817. }
  6818. }
  6819. }
  6820. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  6821. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  6822. if (is_array($any)) {
  6823. if ($ccydh === '') {
  6824. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  6825. }
  6826. if ($cyjmc === '') {
  6827. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  6828. }
  6829. }
  6830. }
  6831. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  6832. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  6833. $cgymc = '';
  6834. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  6835. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  6836. }
  6837. return [
  6838. 'ccydh' => $ccydh,
  6839. 'cyjmc' => $cyjmc,
  6840. 'cgymc' => $cgymc,
  6841. 'process_lines' => $processLines,
  6842. 'process_lines_html' => '',
  6843. ];
  6844. }
  6845. /**
  6846. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  6847. */
  6848. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  6849. {
  6850. $lines = [];
  6851. if ($ccydh !== '') {
  6852. $lines[] = '订单号:' . $ccydh;
  6853. }
  6854. if ($cyjmc !== '') {
  6855. $lines[] = '印件名称:' . $cyjmc;
  6856. }
  6857. if ($processPlain !== '') {
  6858. $lines[] = $processPlain;
  6859. }
  6860. return implode("\n", $lines);
  6861. }
  6862. /**
  6863. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  6864. *
  6865. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6866. */
  6867. protected function buildPlatformLinksPlain(array $detailLinks): string
  6868. {
  6869. $lines = [];
  6870. $i = 1;
  6871. foreach ($detailLinks as $lk) {
  6872. if (!is_array($lk)) {
  6873. continue;
  6874. }
  6875. $url = trim((string)($lk['url'] ?? ''));
  6876. if ($url === '') {
  6877. continue;
  6878. }
  6879. $label = trim((string)($lk['cgymc'] ?? ''));
  6880. if ($label === '') {
  6881. $label = '工序' . $i;
  6882. }
  6883. $lines[] = $label . ':' . $url;
  6884. $i++;
  6885. }
  6886. return implode("\n", $lines);
  6887. }
  6888. /**
  6889. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  6890. *
  6891. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6892. */
  6893. protected function buildPlatformLinksHtml(array $detailLinks): string
  6894. {
  6895. $parts = [];
  6896. $i = 1;
  6897. foreach ($detailLinks as $lk) {
  6898. if (!is_array($lk)) {
  6899. continue;
  6900. }
  6901. $url = trim((string)($lk['url'] ?? ''));
  6902. if ($url === '') {
  6903. continue;
  6904. }
  6905. $label = trim((string)($lk['cgymc'] ?? ''));
  6906. if ($label === '') {
  6907. $label = '工序' . $i;
  6908. }
  6909. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  6910. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  6911. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  6912. $i++;
  6913. }
  6914. return implode("<br>\n", $parts);
  6915. }
  6916. /**
  6917. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  6918. *
  6919. * @return array<string, mixed>
  6920. */
  6921. protected function loadMailerConfig(): array
  6922. {
  6923. try {
  6924. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  6925. } catch (\Throwable $e) {
  6926. $cfg = [];
  6927. }
  6928. return is_array($cfg) ? $cfg : [];
  6929. }
  6930. protected function loadNotifyTemplateRow(string $scene): ?array
  6931. {
  6932. try {
  6933. $row = Db::table('purchase_sms_template')
  6934. ->where('scene', $scene)
  6935. ->where(function ($q) {
  6936. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  6937. })
  6938. ->order('id', 'asc')
  6939. ->find();
  6940. } catch (\Throwable $e) {
  6941. return null;
  6942. }
  6943. if (!is_array($row) || $row === []) {
  6944. return null;
  6945. }
  6946. return [
  6947. 'title' => trim((string)($row['title'] ?? '')),
  6948. 'content' => trim((string)($row['content'] ?? '')),
  6949. ];
  6950. }
  6951. /**
  6952. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  6953. */
  6954. protected function buildProcessLinesHtml(array $mergeRows): string
  6955. {
  6956. if (count($mergeRows) <= 1) {
  6957. $r = $mergeRows[0] ?? [];
  6958. if (!is_array($r)) {
  6959. return '';
  6960. }
  6961. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6962. $dw = trim((string)($r['CDW'] ?? ''));
  6963. $gzl = trim((string)($r['NGZL'] ?? ''));
  6964. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6965. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  6966. if ($dw !== '') {
  6967. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  6968. }
  6969. if ($gzl !== '') {
  6970. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  6971. }
  6972. if ($qty !== '') {
  6973. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  6974. }
  6975. return $html;
  6976. }
  6977. $rows = '';
  6978. $i = 1;
  6979. foreach ($mergeRows as $r) {
  6980. if (!is_array($r)) {
  6981. continue;
  6982. }
  6983. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  6984. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  6985. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  6986. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  6987. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  6988. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  6989. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  6990. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  6991. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  6992. $i++;
  6993. }
  6994. if ($rows === '') {
  6995. return '';
  6996. }
  6997. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  6998. . '<thead><tr style="background:#f5f5f5;">'
  6999. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  7000. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  7001. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  7002. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  7003. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  7004. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7005. }
  7006. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7007. {
  7008. $sysRq = trim($sysRq);
  7009. if ($sysRq === '') {
  7010. if ($required) {
  7011. $this->error('请选择招标截止日期');
  7012. }
  7013. return '';
  7014. }
  7015. $ts = strtotime($sysRq);
  7016. if ($ts === false || $ts <= 0) {
  7017. $this->error('招标截止日期格式无效');
  7018. }
  7019. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7020. if (!$allowPast) {
  7021. $ymd = date('Y-m-d', $ts);
  7022. if ($ymd < date('Y-m-d')) {
  7023. $this->error('招标截止日期不能早于今天');
  7024. }
  7025. if ($ts <= time()) {
  7026. $this->error('招标截止时间不能早于当前时间');
  7027. }
  7028. }
  7029. return date('Y-m-d H:i:s', $ts);
  7030. }
  7031. /**
  7032. * 确保 purchase_order.czlyq(类型)存在
  7033. */
  7034. protected function ensurePurchaseOrderCzlyqColumn(): void
  7035. {
  7036. static $done = false;
  7037. if ($done) {
  7038. return;
  7039. }
  7040. $done = true;
  7041. try {
  7042. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7043. if (empty($cols)) {
  7044. Db::execute(
  7045. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7046. );
  7047. }
  7048. } catch (\Throwable $e) {
  7049. // ignore
  7050. }
  7051. }
  7052. /**
  7053. * 确保 purchase_order.delivery_deadline 存在
  7054. */
  7055. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7056. {
  7057. static $done = false;
  7058. if ($done) {
  7059. return;
  7060. }
  7061. $done = true;
  7062. try {
  7063. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7064. if (empty($cols)) {
  7065. Db::execute(
  7066. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7067. );
  7068. }
  7069. } catch (\Throwable $e) {
  7070. // ignore
  7071. }
  7072. }
  7073. /**
  7074. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7075. */
  7076. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7077. {
  7078. static $done = false;
  7079. if ($done) {
  7080. return;
  7081. }
  7082. $done = true;
  7083. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7084. $adds = [
  7085. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7086. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7087. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7088. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7089. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7090. ];
  7091. $changed = false;
  7092. foreach ($adds as $col => $ddl) {
  7093. try {
  7094. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7095. if (!is_array($cols) || $cols === []) {
  7096. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7097. $changed = true;
  7098. }
  7099. } catch (\Throwable $e) {
  7100. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7101. }
  7102. }
  7103. if ($changed) {
  7104. $this->clearPurchaseOrderTableFieldsCache();
  7105. }
  7106. }
  7107. /**
  7108. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7109. */
  7110. protected function clearPurchaseOrderTableFieldsCache(): void
  7111. {
  7112. try {
  7113. $db = (string)Config::get('database.database');
  7114. $key = $db . '.purchase_order';
  7115. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7116. $ref->setAccessible(true);
  7117. $info = $ref->getValue();
  7118. if (is_array($info) && isset($info[$key])) {
  7119. unset($info[$key]);
  7120. $ref->setValue(null, $info);
  7121. }
  7122. } catch (\Throwable $e) {
  7123. }
  7124. try {
  7125. $db = (string)Config::get('database.database');
  7126. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7127. if (is_file($schemaFile)) {
  7128. @unlink($schemaFile);
  7129. }
  7130. } catch (\Throwable $e) {
  7131. }
  7132. }
  7133. /**
  7134. * @return array<string, bool>
  7135. */
  7136. protected function loadPurchaseOrderColumnSet(): array
  7137. {
  7138. static $set = null;
  7139. if (is_array($set)) {
  7140. return $set;
  7141. }
  7142. $set = [];
  7143. try {
  7144. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7145. } catch (\Throwable $e) {
  7146. return $set;
  7147. }
  7148. if (!is_array($cols)) {
  7149. return $set;
  7150. }
  7151. foreach ($cols as $c) {
  7152. if (!is_array($c)) {
  7153. continue;
  7154. }
  7155. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7156. if ($f !== '') {
  7157. $set[$f] = true;
  7158. }
  7159. }
  7160. return $set;
  7161. }
  7162. /**
  7163. * 解析交货截止日期(仅年月日)
  7164. */
  7165. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7166. {
  7167. $raw = trim($raw);
  7168. if ($raw === '') {
  7169. if ($required) {
  7170. $this->error('请选择交货截止日期');
  7171. }
  7172. return '';
  7173. }
  7174. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7175. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7176. } else {
  7177. $ts = strtotime(str_replace('/', '-', $raw));
  7178. if ($ts === false || $ts <= 0) {
  7179. $this->error('交货截止日期格式无效');
  7180. }
  7181. $ymd = date('Y-m-d', $ts);
  7182. }
  7183. if ($ymd < date('Y-m-d')) {
  7184. $this->error('交货截止日期不能早于今天');
  7185. }
  7186. return $ymd;
  7187. }
  7188. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7189. {
  7190. $s = trim((string)$value);
  7191. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7192. return '';
  7193. }
  7194. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7195. return $m[1];
  7196. }
  7197. $ts = strtotime(str_replace('/', '-', $s));
  7198. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7199. }
  7200. /**
  7201. * @param array{pos?:array} $bundle
  7202. */
  7203. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7204. {
  7205. foreach ($bundle['pos'] ?? [] as $po) {
  7206. if (!is_array($po)) {
  7207. continue;
  7208. }
  7209. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7210. if ($d !== '') {
  7211. return $d;
  7212. }
  7213. }
  7214. return '';
  7215. }
  7216. protected function formatProcuremenSysRqForInput($sysRq): string
  7217. {
  7218. $sr = trim((string)$sysRq);
  7219. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7220. return '';
  7221. }
  7222. $ts = strtotime($sr);
  7223. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7224. }
  7225. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7226. {
  7227. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7228. if ($sr === '') {
  7229. return '—';
  7230. }
  7231. $ts = strtotime($sr);
  7232. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7233. }
  7234. /**
  7235. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7236. *
  7237. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7238. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7239. */
  7240. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7241. {
  7242. return $bundle;
  7243. }
  7244. /**
  7245. * 写入/更新 purchase_order(单道工序行)
  7246. *
  7247. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7248. */
  7249. protected function upsertPurchaseOrderFromRow(
  7250. array $row,
  7251. string $sysRqDb,
  7252. $wflowStatus = null,
  7253. ?string $pickTime = null,
  7254. ?array $exists = null,
  7255. ?string $deliveryDeadline = null,
  7256. $scoreRuleId = null
  7257. ): void {
  7258. $ids = $this->extractScydgyRowId($row);
  7259. if (!$this->isValidScydgyRowId($ids)) {
  7260. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7261. }
  7262. if ($exists === null) {
  7263. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7264. }
  7265. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7266. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7267. $this->ensurePurchaseOrderCzlyqColumn();
  7268. $data = [
  7269. 'scydgy_id' => $ids,
  7270. 'CCYDH' => $row['CCYDH'] ?? null,
  7271. 'CYJMC' => $row['CYJMC'] ?? null,
  7272. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7273. 'CDXMC' => $row['CDXMC'] ?? null,
  7274. 'CGYBH' => $row['CGYBH'] ?? null,
  7275. 'CGYMC' => $row['CGYMC'] ?? null,
  7276. 'CDW' => $row['CDW'] ?? null,
  7277. 'czlyq' => $row['czlyq'] ?? null,
  7278. 'NGZL' => $row['NGZL'] ?? null,
  7279. 'CDF' => $row['CDF'] ?? null,
  7280. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7281. 'MBZ' => $row['MBZ'] ?? null,
  7282. 'bwjg' => $row['bwjg'] ?? null,
  7283. 'iStatus' => $row['iStatus'] ?? null,
  7284. 'dStamp' => $row['dStamp'] ?? null,
  7285. 'dputrecord' => $row['dputrecord'] ?? null,
  7286. 'cywyxm' => $row['cywyxm'] ?? null,
  7287. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7288. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7289. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7290. 'sys_rq' => $sysRqDb,
  7291. ];
  7292. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7293. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7294. if ($qtyUp === '') {
  7295. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7296. 'This_quantity' => '',
  7297. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7298. ]);
  7299. if ($qtyFallback !== '') {
  7300. $data['This_quantity'] = $qtyFallback;
  7301. }
  7302. }
  7303. if ($deliveryDeadline !== null) {
  7304. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7305. }
  7306. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7307. $scoreRule = null;
  7308. if (is_array($scoreRuleId)) {
  7309. $scoreRule = $scoreRuleId;
  7310. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7311. } else {
  7312. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7313. }
  7314. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7315. $poCols = $this->loadPurchaseOrderColumnSet();
  7316. if (!empty($poCols['score_rule_id'])) {
  7317. $data['score_rule_id'] = $scoreRuleId;
  7318. if (is_array($scoreRule)) {
  7319. if (!empty($poCols['score_rule_name'])) {
  7320. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7321. }
  7322. if (!empty($poCols['score_quality_weight'])) {
  7323. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7324. }
  7325. if (!empty($poCols['score_price_weight'])) {
  7326. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7327. }
  7328. if (!empty($poCols['score_lead_weight'])) {
  7329. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7330. }
  7331. }
  7332. }
  7333. }
  7334. if ($wflowStatus !== null && $wflowStatus !== '') {
  7335. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7336. }
  7337. if ($pickTime !== null && $pickTime !== '') {
  7338. $data['pick_time'] = $pickTime;
  7339. $data['pick_company_name'] = '';
  7340. }
  7341. if ($exists) {
  7342. $upd = $data;
  7343. unset($upd['scydgy_id']);
  7344. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7345. } else {
  7346. $data['createtime'] = date('Y-m-d H:i:s');
  7347. Db::table('purchase_order')->insert($data);
  7348. }
  7349. }
  7350. /**
  7351. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7352. *
  7353. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7354. */
  7355. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7356. {
  7357. $toDb = function ($value) {
  7358. if ($value === null) {
  7359. return null;
  7360. }
  7361. if (is_scalar($value)) {
  7362. return $value;
  7363. }
  7364. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7365. };
  7366. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7367. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7368. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7369. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7370. if ($username === '') {
  7371. $username = $this->resolveCustomerContactName($phone, $companyName);
  7372. }
  7373. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7374. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7375. }
  7376. if ($requirePhone && $phone === '') {
  7377. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7378. }
  7379. $detailLinks = [];
  7380. foreach ($mergeRows as $row) {
  7381. if (!is_array($row)) {
  7382. continue;
  7383. }
  7384. $sid = $this->extractScydgyRowId($row);
  7385. $detailId = 0;
  7386. if ($skipExisting) {
  7387. try {
  7388. $existsQuery = Db::table('purchase_order_detail')
  7389. ->where('scydgy_id', $sid)
  7390. ->where('company_name', $companyName);
  7391. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7392. $exists = $existsQuery->find();
  7393. } catch (\Throwable $e) {
  7394. $exists = null;
  7395. }
  7396. if (is_array($exists)) {
  7397. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7398. }
  7399. }
  7400. if ($detailId <= 0) {
  7401. $one = [
  7402. 'scydgy_id' => $toDb($sid),
  7403. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7404. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7405. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7406. 'username' => $username !== '' ? $username : null,
  7407. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7408. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7409. 'createtime' => date('Y-m-d H:i:s'),
  7410. 'status' => ProcuremenStatus::POD_UNPICKED,
  7411. 'status_name' => '未提交',
  7412. ];
  7413. Db::table('purchase_order_detail')->insert($one);
  7414. $detailId = (int)Db::getLastInsID();
  7415. }
  7416. $mprocUrl = '';
  7417. if ($buildMobileLinks && $detailId > 0) {
  7418. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  7419. }
  7420. $detailLinks[] = [
  7421. 'detail_id' => $detailId,
  7422. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7423. 'url' => $mprocUrl,
  7424. ];
  7425. }
  7426. $this->invalidatePickHiddenScydgyCache();
  7427. return $detailLinks;
  7428. }
  7429. /**
  7430. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7431. * @return array<string, mixed>
  7432. */
  7433. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  7434. {
  7435. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7436. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7437. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7438. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7439. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7440. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7441. $isMerge = !empty($ctx['is_merge']);
  7442. $contactName = trim((string)($c['username'] ?? ''));
  7443. if ($contactName === '') {
  7444. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7445. }
  7446. $notifyVars = [
  7447. 'company_name' => $companyName,
  7448. 'contact_name' => $contactName,
  7449. 'phone' => $phone,
  7450. 'email' => $toEmail,
  7451. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7452. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7453. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7454. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7455. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7456. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7457. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7458. 'platform_url' => $platformUrl,
  7459. 'platform_links' => $platformLinksPlain,
  7460. 'platform_links_html' => $platformLinksHtml,
  7461. ];
  7462. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7463. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  7464. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7465. return [
  7466. 'company_name' => $companyName,
  7467. 'phone' => $phone,
  7468. 'email' => $toEmail,
  7469. 'sms_content' => $smsContent,
  7470. 'mail_plain' => $mailPlain,
  7471. 'mail_body' => $mailBody,
  7472. 'notify_vars' => $notifyVars,
  7473. 'detail_links' => $detailLinks,
  7474. ];
  7475. }
  7476. /**
  7477. * @param array<string, mixed> $chosen
  7478. * @param array<int, array<string, mixed>> $mergeRows
  7479. * @param array{ccydh:string, pos:array} $bundle
  7480. */
  7481. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  7482. {
  7483. if (!$sendSms && !$sendEmail) {
  7484. return;
  7485. }
  7486. $companyName = trim((string)($chosen['name'] ?? ''));
  7487. $phone = trim((string)($chosen['phone'] ?? ''));
  7488. $toEmail = trim((string)($chosen['email'] ?? ''));
  7489. if ($companyName === '') {
  7490. throw new \Exception('供应商名称无效');
  7491. }
  7492. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7493. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7494. }
  7495. if ($sendSms && $phone === '') {
  7496. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7497. }
  7498. $sids = [];
  7499. foreach ($mergeRows as $mr) {
  7500. if (!is_array($mr)) {
  7501. continue;
  7502. }
  7503. $sid = $this->extractScydgyRowId($mr);
  7504. if ($this->isValidScydgyRowId($sid)) {
  7505. $sids[$sid] = true;
  7506. }
  7507. }
  7508. if ($sids === []) {
  7509. throw new \Exception('未找到工序行,无法发送通知');
  7510. }
  7511. $sysRqNotify = '';
  7512. $pos = $bundle['pos'] ?? [];
  7513. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7514. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7515. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7516. $ts = strtotime($sr);
  7517. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7518. }
  7519. }
  7520. try {
  7521. $detailsQuery = Db::table('purchase_order_detail')
  7522. ->where('scydgy_id', 'in', array_keys($sids))
  7523. ->where('company_name', $companyName);
  7524. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7525. $details = $detailsQuery->order('id', 'asc')->select();
  7526. } catch (\Throwable $e) {
  7527. $details = [];
  7528. }
  7529. if (!is_array($details) || $details === []) {
  7530. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7531. try {
  7532. $detailsQuery = Db::table('purchase_order_detail')
  7533. ->where('scydgy_id', 'in', array_keys($sids))
  7534. ->where('company_name', $companyName);
  7535. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7536. $details = $detailsQuery->order('id', 'asc')->select();
  7537. } catch (\Throwable $e) {
  7538. $details = [];
  7539. }
  7540. }
  7541. if (!is_array($details) || $details === []) {
  7542. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7543. }
  7544. $detailLinks = [];
  7545. foreach ($details as $d) {
  7546. if (!is_array($d)) {
  7547. continue;
  7548. }
  7549. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7550. if ($detailId <= 0) {
  7551. continue;
  7552. }
  7553. $sid = (int)($d['scydgy_id'] ?? 0);
  7554. $gymc = '';
  7555. foreach ($mergeRows as $mr) {
  7556. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7557. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7558. break;
  7559. }
  7560. }
  7561. $detailLinks[] = [
  7562. 'detail_id' => $detailId,
  7563. 'cgymc' => $gymc,
  7564. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  7565. ];
  7566. }
  7567. if ($detailLinks === []) {
  7568. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7569. }
  7570. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7571. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  7572. $notifyBundle['email_log_scene'] = $emailLogScene;
  7573. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7574. $poIdLog = 0;
  7575. $pos = $bundle['pos'] ?? [];
  7576. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7577. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7578. }
  7579. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7580. if ($sendEmail) {
  7581. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  7582. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7583. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  7584. }
  7585. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  7586. $mailConfig = $this->loadMailerConfig();
  7587. if (!$this->isProcuremenNotifyDryRun()) {
  7588. if (empty($mailConfig['host'])) {
  7589. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7590. }
  7591. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7592. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7593. }
  7594. }
  7595. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7596. }
  7597. if ($sendSms) {
  7598. $this->issueSendSupplierSms($notifyBundle);
  7599. }
  7600. }
  7601. /**
  7602. * @param array<int, array<string, mixed>> $quoteGroups
  7603. * @return array<int, array<string, mixed>>
  7604. */
  7605. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7606. {
  7607. $names = [];
  7608. if (is_string($companiesJson) && $companiesJson !== '') {
  7609. $decoded = json_decode($companiesJson, true);
  7610. if (is_array($decoded)) {
  7611. foreach ($decoded as $nm) {
  7612. $nm = trim((string)$nm);
  7613. if ($nm !== '') {
  7614. $names[] = $nm;
  7615. }
  7616. }
  7617. }
  7618. }
  7619. $names = array_values(array_unique($names));
  7620. if ($names === [] && $selectedCompany !== '') {
  7621. $names = [$selectedCompany];
  7622. }
  7623. if ($names === []) {
  7624. return $quoteGroups;
  7625. }
  7626. $targets = [];
  7627. foreach ($quoteGroups as $g) {
  7628. if (!is_array($g)) {
  7629. continue;
  7630. }
  7631. $cn = trim((string)($g['name'] ?? ''));
  7632. if ($cn !== '' && in_array($cn, $names, true)) {
  7633. $targets[] = $g;
  7634. }
  7635. }
  7636. return $targets;
  7637. }
  7638. /**
  7639. * @return array{pos:array, merge_rows:array, bundle:array}
  7640. */
  7641. protected function loadAuditResendBundle(string $scydgyId): array
  7642. {
  7643. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7644. $pos = $bundle['pos'];
  7645. $mergeRows = $bundle['merge_rows'];
  7646. if ($pos === [] || $mergeRows === []) {
  7647. $this->error('该订单不在待确认供应商状态');
  7648. }
  7649. $sysRqDb = '';
  7650. if (isset($pos[0]) && is_array($pos[0])) {
  7651. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7652. }
  7653. foreach ($pos as $i => $poRow) {
  7654. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7655. $pos[$i]['sys_rq'] = $sysRqDb;
  7656. }
  7657. }
  7658. $bundle['pos'] = $pos;
  7659. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7660. }
  7661. /**
  7662. * @param array<int, array<string, mixed>> $targets
  7663. */
  7664. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7665. {
  7666. if ($targets === []) {
  7667. $this->error('未找到可通知的供应商');
  7668. }
  7669. $notifyErrors = [];
  7670. try {
  7671. $this->notifyDryRunPreview = [];
  7672. foreach ($targets as $g) {
  7673. if (!is_array($g)) {
  7674. continue;
  7675. }
  7676. $cname = trim((string)($g['name'] ?? ''));
  7677. if ($cname === '') {
  7678. continue;
  7679. }
  7680. $chosen = [
  7681. 'name' => $cname,
  7682. 'company_name' => $cname,
  7683. 'email' => trim((string)($g['email'] ?? '')),
  7684. 'phone' => trim((string)($g['phone'] ?? '')),
  7685. 'username' => trim((string)($g['username'] ?? '')),
  7686. ];
  7687. try {
  7688. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7689. } catch (\Throwable $e) {
  7690. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7691. }
  7692. }
  7693. } catch (\Throwable $e) {
  7694. $this->error('通知发送失败:' . $e->getMessage());
  7695. }
  7696. if ($notifyErrors !== []) {
  7697. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7698. }
  7699. if ($this->isProcuremenNotifyDryRun()) {
  7700. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7701. 'notify_dry_run' => true,
  7702. 'notify_preview' => $this->notifyDryRunPreview,
  7703. ]);
  7704. }
  7705. $nameLabels = [];
  7706. foreach ($targets as $g) {
  7707. if (!is_array($g)) {
  7708. continue;
  7709. }
  7710. $n = trim((string)($g['name'] ?? ''));
  7711. if ($n !== '') {
  7712. $nameLabels[] = $n;
  7713. }
  7714. }
  7715. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7716. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7717. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7718. $seenLogSid = [];
  7719. foreach ($bundle['pos'] ?? [] as $poRow) {
  7720. if (!is_array($poRow)) {
  7721. continue;
  7722. }
  7723. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7724. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7725. continue;
  7726. }
  7727. $seenLogSid[$sid] = true;
  7728. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7729. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7730. }
  7731. if ($seenLogSid === []) {
  7732. foreach ($mergeRows as $mr) {
  7733. if (!is_array($mr)) {
  7734. continue;
  7735. }
  7736. $sid = $this->extractScydgyRowId($mr);
  7737. if ($this->isValidScydgyRowId($sid)) {
  7738. $this->addOrderLog($sid, $logAction, $logMsg, null);
  7739. break;
  7740. }
  7741. }
  7742. }
  7743. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  7744. }
  7745. /**
  7746. * 协助下发 — 发送短信(一家供应商)
  7747. *
  7748. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  7749. */
  7750. protected function issueSendSupplierSms(array $bundle): void
  7751. {
  7752. $companyName = (string)($bundle['company_name'] ?? '');
  7753. $phone = (string)($bundle['phone'] ?? '');
  7754. $smsContent = (string)($bundle['sms_content'] ?? '');
  7755. $this->logIssueNotifyDebug('短信', [
  7756. 'company' => $companyName,
  7757. 'phone' => $phone,
  7758. 'sms_content' => $smsContent,
  7759. ]);
  7760. if ($this->isProcuremenNotifyDryRun()) {
  7761. $this->recordNotifyDryRunPreview([
  7762. 'scene' => 'issue_sms',
  7763. 'company_name' => $companyName,
  7764. 'phone' => $phone,
  7765. 'sms_content' => $smsContent,
  7766. ]);
  7767. return;
  7768. }
  7769. $this->smsbao($phone, $smsContent);
  7770. }
  7771. /**
  7772. * 协助下发 — 发送邮件(一家供应商)
  7773. *
  7774. * @param array<string, mixed> $bundle
  7775. * @param array<string, mixed> $mailConfig
  7776. */
  7777. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  7778. {
  7779. $companyName = (string)($bundle['company_name'] ?? '');
  7780. $toEmail = (string)($bundle['email'] ?? '');
  7781. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  7782. $mailBody = (string)($bundle['mail_body'] ?? '');
  7783. $this->logIssueNotifyDebug('邮件', [
  7784. 'company' => $companyName,
  7785. 'email' => $toEmail,
  7786. 'mail_subject' => $mailSubject,
  7787. 'mail_body' => $mailPlain,
  7788. ]);
  7789. if ($this->isProcuremenNotifyDryRun()) {
  7790. $this->recordNotifyDryRunPreview([
  7791. 'scene' => 'issue_email',
  7792. 'company_name' => $companyName,
  7793. 'email' => $toEmail,
  7794. 'mail_subject' => $mailSubject,
  7795. 'mail_body' => $mailPlain,
  7796. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  7797. 'notify_vars' => $bundle['notify_vars'] ?? [],
  7798. 'detail_links' => $bundle['detail_links'] ?? [],
  7799. ]);
  7800. return;
  7801. }
  7802. $mail = new PHPMailer(true);
  7803. $mail->isSMTP();
  7804. $mail->Host = $mailConfig['host'];
  7805. $mail->SMTPAuth = true;
  7806. $mail->Username = $mailConfig['addr'];
  7807. $mail->Password = $mailConfig['pass'];
  7808. $mail->SMTPSecure = $mailConfig['security'];
  7809. $mail->Port = $mailConfig['port'];
  7810. $mail->CharSet = $mailConfig['charset'];
  7811. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  7812. $mail->addAddress($toEmail, $companyName);
  7813. $mail->isHTML(true);
  7814. $mail->Subject = $mailSubject;
  7815. $mail->Body = $mailBody;
  7816. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  7817. $sendOk = true;
  7818. $failReason = '';
  7819. try {
  7820. $mail->send();
  7821. } catch (\Throwable $e) {
  7822. $sendOk = false;
  7823. $failReason = $e->getMessage();
  7824. $this->persistEmailSendLog([
  7825. 'from_email' => $fromEmail,
  7826. 'to_email' => $toEmail,
  7827. 'send_time' => date('Y-m-d H:i:s'),
  7828. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7829. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7830. 'company_name' => $companyName,
  7831. 'mail_subject' => $mailSubject,
  7832. 'status' => 0,
  7833. 'fail_reason' => $failReason,
  7834. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7835. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7836. ]);
  7837. throw $e;
  7838. }
  7839. $this->persistEmailSendLog([
  7840. 'from_email' => $fromEmail,
  7841. 'to_email' => $toEmail,
  7842. 'send_time' => date('Y-m-d H:i:s'),
  7843. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7844. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7845. 'company_name' => $companyName,
  7846. 'mail_subject' => $mailSubject,
  7847. 'status' => 1,
  7848. 'fail_reason' => '',
  7849. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7850. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7851. ]);
  7852. }
  7853. /**
  7854. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  7855. *
  7856. * @param array<int, array<string, mixed>> $mergeRows
  7857. * @return array<string, mixed>
  7858. */
  7859. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  7860. {
  7861. $head = $mergeRows[0] ?? [];
  7862. $isMerge = count($mergeRows) > 1;
  7863. return [
  7864. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  7865. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  7866. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  7867. 'is_merge' => $isMerge,
  7868. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  7869. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  7870. 'deadline' => $sysRqNotify,
  7871. ];
  7872. }
  7873. /**
  7874. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  7875. *
  7876. * @param array<string, mixed> $data
  7877. */
  7878. protected function logIssueNotifyDebug(string $type, array $data): void
  7879. {
  7880. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  7881. return;
  7882. }
  7883. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  7884. }
  7885. protected function ensurePurchaseEmailSendLogTableOnce(): void
  7886. {
  7887. try {
  7888. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  7889. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7890. return;
  7891. } catch (\Throwable $e) {
  7892. }
  7893. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  7894. if (is_file($sqlFile)) {
  7895. $sql = file_get_contents($sqlFile);
  7896. if (is_string($sql) && $sql !== '') {
  7897. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  7898. $stmt = trim($stmt);
  7899. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  7900. continue;
  7901. }
  7902. try {
  7903. Db::execute($stmt);
  7904. } catch (\Throwable $ignore) {
  7905. }
  7906. }
  7907. }
  7908. }
  7909. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7910. }
  7911. /**
  7912. * @param array<string, mixed> $row
  7913. */
  7914. protected function persistEmailSendLog(array $row): void
  7915. {
  7916. try {
  7917. $this->ensurePurchaseEmailSendLogTableOnce();
  7918. } catch (\Throwable $e) {
  7919. return;
  7920. }
  7921. list($adminId, $adminName) = $this->GetUseName();
  7922. $cut = function ($s, $max) {
  7923. $s = (string)$s;
  7924. if (function_exists('mb_substr')) {
  7925. return mb_substr($s, 0, $max, 'UTF-8');
  7926. }
  7927. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  7928. };
  7929. $data = [
  7930. 'from_email' => $cut($row['from_email'] ?? '', 128),
  7931. 'to_email' => $cut($row['to_email'] ?? '', 128),
  7932. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  7933. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  7934. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  7935. 'company_name' => $cut($row['company_name'] ?? '', 128),
  7936. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  7937. 'status' => !empty($row['status']) ? 1 : 0,
  7938. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  7939. 'admin_id' => (int)$adminId,
  7940. 'admin_name' => $cut($adminName, 64),
  7941. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  7942. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  7943. 'createtime' => date('Y-m-d H:i:s'),
  7944. ];
  7945. try {
  7946. Db::table('purchase_email_send_log')->insert($data);
  7947. } catch (\Throwable $e) {
  7948. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  7949. }
  7950. }
  7951. protected function formatEmailLogSceneText(string $scene): string
  7952. {
  7953. $map = [
  7954. 'pick_issue' => '初选下发',
  7955. 'audit_resend' => '确认页重发',
  7956. 'rfq_salesman' => '询价通知业务员',
  7957. ];
  7958. return $map[$scene] ?? $scene;
  7959. }
  7960. /**
  7961. * 邮件发送日志列表
  7962. */
  7963. public function emailLog()
  7964. {
  7965. $this->relationSearch = false;
  7966. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  7967. $this->request->filter(['strip_tags', 'trim']);
  7968. $bakModel = $this->model;
  7969. $this->model = new \app\admin\model\Purchaseemailsendlog;
  7970. if ($this->request->isAjax()) {
  7971. $this->ensurePurchaseEmailSendLogTableOnce();
  7972. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  7973. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  7974. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  7975. $list = $this->model
  7976. ->where($where)
  7977. ->order($sortField, $orderDir)
  7978. ->paginate($limit);
  7979. $rows = [];
  7980. foreach ($list->items() as $item) {
  7981. $row = is_array($item) ? $item : $item->toArray();
  7982. $scene = trim((string)($row['scene'] ?? ''));
  7983. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  7984. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  7985. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  7986. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  7987. $rows[] = $row;
  7988. }
  7989. $this->model = $bakModel;
  7990. return json(['total' => $list->total(), 'rows' => $rows]);
  7991. }
  7992. $this->model = $bakModel;
  7993. return $this->view->fetch('procuremen/emaillog');
  7994. }
  7995. /**
  7996. * 协助下发弹窗(选多家供应商并通知)
  7997. */
  7998. public function pickReview()
  7999. {
  8000. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  8001. $this->error(__('You have no permission'));
  8002. }
  8003. if ($this->request->isPost()) {
  8004. $this->error('请使用弹窗内「确认下发」提交');
  8005. }
  8006. $this->view->assign('pickMode', 1);
  8007. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8008. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8009. }
  8010. /**
  8011. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8012. */
  8013. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  8014. {
  8015. static $done = false;
  8016. if ($done) {
  8017. return;
  8018. }
  8019. $done = true;
  8020. try {
  8021. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  8022. if (empty($cols)) {
  8023. Db::execute(
  8024. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8025. );
  8026. } else {
  8027. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8028. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8029. Db::execute(
  8030. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8031. );
  8032. }
  8033. }
  8034. } catch (\Throwable $e) {
  8035. // ignore
  8036. }
  8037. }
  8038. /**
  8039. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8040. */
  8041. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8042. {
  8043. static $done = false;
  8044. if ($done) {
  8045. return;
  8046. }
  8047. $done = true;
  8048. try {
  8049. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8050. if (empty($cols)) {
  8051. Db::execute(
  8052. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8053. );
  8054. }
  8055. } catch (\Throwable $e) {
  8056. // ignore
  8057. }
  8058. try {
  8059. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8060. if (empty($cols2)) {
  8061. Db::execute(
  8062. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8063. );
  8064. }
  8065. } catch (\Throwable $e) {
  8066. // ignore
  8067. }
  8068. }
  8069. /**
  8070. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8071. */
  8072. protected function ensureRfqSalesmanEmailTemplate(): void
  8073. {
  8074. static $done = false;
  8075. if ($done) {
  8076. return;
  8077. }
  8078. $done = true;
  8079. $content = "您好,{contact_name}:\n\n"
  8080. . "有新的协助采购询价需求,请知悉。\n"
  8081. . "印件名称:{cyjmc}\n"
  8082. . "工序名称:{cgymc}\n"
  8083. . "本次数量:{this_quantity}\n"
  8084. . "供应商:{supplier_name}\n"
  8085. . "需求发起人:{cywyxm}\n";
  8086. try {
  8087. $row = Db::table('purchase_sms_template')
  8088. ->where('scene', 'rfq_salesman_email')
  8089. ->find();
  8090. } catch (\Throwable $e) {
  8091. return;
  8092. }
  8093. $now = date('Y-m-d H:i:s');
  8094. if (is_array($row) && $row !== []) {
  8095. $old = (string)($row['content'] ?? '');
  8096. $needMigrate = (strpos($old, '需求编号:{ccydh}') !== false)
  8097. || (strpos($old, '{supplier_name}') === false && strpos($old, '供应商:') === false);
  8098. if ($needMigrate) {
  8099. $data = ['content' => $content];
  8100. try {
  8101. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8102. if (!empty($cols)) {
  8103. $data['updatetime'] = $now;
  8104. }
  8105. } catch (\Throwable $e) {
  8106. }
  8107. try {
  8108. Db::table('purchase_sms_template')
  8109. ->where('id', (int)($row['id'] ?? 0))
  8110. ->update($data);
  8111. } catch (\Throwable $e) {
  8112. }
  8113. }
  8114. return;
  8115. }
  8116. try {
  8117. $data = [
  8118. 'scene' => 'rfq_salesman_email',
  8119. 'title' => '询价邮箱通知',
  8120. 'content' => $content,
  8121. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8122. 'status' => 1,
  8123. ];
  8124. try {
  8125. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8126. } catch (\Throwable $e) {
  8127. $cols = [];
  8128. }
  8129. $colNames = [];
  8130. foreach ($cols as $c) {
  8131. if (!is_array($c)) {
  8132. continue;
  8133. }
  8134. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8135. if ($n !== '') {
  8136. $colNames[$n] = true;
  8137. }
  8138. }
  8139. if (isset($colNames['updatetime'])) {
  8140. $data['updatetime'] = $now;
  8141. }
  8142. if (isset($colNames['createtime'])) {
  8143. $data['createtime'] = $now;
  8144. }
  8145. Db::table('purchase_sms_template')->insert($data);
  8146. } catch (\Throwable $e) {
  8147. // ignore
  8148. }
  8149. }
  8150. /**
  8151. * 询价多选字段:数组或字符串统一为顿号拼接
  8152. *
  8153. * @param mixed $raw
  8154. */
  8155. protected function joinRfqMultiSelectValues($raw): string
  8156. {
  8157. $parts = [];
  8158. if (is_array($raw)) {
  8159. foreach ($raw as $item) {
  8160. if (is_array($item)) {
  8161. continue;
  8162. }
  8163. $v = trim((string)$item);
  8164. if ($v !== '') {
  8165. $parts[] = $v;
  8166. }
  8167. }
  8168. } else {
  8169. $s = trim((string)$raw);
  8170. if ($s !== '') {
  8171. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8172. $v = trim((string)$piece);
  8173. if ($v !== '') {
  8174. $parts[] = $v;
  8175. }
  8176. }
  8177. }
  8178. }
  8179. $parts = array_values(array_unique($parts));
  8180. return implode('、', $parts);
  8181. }
  8182. /**
  8183. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8184. *
  8185. * @return string[]
  8186. */
  8187. protected function loadRfqSupplierNameOptions(): array
  8188. {
  8189. $out = [];
  8190. try {
  8191. $rows = Db::table('customer')
  8192. ->where(function ($q) {
  8193. $q->where('status', 1)
  8194. ->whereOr('status', '1')
  8195. ->whereOr('status', '')
  8196. ->whereNull('status');
  8197. })
  8198. ->order('id', 'desc')
  8199. ->column('company_name');
  8200. } catch (\Throwable $e) {
  8201. return [];
  8202. }
  8203. if (!is_array($rows)) {
  8204. return [];
  8205. }
  8206. foreach ($rows as $name) {
  8207. $name = trim((string)$name);
  8208. if ($name === '' || isset($out[$name])) {
  8209. continue;
  8210. }
  8211. $out[$name] = $name;
  8212. }
  8213. return array_values($out);
  8214. }
  8215. /**
  8216. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8217. */
  8218. protected function rfqNotifySalesmanAuthGroupId(): int
  8219. {
  8220. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8221. if ($id > 0) {
  8222. return $id;
  8223. }
  8224. try {
  8225. $found = Db::name('auth_group')
  8226. ->where('name', '业务员')
  8227. ->where('status', 'normal')
  8228. ->order('id', 'asc')
  8229. ->value('id');
  8230. $id = (int)$found;
  8231. } catch (\Throwable $e) {
  8232. $id = 0;
  8233. }
  8234. return $id > 0 ? $id : 12;
  8235. }
  8236. /**
  8237. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8238. *
  8239. * @return string[]
  8240. */
  8241. protected function loadRfqSalesmanNameOptions(): array
  8242. {
  8243. $out = [];
  8244. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8245. $name = trim((string)($row['name'] ?? ''));
  8246. if ($name !== '') {
  8247. $out[] = $name;
  8248. }
  8249. }
  8250. return $out;
  8251. }
  8252. /**
  8253. * 业务员角色组下管理员:姓名、邮箱、手机
  8254. *
  8255. * @return array<int, array{name:string,email:string,mobile:string}>
  8256. */
  8257. protected function loadRfqSalesmanContactOptions(): array
  8258. {
  8259. $out = [];
  8260. $seen = [];
  8261. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8262. if ($groupId <= 0) {
  8263. return [];
  8264. }
  8265. try {
  8266. $adminIds = Db::name('auth_group_access')
  8267. ->where('group_id', $groupId)
  8268. ->column('uid');
  8269. } catch (\Throwable $e) {
  8270. return [];
  8271. }
  8272. $adminIds = is_array($adminIds)
  8273. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8274. : [];
  8275. if ($adminIds === []) {
  8276. return [];
  8277. }
  8278. try {
  8279. $rows = Db::name('admin')
  8280. ->where('status', 'normal')
  8281. ->where('id', 'in', $adminIds)
  8282. ->order('id', 'asc')
  8283. ->field('id,nickname,username,email,mobile')
  8284. ->select();
  8285. } catch (\Throwable $e) {
  8286. return [];
  8287. }
  8288. if (!is_array($rows)) {
  8289. return [];
  8290. }
  8291. foreach ($rows as $row) {
  8292. if (!is_array($row)) {
  8293. continue;
  8294. }
  8295. $name = trim((string)($row['nickname'] ?? ''));
  8296. if ($name === '') {
  8297. $name = trim((string)($row['username'] ?? ''));
  8298. }
  8299. if ($name === '' || isset($seen[$name])) {
  8300. continue;
  8301. }
  8302. $seen[$name] = true;
  8303. $out[] = [
  8304. 'name' => $name,
  8305. 'email' => trim((string)($row['email'] ?? '')),
  8306. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8307. ];
  8308. }
  8309. return $out;
  8310. }
  8311. /**
  8312. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8313. *
  8314. * @return string[]
  8315. */
  8316. protected function loadRfqDeptNameOptions(): array
  8317. {
  8318. $out = [];
  8319. // ERP 承揽部门(主来源)
  8320. try {
  8321. $vals = Db::table('mcyd')
  8322. ->where('CCLBMMC', '<>', '')
  8323. ->whereNotNull('CCLBMMC')
  8324. ->distinct(true)
  8325. ->limit(300)
  8326. ->column('CCLBMMC');
  8327. } catch (\Throwable $e) {
  8328. $vals = [];
  8329. }
  8330. if (is_array($vals)) {
  8331. foreach ($vals as $v) {
  8332. $v = trim((string)$v);
  8333. if ($v === '' || isset($out[$v])) {
  8334. continue;
  8335. }
  8336. $out[$v] = $v;
  8337. }
  8338. }
  8339. // 手工询价历史部门补全
  8340. try {
  8341. $poVals = Db::table('purchase_order')
  8342. ->where('CCLBMMC', '<>', '')
  8343. ->whereNotNull('CCLBMMC')
  8344. ->distinct(true)
  8345. ->limit(200)
  8346. ->column('CCLBMMC');
  8347. } catch (\Throwable $e) {
  8348. $poVals = [];
  8349. }
  8350. if (is_array($poVals)) {
  8351. foreach ($poVals as $v) {
  8352. $v = trim((string)$v);
  8353. if ($v === '' || isset($out[$v])) {
  8354. continue;
  8355. }
  8356. $out[$v] = $v;
  8357. }
  8358. }
  8359. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8360. if (!isset($out[$preset])) {
  8361. $out[$preset] = $preset;
  8362. }
  8363. }
  8364. $list = array_values($out);
  8365. // 常用部门靠前
  8366. usort($list, static function ($a, $b) {
  8367. $weight = [
  8368. '营销中心' => 1,
  8369. '业务部' => 2,
  8370. '市场部' => 3,
  8371. '外贸部' => 4,
  8372. '新华技术业务部' => 5,
  8373. ];
  8374. $wa = $weight[$a] ?? 100;
  8375. $wb = $weight[$b] ?? 100;
  8376. if ($wa !== $wb) {
  8377. return $wa <=> $wb;
  8378. }
  8379. return strcmp((string)$a, (string)$b);
  8380. });
  8381. return $list;
  8382. }
  8383. /**
  8384. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8385. */
  8386. public function add()
  8387. {
  8388. if ($this->request->isPost()) {
  8389. $params = $this->request->post('row/a');
  8390. if (!is_array($params)) {
  8391. $this->error(__('Parameter %s can not be empty', ''));
  8392. }
  8393. [, $adminName] = $this->GetUseName();
  8394. $params['cywyxm'] = $adminName;
  8395. try {
  8396. $sid = $this->saveManualPickOrder($params);
  8397. } catch (\InvalidArgumentException $e) {
  8398. $this->error($e->getMessage());
  8399. } catch (\Throwable $e) {
  8400. $this->error($e->getMessage());
  8401. }
  8402. $this->success('新增成功', '', [
  8403. 'scydgy_id' => $sid,
  8404. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8405. ]);
  8406. }
  8407. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8408. [, $adminName] = $this->GetUseName();
  8409. $this->view->assign('adminNickname', $adminName);
  8410. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8411. $this->view->assign('defaultCclbmmc', '营销中心');
  8412. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8413. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8414. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8415. return $this->view->fetch();
  8416. }
  8417. /**
  8418. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  8419. */
  8420. public function rfqlist()
  8421. {
  8422. $this->relationSearch = false;
  8423. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8424. $this->request->filter(['strip_tags', 'trim']);
  8425. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8426. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8427. $this->ensureRfqSalesmanEmailTemplate();
  8428. if ($this->request->isAjax()) {
  8429. try {
  8430. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8431. $limit = max(10, min(500, (int)$limit));
  8432. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8433. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8434. $filterYm = date('Y-m');
  8435. }
  8436. $applyFilters = function ($query) use ($where, $filterYm) {
  8437. $query->where('scydgy_id', '<', 0);
  8438. $this->applyPurchaseOrderNotDeletedWhere($query);
  8439. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  8440. $this->applyRfqListMonthFilter($query, $filterYm);
  8441. if (!empty($where)) {
  8442. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  8443. $safeWhere = [];
  8444. $skipFields = [
  8445. 'supplier_name' => true,
  8446. 'progress_text' => true,
  8447. 'createtime_text' => true,
  8448. 'notify_time_text' => true,
  8449. 'can_notify_salesman' => true,
  8450. 'has_issued' => true,
  8451. 'has_quoted' => true,
  8452. ];
  8453. foreach ((array)$where as $cond) {
  8454. if (!is_array($cond) || !isset($cond[0])) {
  8455. continue;
  8456. }
  8457. $field = (string)$cond[0];
  8458. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  8459. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  8460. if (isset($skipFields[$fieldBase])) {
  8461. continue;
  8462. }
  8463. if ($fieldBase === 'supplier_name') {
  8464. continue;
  8465. }
  8466. $safeWhere[] = $cond;
  8467. }
  8468. if ($safeWhere !== []) {
  8469. $query->where($safeWhere);
  8470. }
  8471. }
  8472. };
  8473. $countQuery = Db::table('purchase_order');
  8474. $applyFilters($countQuery);
  8475. $total = (int)$countQuery->count();
  8476. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8477. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8478. $listQuery = Db::table('purchase_order');
  8479. $applyFilters($listQuery);
  8480. $rows = $listQuery
  8481. ->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')
  8482. ->order($sortField, $orderDir)
  8483. ->limit($offset, $limit)
  8484. ->select();
  8485. if (!is_array($rows)) {
  8486. $rows = [];
  8487. }
  8488. $sidList = [];
  8489. foreach ($rows as $r) {
  8490. if (!is_array($r)) {
  8491. continue;
  8492. }
  8493. $sid = (int)($r['scydgy_id'] ?? 0);
  8494. if ($sid < 0) {
  8495. $sidList[$sid] = true;
  8496. }
  8497. }
  8498. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  8499. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  8500. $out = [];
  8501. foreach ($rows as $r) {
  8502. if (!is_array($r)) {
  8503. continue;
  8504. }
  8505. $sid = (int)($r['scydgy_id'] ?? 0);
  8506. if ($sid >= 0) {
  8507. continue;
  8508. }
  8509. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8510. if ($createdText === '') {
  8511. $createdText = trim((string)($r['dStamp'] ?? ''));
  8512. }
  8513. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  8514. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  8515. if ($supplier === '') {
  8516. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  8517. }
  8518. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  8519. || isset($issuedSidSet[$sid]);
  8520. $hasQuoted = isset($quotedSidSet[$sid]);
  8521. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  8522. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  8523. $out[] = [
  8524. 'id' => (int)($r['id'] ?? 0),
  8525. 'scydgy_id' => $sid,
  8526. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  8527. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  8528. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  8529. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  8530. 'CDW' => trim((string)($r['CDW'] ?? '')),
  8531. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  8532. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  8533. 'CDF' => trim((string)($r['CDF'] ?? '')),
  8534. 'supplier_name' => $supplier,
  8535. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  8536. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  8537. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  8538. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  8539. 'notify_time_text' => $notifyTimeText,
  8540. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  8541. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  8542. 'has_issued' => $hasIssued ? 1 : 0,
  8543. 'has_quoted' => $hasQuoted ? 1 : 0,
  8544. 'can_notify_salesman' => $canNotifySalesman,
  8545. 'createtime' => $r['createtime'] ?? null,
  8546. 'createtime_text' => $createdText,
  8547. ];
  8548. }
  8549. return json(['total' => $total, 'rows' => $out]);
  8550. } catch (\Throwable $e) {
  8551. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  8552. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  8553. }
  8554. }
  8555. $sidebar = $this->loadRfqSidebarYearMonths();
  8556. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  8557. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  8558. [, $adminName] = $this->GetUseName();
  8559. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  8560. $this->view->assign('adminNickname', $adminName);
  8561. $this->view->assign('defaultYm', $defaultYm);
  8562. $this->view->assign('sidebarYearMonths', $sidebar);
  8563. return $this->view->fetch('procuremen/rfqlist');
  8564. }
  8565. /**
  8566. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  8567. *
  8568. * @param array<int, array{year:string, months:array}> $sidebar
  8569. */
  8570. protected function resolveRfqListDefaultYm(array $sidebar): string
  8571. {
  8572. $current = date('Y-m');
  8573. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  8574. if (in_array($current, $yms, true)) {
  8575. return $current;
  8576. }
  8577. if ($yms !== []) {
  8578. rsort($yms, SORT_STRING);
  8579. return (string)$yms[0];
  8580. }
  8581. return $current;
  8582. }
  8583. /**
  8584. * 手工询价列表左侧月份(按 createtime / dStamp)
  8585. *
  8586. * @return array<int, array{year:string, months:array}>
  8587. */
  8588. protected function loadRfqSidebarYearMonths(): array
  8589. {
  8590. $ymSet = [];
  8591. try {
  8592. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  8593. $this->applyPurchaseOrderNotDeletedWhere($q);
  8594. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  8595. } catch (\Throwable $e) {
  8596. $rows = [];
  8597. }
  8598. if (!is_array($rows)) {
  8599. $rows = [];
  8600. }
  8601. foreach ($rows as $r) {
  8602. if (!is_array($r)) {
  8603. continue;
  8604. }
  8605. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8606. if ($t === '') {
  8607. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  8608. }
  8609. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  8610. $ymSet[$m[1] . '-' . $m[2]] = true;
  8611. }
  8612. }
  8613. return $this->buildYearMonthSidebar(array_keys($ymSet));
  8614. }
  8615. /**
  8616. * 手工询价可见范围(用于详情/操作校验):
  8617. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  8618. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  8619. */
  8620. protected function applyManualRfqViewerWhere($query): void
  8621. {
  8622. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  8623. return;
  8624. }
  8625. [, $adminName] = $this->GetUseName();
  8626. $adminName = trim((string)$adminName);
  8627. if ($adminName === '') {
  8628. $query->whereRaw('1 = 0');
  8629. return;
  8630. }
  8631. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  8632. $query->where(function ($q) use ($adminName) {
  8633. $q->where('cywyxm', $adminName)
  8634. ->whereOr('notify_salesman', $adminName)
  8635. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  8636. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  8637. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  8638. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  8639. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  8640. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  8641. });
  8642. }
  8643. /**
  8644. * 当前用户是否可查看/操作该手工询价单
  8645. */
  8646. protected function canViewManualRfqOrder(array $po): bool
  8647. {
  8648. if ($this->auth->isSuperAdmin()) {
  8649. return true;
  8650. }
  8651. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  8652. if ($this->hasProcuremenPerm(['rfqlist'])) {
  8653. return true;
  8654. }
  8655. [, $adminName] = $this->GetUseName();
  8656. $adminName = trim((string)$adminName);
  8657. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  8658. return true;
  8659. }
  8660. if ($adminName !== '') {
  8661. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8662. if ($n === $adminName) {
  8663. return true;
  8664. }
  8665. }
  8666. }
  8667. return false;
  8668. }
  8669. /**
  8670. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  8671. */
  8672. protected function applyRfqListMonthFilter($query, string $ym): void
  8673. {
  8674. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8675. $ym = date('Y-m');
  8676. }
  8677. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  8678. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  8679. $query->whereRaw(
  8680. "("
  8681. . "CASE "
  8682. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  8683. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  8684. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  8685. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  8686. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  8687. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  8688. . "END"
  8689. . ") LIKE '{$ymEsc}-%'"
  8690. );
  8691. }
  8692. /**
  8693. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  8694. */
  8695. public function rfqlistDetails()
  8696. {
  8697. return $this->details();
  8698. }
  8699. /**
  8700. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  8701. */
  8702. public function rfqnotifysalesmen()
  8703. {
  8704. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen'])) {
  8705. $this->error(__('You have no permission'));
  8706. }
  8707. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8708. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8709. $sid = (int)$this->request->param('scydgy_id', 0);
  8710. if ($sid >= 0) {
  8711. $this->error('仅支持手工新增询价单');
  8712. }
  8713. $po = $this->loadManualRfqOrderForNotify($sid);
  8714. $selectedMap = [];
  8715. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8716. $selectedMap[$n] = true;
  8717. }
  8718. $list = [];
  8719. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8720. $name = trim((string)($row['name'] ?? ''));
  8721. if ($name === '') {
  8722. continue;
  8723. }
  8724. $email = trim((string)($row['email'] ?? ''));
  8725. $mobile = trim((string)($row['mobile'] ?? ''));
  8726. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8727. $list[] = [
  8728. 'name' => $name,
  8729. 'email' => $email,
  8730. 'mobile' => $mobile,
  8731. 'can_select' => $hasEmail ? 1 : 0,
  8732. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  8733. ];
  8734. }
  8735. $canNotify = $this->canRfqNotifySalesman($po);
  8736. $this->success('', null, [
  8737. 'scydgy_id' => $sid,
  8738. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  8739. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  8740. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  8741. 'can_notify_salesman' => $canNotify ? 1 : 0,
  8742. 'list' => $list,
  8743. ]);
  8744. }
  8745. /**
  8746. * 查询询价 — 补加通知业务员可选名单
  8747. */
  8748. public function rfqsalesmanoptions()
  8749. {
  8750. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  8751. $this->error(__('You have no permission'));
  8752. }
  8753. $out = [];
  8754. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8755. $email = trim((string)($row['email'] ?? ''));
  8756. $mobile = trim((string)($row['mobile'] ?? ''));
  8757. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8758. $out[] = [
  8759. 'name' => (string)($row['name'] ?? ''),
  8760. 'email' => $email,
  8761. 'mobile' => $mobile,
  8762. 'can_select' => $hasEmail ? 1 : 0,
  8763. ];
  8764. }
  8765. $this->success('', null, ['list' => $out]);
  8766. }
  8767. /**
  8768. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  8769. */
  8770. public function rfqappendsalesmen()
  8771. {
  8772. if (!$this->request->isPost()) {
  8773. $this->error(__('Invalid parameters'));
  8774. }
  8775. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqappendsalesmen'])) {
  8776. $this->error(__('You have no permission'));
  8777. }
  8778. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8779. $sid = (int)$this->request->post('scydgy_id', 0);
  8780. if ($sid >= 0) {
  8781. $this->error('仅支持手工新增询价单');
  8782. }
  8783. $po = $this->loadManualRfqOrderForNotify($sid);
  8784. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  8785. $this->error('订单已完结,无法添加业务员');
  8786. }
  8787. $raw = $this->request->post('salesmen/a', []);
  8788. if (!is_array($raw) || $raw === []) {
  8789. $salesmenJson = $this->request->post('salesmen_json', '');
  8790. if (is_string($salesmenJson) && $salesmenJson !== '') {
  8791. $decoded = json_decode($salesmenJson, true);
  8792. $raw = is_array($decoded) ? $decoded : [];
  8793. }
  8794. }
  8795. $addNames = [];
  8796. foreach ((array)$raw as $item) {
  8797. if (is_array($item)) {
  8798. $n = trim((string)($item['name'] ?? ''));
  8799. } else {
  8800. $n = trim((string)$item);
  8801. }
  8802. if ($n !== '') {
  8803. $addNames[] = $n;
  8804. }
  8805. }
  8806. $addNames = array_values(array_unique($addNames));
  8807. if ($addNames === []) {
  8808. $this->error('请选择要添加的业务员');
  8809. }
  8810. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  8811. $allowedMap = [];
  8812. foreach ($allowedOptions as $opt) {
  8813. $n = trim((string)($opt['name'] ?? ''));
  8814. if ($n === '') {
  8815. continue;
  8816. }
  8817. $email = trim((string)($opt['email'] ?? ''));
  8818. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  8819. }
  8820. foreach ($addNames as $n) {
  8821. if (!array_key_exists($n, $allowedMap)) {
  8822. $this->error('业务员不在可选名单中:' . $n);
  8823. }
  8824. if (!$allowedMap[$n]) {
  8825. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  8826. }
  8827. }
  8828. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  8829. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  8830. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  8831. try {
  8832. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  8833. } catch (\Throwable $e) {
  8834. $this->error('保存失败:' . $e->getMessage());
  8835. }
  8836. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8837. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  8838. $this->success('已添加业务员', null, [
  8839. 'scydgy_id' => $sid,
  8840. 'notify_salesman' => $mergedStr,
  8841. 'added_count' => count($addNames),
  8842. ]);
  8843. }
  8844. /**
  8845. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  8846. */
  8847. public function rfqnotifysalesman()
  8848. {
  8849. if (!$this->request->isPost()) {
  8850. $this->error(__('Invalid parameters'));
  8851. }
  8852. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesman'])) {
  8853. $this->error(__('You have no permission'));
  8854. }
  8855. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8856. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8857. $sid = (int)$this->request->post('scydgy_id', 0);
  8858. if ($sid >= 0) {
  8859. $this->error('仅支持手工新增询价单');
  8860. }
  8861. $po = $this->loadManualRfqOrderForNotify($sid);
  8862. $this->assertRfqCanNotifySalesman($po);
  8863. $raw = $this->request->post('salesmen/a', []);
  8864. if (!is_array($raw) || $raw === []) {
  8865. $salesmenJson = $this->request->post('salesmen_json', '');
  8866. if (is_string($salesmenJson) && $salesmenJson !== '') {
  8867. $decoded = json_decode($salesmenJson, true);
  8868. $raw = is_array($decoded) ? $decoded : [];
  8869. }
  8870. }
  8871. // 兼容旧参数:notify_all / 单人 name
  8872. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  8873. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  8874. }
  8875. if ((!is_array($raw) || $raw === [])) {
  8876. $oneName = trim((string)$this->request->post('name', ''));
  8877. if ($oneName !== '') {
  8878. $raw = [$oneName];
  8879. }
  8880. }
  8881. $selectedNames = [];
  8882. foreach ((array)$raw as $item) {
  8883. if (is_array($item)) {
  8884. $n = trim((string)($item['name'] ?? ''));
  8885. } else {
  8886. $n = trim((string)$item);
  8887. }
  8888. if ($n !== '') {
  8889. $selectedNames[] = $n;
  8890. }
  8891. }
  8892. $selectedNames = array_values(array_unique($selectedNames));
  8893. if ($selectedNames === []) {
  8894. $this->error('请选择要通知的业务员');
  8895. }
  8896. $optionMap = [];
  8897. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  8898. $n = trim((string)($opt['name'] ?? ''));
  8899. if ($n === '') {
  8900. continue;
  8901. }
  8902. $optionMap[$n] = $opt;
  8903. }
  8904. $targets = [];
  8905. foreach ($selectedNames as $n) {
  8906. if (!isset($optionMap[$n])) {
  8907. $this->error('业务员不在可选名单中:' . $n);
  8908. }
  8909. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  8910. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  8911. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  8912. }
  8913. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  8914. $targets[] = $resolved[0] ?? [
  8915. 'admin_id' => 0,
  8916. 'name' => $n,
  8917. 'email' => $email,
  8918. ];
  8919. }
  8920. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  8921. try {
  8922. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8923. 'notify_salesman' => $mergedStr,
  8924. ]);
  8925. } catch (\Throwable $e) {
  8926. $this->error('保存通知业务员失败:' . $e->getMessage());
  8927. }
  8928. $po['notify_salesman'] = $mergedStr;
  8929. $mailConfig = $this->loadMailerConfig();
  8930. if (empty($mailConfig['host'])) {
  8931. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  8932. }
  8933. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  8934. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  8935. }
  8936. $this->ensureRfqSalesmanEmailTemplate();
  8937. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  8938. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  8939. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  8940. $qty = trim((string)($po['This_quantity'] ?? ''));
  8941. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  8942. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  8943. if ($supplier === '') {
  8944. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  8945. }
  8946. try {
  8947. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  8948. } catch (\Throwable $e) {
  8949. $this->error($e->getMessage());
  8950. }
  8951. $okNames = [];
  8952. $failMsgs = [];
  8953. foreach ($targets as $contact) {
  8954. $toEmail = trim((string)($contact['email'] ?? ''));
  8955. $toName = trim((string)($contact['name'] ?? ''));
  8956. $notifyVars = [
  8957. 'contact_name' => $toName,
  8958. 'salesman_name' => $toName,
  8959. 'company_name' => $toName,
  8960. 'email' => $toEmail,
  8961. 'ccydh' => $ccydh,
  8962. 'cyjmc' => $cyjmc,
  8963. 'cgymc' => $cgymc,
  8964. 'this_quantity' => $qty,
  8965. 'supplier_name' => $supplier,
  8966. 'cywyxm' => $cywyxm,
  8967. ];
  8968. try {
  8969. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  8970. $mailSubject = $mailSubjectTpl;
  8971. foreach ($notifyVars as $k => $v) {
  8972. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  8973. }
  8974. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  8975. $mailSubject = trim((string)$mailSubject);
  8976. if ($mailSubject === '') {
  8977. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  8978. }
  8979. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  8980. $bundle = [
  8981. 'company_name' => $toName,
  8982. 'email' => $toEmail,
  8983. 'mail_plain' => $mailPlain,
  8984. 'mail_body' => $mailBody,
  8985. 'ccydh' => $ccydh,
  8986. 'email_log_scene' => 'rfq_salesman',
  8987. 'email_log_scydgy_id' => $sid,
  8988. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  8989. 'notify_vars' => $notifyVars,
  8990. ];
  8991. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  8992. $okNames[] = $toName . '(' . $toEmail . ')';
  8993. } catch (\Throwable $e) {
  8994. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  8995. }
  8996. }
  8997. if ($okNames === []) {
  8998. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  8999. }
  9000. $now = date('Y-m-d H:i:s');
  9001. try {
  9002. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9003. 'rfq_salesman_notified' => 1,
  9004. 'rfq_salesman_notify_time' => $now,
  9005. ]);
  9006. } catch (\Throwable $e) {
  9007. // ignore
  9008. }
  9009. $this->addOrderLog(
  9010. $sid,
  9011. 'rfq_notify_salesman',
  9012. '邮箱通知业务员:' . implode('、', $okNames),
  9013. (int)($po['id'] ?? 0)
  9014. );
  9015. $msg = '已通知 ' . count($okNames) . ' 人';
  9016. if ($failMsgs !== []) {
  9017. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9018. }
  9019. $this->success($msg, null, [
  9020. 'scydgy_id' => $sid,
  9021. 'notify_salesman' => $mergedStr,
  9022. 'rfq_salesman_notified' => 1,
  9023. 'rfq_salesman_notify_time' => $now,
  9024. 'notify_time_text' => $now,
  9025. 'ok_count' => count($okNames),
  9026. 'fail_count' => count($failMsgs),
  9027. ]);
  9028. }
  9029. /**
  9030. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9031. */
  9032. public function rfqissuesuppliers()
  9033. {
  9034. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesuppliers'])) {
  9035. $this->error(__('You have no permission'));
  9036. }
  9037. $sid = (int)$this->request->param('scydgy_id', 0);
  9038. if ($sid >= 0) {
  9039. $this->error('仅支持手工新增询价单');
  9040. }
  9041. $po = $this->loadManualRfqOrderForNotify($sid);
  9042. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9043. if ($supplierRaw === '') {
  9044. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9045. }
  9046. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9047. $list = [];
  9048. foreach ($names as $name) {
  9049. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9050. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9051. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9052. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9053. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9054. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9055. $list[] = [
  9056. 'name' => $name,
  9057. 'username' => $username,
  9058. 'email' => $email,
  9059. 'phone' => $phone,
  9060. 'can_notify' => $okEmail ? 1 : 0,
  9061. 'found' => is_array($contact) ? 1 : 0,
  9062. ];
  9063. }
  9064. $this->success('', null, [
  9065. 'scydgy_id' => $sid,
  9066. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9067. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9068. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9069. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9070. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9071. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9072. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9073. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9074. 'list' => $list,
  9075. ]);
  9076. }
  9077. /**
  9078. * 查询询价 — 补加供应商可选名单
  9079. */
  9080. public function rfqsupplieroptions()
  9081. {
  9082. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9083. $this->error(__('You have no permission'));
  9084. }
  9085. $names = array_values($this->loadRfqSupplierNameOptions());
  9086. $out = [];
  9087. foreach ($names as $name) {
  9088. $out[] = ['name' => $name];
  9089. }
  9090. $this->success('', null, ['list' => $out]);
  9091. }
  9092. /**
  9093. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9094. */
  9095. public function rfqappendsuppliers()
  9096. {
  9097. if (!$this->request->isPost()) {
  9098. $this->error(__('Invalid parameters'));
  9099. }
  9100. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers'])) {
  9101. $this->error(__('You have no permission'));
  9102. }
  9103. $sid = (int)$this->request->post('scydgy_id', 0);
  9104. if ($sid >= 0) {
  9105. $this->error('仅支持手工新增询价单');
  9106. }
  9107. $po = $this->loadManualRfqOrderForNotify($sid);
  9108. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9109. $this->error('订单已完结,无法补加供应商');
  9110. }
  9111. $raw = $this->request->post('suppliers/a', []);
  9112. if (!is_array($raw) || $raw === []) {
  9113. $suppliersJson = $this->request->post('suppliers_json', '');
  9114. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9115. $decoded = json_decode($suppliersJson, true);
  9116. $raw = is_array($decoded) ? $decoded : [];
  9117. }
  9118. }
  9119. $addNames = [];
  9120. foreach ((array)$raw as $item) {
  9121. if (is_array($item)) {
  9122. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9123. } else {
  9124. $n = trim((string)$item);
  9125. }
  9126. if ($n !== '') {
  9127. $addNames[] = $n;
  9128. }
  9129. }
  9130. $addNames = array_values(array_unique($addNames));
  9131. if ($addNames === []) {
  9132. $this->error('请选择要补加的供应商');
  9133. }
  9134. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9135. if ($existingRaw === '') {
  9136. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9137. }
  9138. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9139. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9140. try {
  9141. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9142. } catch (\Throwable $e) {
  9143. $this->error('保存失败:' . $e->getMessage());
  9144. }
  9145. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9146. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9147. $this->success('已补加供应商', null, [
  9148. 'scydgy_id' => $sid,
  9149. 'cGzzxMc' => $mergedStr,
  9150. 'added_count' => count($addNames),
  9151. ]);
  9152. }
  9153. /**
  9154. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9155. */
  9156. public function rfqissue()
  9157. {
  9158. if (!$this->request->isPost()) {
  9159. $this->error(__('Invalid parameters'));
  9160. }
  9161. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue'])) {
  9162. $this->error(__('You have no permission'));
  9163. }
  9164. $sid = (int)$this->request->post('scydgy_id', 0);
  9165. if ($sid >= 0) {
  9166. $this->error('仅支持手工新增询价单');
  9167. }
  9168. $po = $this->loadManualRfqOrderForNotify($sid);
  9169. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9170. $this->error('订单已完结,无法下发');
  9171. }
  9172. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9173. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9174. $this->error('订单已进入后续流程,无法再下发');
  9175. }
  9176. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9177. if ($supplierRaw === '') {
  9178. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9179. }
  9180. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9181. if ($supplierNames === []) {
  9182. $this->error('请先在新增询价时选择供应商');
  9183. }
  9184. $companies = [];
  9185. $missing = [];
  9186. $noEmail = [];
  9187. foreach ($supplierNames as $name) {
  9188. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9189. if ($contact === null) {
  9190. $missing[] = $name;
  9191. continue;
  9192. }
  9193. $em = trim((string)($contact['email'] ?? ''));
  9194. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9195. $noEmail[] = $name;
  9196. continue;
  9197. }
  9198. $companies[] = $contact;
  9199. }
  9200. if ($missing !== []) {
  9201. $this->error('未找到供应商档案:' . implode('、', $missing));
  9202. }
  9203. if ($noEmail !== []) {
  9204. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9205. }
  9206. if ($companies === []) {
  9207. $this->error('没有可通知的供应商');
  9208. }
  9209. $mailConfig = $this->loadMailerConfig();
  9210. if (empty($mailConfig['host'])) {
  9211. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9212. }
  9213. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9214. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9215. }
  9216. $mergeRow = $po;
  9217. $mergeRow['ID'] = $sid;
  9218. $mergeRow['id'] = $sid;
  9219. $mergeRows = [$mergeRow];
  9220. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9221. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9222. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9223. }
  9224. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9225. $issueTime = date('Y-m-d H:i:s');
  9226. $nameLabels = [];
  9227. foreach ($companies as $c) {
  9228. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9229. }
  9230. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9231. Db::startTrans();
  9232. try {
  9233. $this->upsertPurchaseOrderFromRow(
  9234. $mergeRow,
  9235. $sysRqDb,
  9236. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9237. $issueTime,
  9238. $po,
  9239. null,
  9240. $scoreRule
  9241. );
  9242. foreach ($companies as $c) {
  9243. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9244. }
  9245. Db::commit();
  9246. } catch (\Throwable $e) {
  9247. Db::rollback();
  9248. $this->error($e->getMessage());
  9249. }
  9250. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9251. if ($poId <= 0) {
  9252. try {
  9253. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9254. } catch (\Throwable $e) {
  9255. $poId = 0;
  9256. }
  9257. }
  9258. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9259. $posNotify = [];
  9260. try {
  9261. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9262. if (is_array($fresh)) {
  9263. $fresh['sys_rq'] = $sysRqDb;
  9264. $posNotify = [$fresh];
  9265. }
  9266. } catch (\Throwable $e) {
  9267. $posNotify = [$po];
  9268. $posNotify[0]['sys_rq'] = $sysRqDb;
  9269. }
  9270. $notifyBundle = [
  9271. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9272. 'pos' => $posNotify,
  9273. 'merge_rows' => $mergeRows,
  9274. ];
  9275. $notifyErrors = [];
  9276. foreach ($companies as $c) {
  9277. $cname = trim((string)($c['name'] ?? ''));
  9278. try {
  9279. // 询价下发:仅邮箱通知供应商
  9280. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'pick_issue');
  9281. } catch (\Throwable $e) {
  9282. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9283. }
  9284. }
  9285. if ($notifyErrors !== []) {
  9286. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9287. }
  9288. $this->success('已询价并邮件通知供应商', null, [
  9289. 'scydgy_id' => $sid,
  9290. 'progress_text' => '待报价',
  9291. 'supplier_count' => count($companies),
  9292. ]);
  9293. }
  9294. /**
  9295. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9296. */
  9297. public function rfqissuesendmail()
  9298. {
  9299. if (!$this->request->isPost()) {
  9300. $this->error(__('Invalid parameters'));
  9301. }
  9302. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesendmail'])) {
  9303. $this->error(__('You have no permission'));
  9304. }
  9305. $sid = (int)$this->request->post('scydgy_id', 0);
  9306. $companyName = trim((string)$this->request->post('company_name', ''));
  9307. if ($sid >= 0) {
  9308. $this->error('仅支持手工新增询价单');
  9309. }
  9310. if ($companyName === '') {
  9311. $this->error('请选择供应商');
  9312. }
  9313. $po = $this->loadManualRfqOrderForNotify($sid);
  9314. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9315. $this->error('订单已完结,无法发送');
  9316. }
  9317. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9318. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9319. $this->error('订单已进入后续流程,无法再发送');
  9320. }
  9321. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9322. if ($contact === null) {
  9323. $this->error('未找到供应商档案:' . $companyName);
  9324. }
  9325. $email = trim((string)($contact['email'] ?? ''));
  9326. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9327. $this->error('该供应商未填写有效邮箱');
  9328. }
  9329. $mailConfig = $this->loadMailerConfig();
  9330. if (empty($mailConfig['host'])) {
  9331. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9332. }
  9333. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9334. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9335. }
  9336. $mergeRow = $po;
  9337. $mergeRow['ID'] = $sid;
  9338. $mergeRow['id'] = $sid;
  9339. $mergeRows = [$mergeRow];
  9340. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9341. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9342. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9343. }
  9344. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9345. $issueTime = date('Y-m-d H:i:s');
  9346. Db::startTrans();
  9347. try {
  9348. $this->upsertPurchaseOrderFromRow(
  9349. $mergeRow,
  9350. $sysRqDb,
  9351. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9352. $issueTime,
  9353. $po,
  9354. null,
  9355. $scoreRule
  9356. );
  9357. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9358. Db::commit();
  9359. } catch (\Throwable $e) {
  9360. Db::rollback();
  9361. $this->error($e->getMessage());
  9362. }
  9363. $posNotify = [];
  9364. try {
  9365. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9366. if (is_array($fresh)) {
  9367. $fresh['sys_rq'] = $sysRqDb;
  9368. $posNotify = [$fresh];
  9369. }
  9370. } catch (\Throwable $e) {
  9371. $posNotify = [$po];
  9372. $posNotify[0]['sys_rq'] = $sysRqDb;
  9373. }
  9374. $notifyBundle = [
  9375. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9376. 'pos' => $posNotify,
  9377. 'merge_rows' => $mergeRows,
  9378. ];
  9379. try {
  9380. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'pick_issue');
  9381. } catch (\Throwable $e) {
  9382. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  9383. }
  9384. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9385. if ($poId <= 0) {
  9386. try {
  9387. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9388. } catch (\Throwable $e) {
  9389. $poId = 0;
  9390. }
  9391. }
  9392. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  9393. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  9394. 'scydgy_id' => $sid,
  9395. 'company_name' => $companyName,
  9396. ]);
  9397. }
  9398. /**
  9399. * 查询询价 — 查看各供应商报价(单价)
  9400. */
  9401. public function rfqquotes()
  9402. {
  9403. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqquotes', 'rfqissue'])) {
  9404. $this->error(__('You have no permission'));
  9405. }
  9406. $sid = (int)$this->request->param('scydgy_id', 0);
  9407. if ($sid >= 0) {
  9408. $this->error('仅支持手工新增询价单');
  9409. }
  9410. $po = $this->loadManualRfqOrderForNotify($sid);
  9411. $rows = [];
  9412. try {
  9413. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  9414. $q = Db::table('purchase_order_detail')
  9415. ->where('scydgy_id', $sid)
  9416. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  9417. ->order('id', 'asc');
  9418. $this->applyActivePurchaseOrderDetailWhere($q);
  9419. $rows = $q->select();
  9420. } catch (\Throwable $e) {
  9421. try {
  9422. $q = Db::table('purchase_order_detail')
  9423. ->where('scydgy_id', $sid)
  9424. ->order('id', 'asc');
  9425. $this->applyActivePurchaseOrderDetailWhere($q);
  9426. $rows = $q->select();
  9427. } catch (\Throwable $e2) {
  9428. $rows = [];
  9429. }
  9430. }
  9431. if (!is_array($rows)) {
  9432. $rows = [];
  9433. }
  9434. $list = [];
  9435. foreach ($rows as $row) {
  9436. if (!is_array($row)) {
  9437. continue;
  9438. }
  9439. $amount = trim((string)($row['amount'] ?? ''));
  9440. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  9441. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  9442. $oper = '';
  9443. if ($isQuoted) {
  9444. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  9445. if ($oper === '') {
  9446. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  9447. }
  9448. }
  9449. $list[] = [
  9450. 'id' => (int)($row['id'] ?? 0),
  9451. 'company_name' => trim((string)($row['company_name'] ?? '')),
  9452. 'amount' => $amount,
  9453. 'amount_text' => $isQuoted ? $amount : '',
  9454. 'is_quoted' => $isQuoted,
  9455. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  9456. 'status_name' => trim((string)($row['status_name'] ?? '')),
  9457. 'oper_time' => $oper,
  9458. ];
  9459. }
  9460. $this->success('', null, [
  9461. 'scydgy_id' => $sid,
  9462. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9463. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9464. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9465. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9466. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9467. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9468. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9469. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9470. 'list' => $list,
  9471. ]);
  9472. }
  9473. /**
  9474. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  9475. */
  9476. protected function isRfqOrderIssued(array $po): bool
  9477. {
  9478. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  9479. return true;
  9480. }
  9481. $sid = (int)($po['scydgy_id'] ?? 0);
  9482. if ($sid >= 0) {
  9483. return false;
  9484. }
  9485. try {
  9486. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9487. $this->applyActivePurchaseOrderDetailWhere($q);
  9488. return (int)$q->count() > 0;
  9489. } catch (\Throwable $e) {
  9490. return false;
  9491. }
  9492. }
  9493. /**
  9494. * 批量:已有下发明细的手工询价 scydgy_id
  9495. *
  9496. * @param int[] $scydgyIds
  9497. * @return array<int, bool>
  9498. */
  9499. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  9500. {
  9501. $set = [];
  9502. $ids = [];
  9503. foreach ($scydgyIds as $sid) {
  9504. $sid = (int)$sid;
  9505. if ($sid < 0) {
  9506. $ids[$sid] = true;
  9507. }
  9508. }
  9509. if ($ids === []) {
  9510. return $set;
  9511. }
  9512. try {
  9513. $q = Db::table('purchase_order_detail')
  9514. ->where('scydgy_id', 'in', array_keys($ids))
  9515. ->field('scydgy_id');
  9516. $this->applyActivePurchaseOrderDetailWhere($q);
  9517. $rows = $q->select();
  9518. } catch (\Throwable $e) {
  9519. return $set;
  9520. }
  9521. if (!is_array($rows)) {
  9522. return $set;
  9523. }
  9524. foreach ($rows as $row) {
  9525. if (!is_array($row)) {
  9526. continue;
  9527. }
  9528. $sid = (int)($row['scydgy_id'] ?? 0);
  9529. if ($sid < 0) {
  9530. $set[$sid] = true;
  9531. }
  9532. }
  9533. return $set;
  9534. }
  9535. /**
  9536. * 批量:已填单价(已报价)的手工询价 scydgy_id
  9537. *
  9538. * @param int[] $scydgyIds
  9539. * @return array<int, bool>
  9540. */
  9541. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  9542. {
  9543. $set = [];
  9544. $ids = [];
  9545. foreach ($scydgyIds as $sid) {
  9546. $sid = (int)$sid;
  9547. if ($sid < 0) {
  9548. $ids[$sid] = true;
  9549. }
  9550. }
  9551. if ($ids === []) {
  9552. return $set;
  9553. }
  9554. try {
  9555. $q = Db::table('purchase_order_detail')
  9556. ->where('scydgy_id', 'in', array_keys($ids))
  9557. ->field('scydgy_id,amount');
  9558. $this->applyActivePurchaseOrderDetailWhere($q);
  9559. $rows = $q->select();
  9560. } catch (\Throwable $e) {
  9561. return $set;
  9562. }
  9563. if (!is_array($rows)) {
  9564. return $set;
  9565. }
  9566. foreach ($rows as $row) {
  9567. if (!is_array($row)) {
  9568. continue;
  9569. }
  9570. $amount = trim((string)($row['amount'] ?? ''));
  9571. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  9572. continue;
  9573. }
  9574. $sid = (int)($row['scydgy_id'] ?? 0);
  9575. if ($sid < 0) {
  9576. $set[$sid] = true;
  9577. }
  9578. }
  9579. return $set;
  9580. }
  9581. /**
  9582. * 已下发且至少一家供应商已报价,才允许通知业务员
  9583. */
  9584. protected function canRfqNotifySalesman(array $po): bool
  9585. {
  9586. if (!$this->isRfqOrderIssued($po)) {
  9587. return false;
  9588. }
  9589. $sid = (int)($po['scydgy_id'] ?? 0);
  9590. if ($sid >= 0) {
  9591. return false;
  9592. }
  9593. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  9594. return isset($quoted[$sid]);
  9595. }
  9596. protected function assertRfqCanNotifySalesman(array $po): void
  9597. {
  9598. if (!$this->isRfqOrderIssued($po)) {
  9599. $this->error('请先询价并等待供应商报价后再通知业务员');
  9600. }
  9601. if (!$this->canRfqNotifySalesman($po)) {
  9602. $this->error('供应商尚未报价,暂不能通知业务员');
  9603. }
  9604. }
  9605. /**
  9606. * 加载手工询价单(含可见性校验)
  9607. *
  9608. * @return array<string, mixed>
  9609. */
  9610. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  9611. {
  9612. try {
  9613. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9614. } catch (\Throwable $e) {
  9615. $po = null;
  9616. }
  9617. if (!is_array($po)) {
  9618. $this->error('订单不存在');
  9619. }
  9620. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9621. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9622. $this->error('订单不存在');
  9623. }
  9624. if ($this->auth->isSuperAdmin()) {
  9625. return $po;
  9626. }
  9627. if ($this->canViewManualRfqOrder($po)) {
  9628. return $po;
  9629. }
  9630. $this->error('无权操作该订单');
  9631. }
  9632. /**
  9633. * @return string[]
  9634. */
  9635. protected function splitRfqSalesmanNames(string $raw): array
  9636. {
  9637. $parts = [];
  9638. $raw = trim($raw);
  9639. if ($raw === '') {
  9640. return [];
  9641. }
  9642. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  9643. $v = trim((string)$piece);
  9644. if ($v !== '' && !in_array($v, $parts, true)) {
  9645. $parts[] = $v;
  9646. }
  9647. }
  9648. return $parts;
  9649. }
  9650. /**
  9651. * 按姓名匹配 fa_admin 邮箱
  9652. *
  9653. * @param string[] $names
  9654. * @return array<int, array{admin_id:int,name:string,email:string}>
  9655. */
  9656. protected function resolveRfqSalesmanContactRows(array $names): array
  9657. {
  9658. $out = [];
  9659. foreach ($names as $name) {
  9660. $name = trim((string)$name);
  9661. if ($name === '') {
  9662. continue;
  9663. }
  9664. $adminId = 0;
  9665. $email = '';
  9666. try {
  9667. $row = Db::name('admin')
  9668. ->where(function ($q) use ($name) {
  9669. $q->where('nickname', $name)->whereOr('username', $name);
  9670. })
  9671. ->where('status', 'normal')
  9672. ->order('id', 'asc')
  9673. ->field('id,nickname,username,email')
  9674. ->find();
  9675. } catch (\Throwable $e) {
  9676. $row = null;
  9677. }
  9678. if (is_array($row)) {
  9679. $adminId = (int)($row['id'] ?? 0);
  9680. $email = trim((string)($row['email'] ?? ''));
  9681. $disp = trim((string)($row['nickname'] ?? ''));
  9682. if ($disp === '') {
  9683. $disp = trim((string)($row['username'] ?? ''));
  9684. }
  9685. if ($disp !== '') {
  9686. $name = $disp;
  9687. }
  9688. }
  9689. $out[] = [
  9690. 'admin_id' => $adminId,
  9691. 'name' => $name,
  9692. 'email' => $email,
  9693. ];
  9694. }
  9695. return $out;
  9696. }
  9697. /**
  9698. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  9699. */
  9700. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  9701. {
  9702. if ($scydgyId >= 0) {
  9703. return;
  9704. }
  9705. try {
  9706. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9707. } catch (\Throwable $e) {
  9708. $po = null;
  9709. }
  9710. if (!is_array($po)) {
  9711. $this->error('订单不存在');
  9712. }
  9713. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9714. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9715. $this->error('订单不存在');
  9716. }
  9717. if ($this->auth->isSuperAdmin()) {
  9718. return;
  9719. }
  9720. [, $adminName] = $this->GetUseName();
  9721. $cywy = trim((string)($po['cywyxm'] ?? ''));
  9722. if ($cywy !== '' && $cywy === $adminName) {
  9723. return;
  9724. }
  9725. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  9726. try {
  9727. if ($this->auth->check($rule)) {
  9728. return;
  9729. }
  9730. } catch (\Throwable $e) {
  9731. }
  9732. }
  9733. $this->error('无权查看该订单');
  9734. }
  9735. /**
  9736. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  9737. */
  9738. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  9739. {
  9740. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  9741. return ProcuremenStatus::PO_COMPLETED;
  9742. }
  9743. $sid = (int)($row['scydgy_id'] ?? 0);
  9744. if ($sid < 0) {
  9745. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  9746. return '已通知业务员';
  9747. }
  9748. if ($hasQuoted) {
  9749. return '供应商已报价';
  9750. }
  9751. if ($hasIssued
  9752. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  9753. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  9754. return '待报价';
  9755. }
  9756. try {
  9757. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9758. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  9759. if ((int)$detCntQuery->count() > 0) {
  9760. return '待报价';
  9761. }
  9762. } catch (\Throwable $e) {
  9763. }
  9764. return '待询价';
  9765. }
  9766. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  9767. return '待入库评分';
  9768. }
  9769. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  9770. return '待采购确认';
  9771. }
  9772. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  9773. return '待确认供应商';
  9774. }
  9775. return '待协助下发';
  9776. }
  9777. /**
  9778. * 协助初选列表 — 批量软删除
  9779. */
  9780. public function pickDelete()
  9781. {
  9782. if (!$this->request->isPost() || !$this->request->isAjax()) {
  9783. $this->error(__('Invalid parameters'));
  9784. }
  9785. if (!$this->procuremenCanPickDelete()) {
  9786. $this->error(__('You have no permission'));
  9787. }
  9788. $rowsRaw = $this->request->post('rows_json', '[]');
  9789. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  9790. if (!is_array($rows) || $rows === []) {
  9791. $this->error('请至少勾选一条工序');
  9792. }
  9793. $done = 0;
  9794. Db::startTrans();
  9795. try {
  9796. foreach ($rows as $row) {
  9797. if (!is_array($row)) {
  9798. continue;
  9799. }
  9800. $this->softDeleteProcuremenPickRow($row);
  9801. $done++;
  9802. }
  9803. if ($done < 1) {
  9804. throw new \Exception('没有可删除的工序');
  9805. }
  9806. Db::commit();
  9807. } catch (\InvalidArgumentException $e) {
  9808. Db::rollback();
  9809. $this->error($e->getMessage());
  9810. } catch (\Throwable $e) {
  9811. Db::rollback();
  9812. $this->error($e->getMessage());
  9813. }
  9814. $this->pickHiddenScydgySetCache = null;
  9815. $this->success('已删除 ' . $done . ' 条工序');
  9816. }
  9817. /**
  9818. * 下发 — 手工新增工序(弹窗)
  9819. */
  9820. public function pickAdd()
  9821. {
  9822. if ($this->request->isPost()) {
  9823. $params = $this->request->post('row/a');
  9824. if (!is_array($params)) {
  9825. $this->error(__('Parameter %s can not be empty', ''));
  9826. }
  9827. try {
  9828. $sid = $this->saveManualPickOrder($params);
  9829. } catch (\InvalidArgumentException $e) {
  9830. $this->error($e->getMessage());
  9831. } catch (\Throwable $e) {
  9832. $this->error($e->getMessage());
  9833. }
  9834. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  9835. }
  9836. return $this->view->fetch('procuremen/pick_add');
  9837. }
  9838. /**
  9839. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  9840. */
  9841. public function pickSubmit()
  9842. {
  9843. if (!$this->request->isPost()) {
  9844. $this->error(__('Invalid parameters'));
  9845. }
  9846. // ---------- 接口订单数据 ----------
  9847. $rowJson = $this->request->post('row_json', '');
  9848. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  9849. $companiesJson = $this->request->post('companies_json', '[]');
  9850. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  9851. $companies = json_decode($companiesJson, true);
  9852. if (!is_array($companies)) {
  9853. $this->error('供应商数据无效');
  9854. }
  9855. $issueCompanies = $this->normalizePickCompanies($companies);
  9856. if ($issueCompanies === []) {
  9857. $this->error('请至少选择一家合作供应商');
  9858. }
  9859. $issueNameLabels = [];
  9860. foreach ($issueCompanies as $pc) {
  9861. $issueNameLabels[] = $pc['name'];
  9862. }
  9863. $issueNamesSummary = implode('、', $issueNameLabels);
  9864. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  9865. if ($sysRq === '') {
  9866. $this->error('请选择招标截止日期');
  9867. }
  9868. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  9869. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  9870. (string)$this->request->post('delivery_deadline', ''),
  9871. true
  9872. );
  9873. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  9874. if ($scoreRuleId <= 0) {
  9875. $this->error('请选择订单类型');
  9876. }
  9877. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  9878. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  9879. $this->error('订单类型无效,请刷新后重选');
  9880. }
  9881. $scoreRuleId = (int)$scoreRule['id'];
  9882. $this->ensurePurchaseOrderScoreRuleIdColumn();
  9883. $isMerge = count($mergeRows) > 1;
  9884. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  9885. $logMsg = '下发' . $procPart
  9886. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  9887. $issueTime = date('Y-m-d H:i:s');
  9888. $logSidList = [];
  9889. foreach ($mergeRows as $row) {
  9890. if (!is_array($row)) {
  9891. continue;
  9892. }
  9893. $sid = $this->extractScydgyRowId($row);
  9894. if ($this->isValidScydgyRowId($sid)) {
  9895. $logSidList[$sid] = true;
  9896. }
  9897. }
  9898. $existingBySid = [];
  9899. if ($logSidList !== []) {
  9900. try {
  9901. $existingRows = Db::table('purchase_order')
  9902. ->where('scydgy_id', 'in', array_keys($logSidList))
  9903. ->select();
  9904. if (is_array($existingRows)) {
  9905. foreach ($existingRows as $poRow) {
  9906. if (!is_array($poRow)) {
  9907. continue;
  9908. }
  9909. $sid = (int)($poRow['scydgy_id'] ?? 0);
  9910. if ($this->isValidScydgyRowId($sid)) {
  9911. $existingBySid[$sid] = $poRow;
  9912. }
  9913. }
  9914. }
  9915. } catch (\Throwable $e) {
  9916. $existingBySid = [];
  9917. }
  9918. }
  9919. Db::startTrans();
  9920. try {
  9921. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  9922. foreach ($mergeRows as $row) {
  9923. if (!is_array($row)) {
  9924. continue;
  9925. }
  9926. $sid = $this->extractScydgyRowId($row);
  9927. $this->upsertPurchaseOrderFromRow(
  9928. $row,
  9929. $sysRqDb,
  9930. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9931. $issueTime,
  9932. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  9933. $deliveryDeadlineDb,
  9934. $scoreRule
  9935. );
  9936. }
  9937. foreach ($issueCompanies as $c) {
  9938. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  9939. }
  9940. Db::commit();
  9941. } catch (\Throwable $e) {
  9942. Db::rollback();
  9943. $this->error($e->getMessage());
  9944. }
  9945. $poIdBySid = [];
  9946. if ($logSidList !== []) {
  9947. try {
  9948. $poIdBySid = Db::table('purchase_order')
  9949. ->where('scydgy_id', 'in', array_keys($logSidList))
  9950. ->column('id', 'scydgy_id');
  9951. } catch (\Throwable $e) {
  9952. $poIdBySid = [];
  9953. }
  9954. }
  9955. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  9956. if ($logSidList !== []) {
  9957. list($adminId, $adminName) = $this->GetUseName();
  9958. $logRows = [];
  9959. $seenLogSid = [];
  9960. foreach ($mergeRows as $row) {
  9961. if (!is_array($row)) {
  9962. continue;
  9963. }
  9964. $ids = $this->extractScydgyRowId($row);
  9965. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  9966. continue;
  9967. }
  9968. $seenLogSid[$ids] = true;
  9969. $poIdLog = null;
  9970. if (isset($poIdBySid[$ids])) {
  9971. $tid = (int)$poIdBySid[$ids];
  9972. $poIdLog = $tid > 0 ? $tid : null;
  9973. }
  9974. $logRows[] = ProcuremenOperLog::buildInsertRow(
  9975. $ids,
  9976. 'issue_submit',
  9977. $logMsg,
  9978. $poIdLog,
  9979. (int)$adminId,
  9980. (string)$adminName
  9981. );
  9982. }
  9983. if ($logRows !== []) {
  9984. try {
  9985. Db::table('purchase_order_oper_log')->insertAll($logRows);
  9986. } catch (\Throwable $e) {
  9987. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  9988. }
  9989. }
  9990. }
  9991. $notifyErrors = [];
  9992. $posNotify = [];
  9993. if ($logSidList !== []) {
  9994. try {
  9995. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  9996. } catch (\Throwable $e) {
  9997. $posNotify = [];
  9998. }
  9999. }
  10000. if (!is_array($posNotify)) {
  10001. $posNotify = [];
  10002. }
  10003. foreach ($posNotify as $i => $prow) {
  10004. if (is_array($posNotify[$i])) {
  10005. $posNotify[$i]['sys_rq'] = $sysRqDb;
  10006. }
  10007. }
  10008. $ccydhPick = '';
  10009. foreach ($mergeRows as $row) {
  10010. if (!is_array($row)) {
  10011. continue;
  10012. }
  10013. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10014. if ($ccydhPick !== '') {
  10015. break;
  10016. }
  10017. }
  10018. $notifyBundleBase = [
  10019. 'ccydh' => $ccydhPick,
  10020. 'pos' => $posNotify,
  10021. 'merge_rows' => $mergeRows,
  10022. ];
  10023. try {
  10024. $this->notifyDryRunPreview = [];
  10025. foreach ($issueCompanies as $c) {
  10026. if (!is_array($c)) {
  10027. continue;
  10028. }
  10029. $cname = trim((string)($c['name'] ?? ''));
  10030. if ($cname === '') {
  10031. continue;
  10032. }
  10033. try {
  10034. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10035. } catch (\Throwable $e) {
  10036. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10037. }
  10038. }
  10039. } catch (\Throwable $e) {
  10040. $this->error('通知发送失败:' . $e->getMessage());
  10041. }
  10042. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10043. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10044. }
  10045. if ($this->isProcuremenNotifyDryRun()) {
  10046. $this->success('【演练模式】已保存并生成通知预览', '', [
  10047. 'notify_dry_run' => true,
  10048. 'notify_preview' => $this->notifyDryRunPreview,
  10049. ]);
  10050. }
  10051. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10052. }
  10053. /**
  10054. * 确认供应商弹窗
  10055. */
  10056. public function auditIssue()
  10057. {
  10058. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10059. if (is_array($ids)) {
  10060. $ids = isset($ids[0]) ? $ids[0] : '';
  10061. }
  10062. $ids = trim((string)$ids);
  10063. if ($ids === '') {
  10064. $this->error(__('Invalid parameters'));
  10065. }
  10066. if ($this->request->isPost()) {
  10067. $this->error('请使用弹窗内「确认」提交');
  10068. }
  10069. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10070. $pos = $bundle['pos'];
  10071. if ($pos === []) {
  10072. $this->error('该订单不在待确认供应商状态');
  10073. }
  10074. $po = $pos[0];
  10075. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10076. if ($quoteGroups === []) {
  10077. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10078. }
  10079. $pickedName = '';
  10080. foreach ($pos as $poRow) {
  10081. if (!is_array($poRow)) {
  10082. continue;
  10083. }
  10084. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10085. if ($pn !== '') {
  10086. $pickedName = $pn;
  10087. break;
  10088. }
  10089. }
  10090. $this->view->assign('po', $po);
  10091. $this->view->assign('scydgyId', $ids);
  10092. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10093. $mergeRows = $bundle['merge_rows'];
  10094. $this->view->assign('processRows', $mergeRows);
  10095. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10096. $this->view->assign('processCount', count($mergeRows));
  10097. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10098. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10099. $this->view->assign('pickedCompanyName', $pickedName);
  10100. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10101. if ($sysRqForView === '') {
  10102. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10103. }
  10104. $this->view->assign('sysRq', $sysRqForView);
  10105. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10106. if ($deliveryDeadlineForView === '') {
  10107. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10108. }
  10109. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10110. $this->ensurePurchaseOrderManualPickColumns();
  10111. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10112. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10113. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10114. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10115. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10116. $pickedName = $manualPickInfo['company'];
  10117. $this->view->assign('pickedCompanyName', $pickedName);
  10118. }
  10119. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10120. $this->view->assign('manualPicked', $manualPicked);
  10121. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10122. $this->view->assign('quoteVisible', $quoteVisible);
  10123. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10124. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10125. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10126. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10127. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10128. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10129. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10130. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10131. return $this->view->fetch('procuremen/audit_issue');
  10132. }
  10133. /**
  10134. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10135. *
  10136. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10137. */
  10138. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10139. {
  10140. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10141. return false;
  10142. }
  10143. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10144. return false;
  10145. }
  10146. return true;
  10147. }
  10148. /**
  10149. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10150. *
  10151. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10152. */
  10153. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10154. {
  10155. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10156. return false;
  10157. }
  10158. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10159. return false;
  10160. }
  10161. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10162. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10163. return true;
  10164. }
  10165. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10166. }
  10167. /**
  10168. * 确认页 — 补加供应商弹窗
  10169. */
  10170. public function auditAppend()
  10171. {
  10172. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10173. $this->error(__('You have no permission'));
  10174. }
  10175. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10176. if (is_array($ids)) {
  10177. $ids = isset($ids[0]) ? $ids[0] : '';
  10178. }
  10179. $ids = trim((string)$ids);
  10180. if ($ids === '') {
  10181. $this->error(__('Invalid parameters'));
  10182. }
  10183. if ($this->request->isPost()) {
  10184. $this->error('请使用弹窗内「确认」提交');
  10185. }
  10186. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10187. if (($bundle['pos'] ?? []) === []) {
  10188. $this->error('该订单不在待确认供应商状态');
  10189. }
  10190. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10191. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10192. $this->error('已开标验证,不能再补加供应商');
  10193. }
  10194. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10195. $this->error('已指定供应商,不能再补加供应商');
  10196. }
  10197. $this->error('已经超过了招标截止日期,不可操作');
  10198. }
  10199. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10200. $existingNames = [];
  10201. foreach ($quoteGroups as $g) {
  10202. if (!is_array($g)) {
  10203. continue;
  10204. }
  10205. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10206. if ($n !== '') {
  10207. $existingNames[$n] = true;
  10208. }
  10209. }
  10210. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10211. $mergeRows = $bundle['merge_rows'] ?? [];
  10212. $this->view->assign('scydgyId', $ids);
  10213. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10214. $this->view->assign('po', $po);
  10215. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10216. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10217. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10218. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10219. if ($sysRqForView === '') {
  10220. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10221. }
  10222. $this->view->assign('sysRq', $sysRqForView);
  10223. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10224. if ($deliveryDeadlineForView === '') {
  10225. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10226. }
  10227. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10228. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10229. }
  10230. /**
  10231. * 确认页 — 补加供应商提交
  10232. */
  10233. public function auditAppendSubmit()
  10234. {
  10235. if (!$this->request->isPost()) {
  10236. $this->error(__('Invalid parameters'));
  10237. }
  10238. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10239. $this->error(__('You have no permission'));
  10240. }
  10241. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10242. if ($ids === '') {
  10243. $this->error(__('Invalid parameters'));
  10244. }
  10245. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10246. if (($bundle['pos'] ?? []) === []) {
  10247. $this->error('该订单不在待确认供应商状态');
  10248. }
  10249. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10250. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10251. $this->error('已开标验证,不能再补加供应商');
  10252. }
  10253. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10254. $this->error('已指定供应商,不能再补加供应商');
  10255. }
  10256. $this->error('已经超过了招标截止日期,不可操作');
  10257. }
  10258. $companiesJson = $this->request->post('companies_json', '[]');
  10259. $companies = json_decode((string)$companiesJson, true);
  10260. if (!is_array($companies)) {
  10261. $this->error('供应商数据无效');
  10262. }
  10263. $issueCompanies = $this->normalizePickCompanies($companies);
  10264. if ($issueCompanies === []) {
  10265. $this->error('请至少选择一家合作供应商');
  10266. }
  10267. $mergeRows = $bundle['merge_rows'] ?? [];
  10268. if (!is_array($mergeRows) || $mergeRows === []) {
  10269. $this->error('未找到工序行,无法补加');
  10270. }
  10271. $existingNames = [];
  10272. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10273. if (!is_array($g)) {
  10274. continue;
  10275. }
  10276. $n = trim((string)($g['company_name'] ?? ''));
  10277. if ($n !== '') {
  10278. $existingNames[$n] = true;
  10279. }
  10280. }
  10281. $toAdd = [];
  10282. foreach ($issueCompanies as $c) {
  10283. if (!is_array($c)) {
  10284. continue;
  10285. }
  10286. $n = trim((string)($c['name'] ?? ''));
  10287. if ($n === '' || isset($existingNames[$n])) {
  10288. continue;
  10289. }
  10290. $toAdd[] = $c;
  10291. }
  10292. if ($toAdd === []) {
  10293. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10294. }
  10295. $addedNames = [];
  10296. Db::startTrans();
  10297. try {
  10298. foreach ($toAdd as $c) {
  10299. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10300. $addedNames[] = trim((string)($c['name'] ?? ''));
  10301. }
  10302. Db::commit();
  10303. } catch (\Throwable $e) {
  10304. Db::rollback();
  10305. $this->error($e->getMessage());
  10306. }
  10307. $notifyErrors = [];
  10308. $notifyBundleBase = [
  10309. 'ccydh' => $bundle['ccydh'] ?? '',
  10310. 'pos' => $bundle['pos'] ?? [],
  10311. 'merge_rows' => $mergeRows,
  10312. ];
  10313. foreach ($toAdd as $c) {
  10314. if (!is_array($c)) {
  10315. continue;
  10316. }
  10317. $cname = trim((string)($c['name'] ?? ''));
  10318. if ($cname === '') {
  10319. continue;
  10320. }
  10321. try {
  10322. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10323. } catch (\Throwable $e) {
  10324. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10325. }
  10326. }
  10327. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10328. $seenLogSid = [];
  10329. foreach ($bundle['pos'] ?? [] as $poRow) {
  10330. if (!is_array($poRow)) {
  10331. continue;
  10332. }
  10333. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10334. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10335. continue;
  10336. }
  10337. $seenLogSid[$sid] = true;
  10338. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10339. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10340. }
  10341. if ($seenLogSid === []) {
  10342. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10343. if ($this->isValidScydgyRowId($logSid)) {
  10344. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10345. }
  10346. }
  10347. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10348. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  10349. }
  10350. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  10351. }
  10352. /**
  10353. * 开标双重验证 — 可选验证人列表
  10354. */
  10355. public function bidOpenUsers()
  10356. {
  10357. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10358. $this->error('无权限');
  10359. }
  10360. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  10361. if ($scydgyId !== '') {
  10362. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10363. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10364. $this->success('已完成开标验证', null, [
  10365. 'verified' => 1,
  10366. 'users' => [],
  10367. ]);
  10368. }
  10369. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10370. $this->error('本单已指定供应商,无需再开标');
  10371. }
  10372. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10373. }
  10374. $this->success('', null, [
  10375. 'verified' => 0,
  10376. 'users' => $this->listBidOpenVerifierCandidates(),
  10377. ]);
  10378. }
  10379. /**
  10380. * 开标双重验证 — 向指定管理员发送短信验证码
  10381. */
  10382. public function bidOpenSendCode()
  10383. {
  10384. if (!$this->request->isPost()) {
  10385. $this->error(__('Invalid parameters'));
  10386. }
  10387. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10388. $this->error('无权限');
  10389. }
  10390. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10391. $adminId = (int)$this->request->post('admin_id', 0);
  10392. if ($scydgyId === '' || $adminId <= 0) {
  10393. $this->error('参数无效');
  10394. }
  10395. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10396. if ($bundle['pos'] === []) {
  10397. $this->error('该订单不在待确认供应商状态');
  10398. }
  10399. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10400. $this->success('已完成开标验证,无需重复发送');
  10401. }
  10402. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10403. $this->error('本单已指定供应商,无需再开标');
  10404. }
  10405. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10406. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10407. if ($ccydh === '') {
  10408. $this->error('订单号无效');
  10409. }
  10410. $admin = $this->loadBidOpenAdminUser($adminId);
  10411. if ($admin === null) {
  10412. $this->error('验证人无效或未绑定手机号');
  10413. }
  10414. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  10415. $cd = max(30, min(120, $cd));
  10416. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  10417. $this->error('发送过于频繁,请稍后再试');
  10418. }
  10419. $code = (string)random_int(100000, 999999);
  10420. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  10421. $ttl = max(60, min(600, $ttl));
  10422. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  10423. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  10424. try {
  10425. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  10426. } catch (\Throwable $e) {
  10427. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  10428. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  10429. $this->error($e->getMessage());
  10430. }
  10431. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  10432. }
  10433. /**
  10434. * 开标双重验证 — 两人验证码校验并记录
  10435. */
  10436. public function bidOpenVerify()
  10437. {
  10438. if (!$this->request->isPost()) {
  10439. $this->error(__('Invalid parameters'));
  10440. }
  10441. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10442. $this->error('无权限');
  10443. }
  10444. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10445. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  10446. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  10447. $code1 = trim((string)$this->request->post('code1', ''));
  10448. $code2 = trim((string)$this->request->post('code2', ''));
  10449. if ($scydgyId === '') {
  10450. $this->error('参数无效');
  10451. }
  10452. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  10453. $this->error('请选择两位验证人');
  10454. }
  10455. if ($verifier1Id === $verifier2Id) {
  10456. $this->error('两位验证人不能相同');
  10457. }
  10458. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  10459. $this->error('请输入6位短信验证码');
  10460. }
  10461. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10462. if ($bundle['pos'] === []) {
  10463. $this->error('该订单不在待确认供应商状态');
  10464. }
  10465. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10466. if ($ccydh === '') {
  10467. $this->error('订单号无效');
  10468. }
  10469. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10470. $this->success('已完成开标验证');
  10471. }
  10472. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10473. $this->error('本单已指定供应商,无需再开标');
  10474. }
  10475. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10476. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  10477. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  10478. if ($verifier1 === null || $verifier2 === null) {
  10479. $this->error('验证人无效或未绑定手机号');
  10480. }
  10481. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  10482. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  10483. }
  10484. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  10485. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  10486. }
  10487. try {
  10488. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  10489. } catch (\Throwable $e) {
  10490. $this->error($e->getMessage());
  10491. }
  10492. $this->success('开标验证成功,可查看供应商报价与交货日期');
  10493. }
  10494. /**
  10495. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  10496. */
  10497. public function auditManualPick()
  10498. {
  10499. if (!$this->request->isPost()) {
  10500. $this->error(__('Invalid parameters'));
  10501. }
  10502. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  10503. $this->error('无权限');
  10504. }
  10505. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10506. if ($scydgyId === '') {
  10507. $this->error('参数无效');
  10508. }
  10509. $companyName = trim((string)$this->request->post('selected_company', ''));
  10510. $reason = trim((string)$this->request->post('pick_reason', ''));
  10511. if ($companyName === '') {
  10512. $this->error('请选择一家供应商');
  10513. }
  10514. if ($reason === '') {
  10515. $this->error('请填写选择说明');
  10516. }
  10517. if (mb_strlen($reason) > 500) {
  10518. $this->error('选择说明不能超过500字');
  10519. }
  10520. $this->ensurePurchaseOrderManualPickColumns();
  10521. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10522. $pos = $bundle['pos'];
  10523. if ($pos === []) {
  10524. $this->error('该订单不在待确认供应商状态');
  10525. }
  10526. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10527. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  10528. }
  10529. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10530. if ($quoteGroups === []) {
  10531. $this->error('暂无供应商,请确认已完成协助初选通知');
  10532. }
  10533. $matched = null;
  10534. foreach ($quoteGroups as $g) {
  10535. if (!is_array($g)) {
  10536. continue;
  10537. }
  10538. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10539. $matched = $g;
  10540. break;
  10541. }
  10542. }
  10543. if ($matched === null) {
  10544. $this->error('所选供应商不在本单报价列表中');
  10545. }
  10546. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  10547. Db::startTrans();
  10548. try {
  10549. foreach ($pos as $poRow) {
  10550. if (!is_array($poRow)) {
  10551. continue;
  10552. }
  10553. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10554. if (!$this->isValidScydgyRowId($sid)) {
  10555. continue;
  10556. }
  10557. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10558. 'pick_company_name' => $companyName,
  10559. 'manual_pick' => 1,
  10560. 'manual_pick_reason' => $reason,
  10561. ]);
  10562. }
  10563. Db::commit();
  10564. } catch (\Throwable $e) {
  10565. Db::rollback();
  10566. $this->error($e->getMessage());
  10567. }
  10568. foreach ($pos as $poRow) {
  10569. if (!is_array($poRow)) {
  10570. continue;
  10571. }
  10572. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10573. if (!$this->isValidScydgyRowId($sid)) {
  10574. continue;
  10575. }
  10576. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10577. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10578. }
  10579. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  10580. try {
  10581. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10582. if ($ccydh !== '') {
  10583. // 重新加载以拿到未掩码报价参与计分
  10584. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10585. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  10586. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  10587. }
  10588. } catch (\Throwable $e) {
  10589. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  10590. }
  10591. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  10592. }
  10593. /**
  10594. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  10595. */
  10596. public function auditSubmit()
  10597. {
  10598. if (!$this->request->isPost()) {
  10599. $this->error(__('Invalid parameters'));
  10600. }
  10601. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10602. if ($scydgyId === '') {
  10603. $this->error('参数无效');
  10604. }
  10605. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10606. $pos = $bundle['pos'];
  10607. $mergeRows = $bundle['merge_rows'];
  10608. if ($pos === [] || $mergeRows === []) {
  10609. $this->error('该订单不在待确认供应商状态');
  10610. }
  10611. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10612. if ($quoteGroups === []) {
  10613. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  10614. }
  10615. $companyName = trim((string)$this->request->post('selected_company', ''));
  10616. if ($companyName === '') {
  10617. $this->error('请选择一家供应商');
  10618. }
  10619. $matched = null;
  10620. foreach ($quoteGroups as $g) {
  10621. if (!is_array($g)) {
  10622. continue;
  10623. }
  10624. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10625. $matched = $g;
  10626. break;
  10627. }
  10628. }
  10629. if ($matched === null) {
  10630. $this->error('所选供应商不在本单报价列表中');
  10631. }
  10632. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10633. if ($sysRqDb === '') {
  10634. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  10635. } else {
  10636. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  10637. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  10638. }
  10639. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  10640. $this->error('未到招标截止日期,暂不可确认');
  10641. }
  10642. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  10643. && !$this->isProcuremenManualPickedForBundle($bundle)
  10644. ) {
  10645. $this->error('请先完成开标双重验证或指定供应商后再确认');
  10646. }
  10647. $procCnt = count($mergeRows);
  10648. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  10649. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  10650. Db::startTrans();
  10651. try {
  10652. foreach ($pos as $poRow) {
  10653. if (!is_array($poRow)) {
  10654. continue;
  10655. }
  10656. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10657. if (!$this->isValidScydgyRowId($sid)) {
  10658. continue;
  10659. }
  10660. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10661. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  10662. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10663. 'pick_company_name' => $companyName,
  10664. 'sys_rq' => $sysRqDb,
  10665. ]);
  10666. }
  10667. Db::commit();
  10668. } catch (\Throwable $e) {
  10669. Db::rollback();
  10670. $this->error($e->getMessage());
  10671. }
  10672. foreach ($pos as $poRow) {
  10673. if (!is_array($poRow)) {
  10674. continue;
  10675. }
  10676. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10677. if (!$this->isValidScydgyRowId($sid)) {
  10678. continue;
  10679. }
  10680. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10681. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10682. }
  10683. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  10684. }
  10685. /**
  10686. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  10687. */
  10688. public function auditResendSms()
  10689. {
  10690. if (!$this->request->isPost()) {
  10691. $this->error(__('Invalid parameters'));
  10692. }
  10693. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10694. if ($scydgyId === '') {
  10695. $this->error('参数无效');
  10696. }
  10697. $loaded = $this->loadAuditResendBundle($scydgyId);
  10698. $mergeRows = $loaded['merge_rows'];
  10699. $bundle = $loaded['bundle'];
  10700. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10701. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10702. if ($quoteGroups === []) {
  10703. $this->error('暂无可通知的供应商');
  10704. }
  10705. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10706. $companiesJson = (string)$this->request->post('companies_json', '');
  10707. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10708. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  10709. }
  10710. /**
  10711. * 确认供应商 — 二次发送邮件(可选单家/批量)
  10712. */
  10713. public function auditResendEmail()
  10714. {
  10715. if (!$this->request->isPost()) {
  10716. $this->error(__('Invalid parameters'));
  10717. }
  10718. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10719. if ($scydgyId === '') {
  10720. $this->error('参数无效');
  10721. }
  10722. $loaded = $this->loadAuditResendBundle($scydgyId);
  10723. $mergeRows = $loaded['merge_rows'];
  10724. $bundle = $loaded['bundle'];
  10725. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10726. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10727. if ($quoteGroups === []) {
  10728. $this->error('暂无可通知的供应商');
  10729. }
  10730. $companiesJson = (string)$this->request->post('companies_json', '');
  10731. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10732. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10733. if ($companiesJson === '' && $selectedCompany === '') {
  10734. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  10735. }
  10736. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  10737. }
  10738. /**
  10739. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  10740. *
  10741. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  10742. * @return array<int, true> 已处理的 scydgy_id 集合
  10743. */
  10744. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  10745. {
  10746. $pos = $bundle['pos'] ?? [];
  10747. if (!is_array($pos) || $pos === []) {
  10748. return [];
  10749. }
  10750. $sids = [];
  10751. $poIdBySid = [];
  10752. foreach ($pos as $poRow) {
  10753. if (!is_array($poRow)) {
  10754. continue;
  10755. }
  10756. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10757. if ($this->isValidScydgyRowId($sid)) {
  10758. $sids[$sid] = true;
  10759. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10760. if ($poId > 0) {
  10761. $poIdBySid[$sid] = $poId;
  10762. }
  10763. }
  10764. }
  10765. if ($sids === []) {
  10766. return [];
  10767. }
  10768. $logMsg = '重新下发';
  10769. $suffix = trim((string)$logSuffix, ',, ');
  10770. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  10771. $logMsg .= ':从历史存证退回协助初选';
  10772. } else {
  10773. $logMsg .= ':退回协助初选';
  10774. }
  10775. Db::table('purchase_order')
  10776. ->where('scydgy_id', 'in', array_keys($sids))
  10777. ->update([
  10778. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  10779. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10780. 'pick_company_name' => '',
  10781. 'pick_time' => null,
  10782. 'sys_rq' => null,
  10783. 'mod_rq' => null,
  10784. ]);
  10785. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  10786. foreach (array_keys($sids) as $sid) {
  10787. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  10788. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10789. }
  10790. return $sids;
  10791. }
  10792. /**
  10793. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  10794. *
  10795. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10796. */
  10797. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  10798. {
  10799. $scydgyId = trim($scydgyId);
  10800. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10801. if ($scydgyId === '') {
  10802. return $empty;
  10803. }
  10804. try {
  10805. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10806. } catch (\Throwable $e) {
  10807. $anchor = null;
  10808. }
  10809. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  10810. return $empty;
  10811. }
  10812. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10813. if ($ccydh === '') {
  10814. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10815. }
  10816. try {
  10817. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  10818. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  10819. $pos = $query->order('scydgy_id', 'asc')->select();
  10820. } catch (\Throwable $e) {
  10821. $pos = [$anchor];
  10822. }
  10823. if (!is_array($pos) || $pos === []) {
  10824. $pos = [$anchor];
  10825. }
  10826. return [
  10827. 'ccydh' => $ccydh,
  10828. 'pos' => $pos,
  10829. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10830. ];
  10831. }
  10832. protected function purchaseOrderRowIsCompleted(array $po): bool
  10833. {
  10834. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  10835. }
  10836. /**
  10837. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  10838. *
  10839. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10840. */
  10841. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  10842. {
  10843. $scydgyId = trim($scydgyId);
  10844. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10845. if ($scydgyId === '') {
  10846. return $empty;
  10847. }
  10848. try {
  10849. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10850. } catch (\Throwable $e) {
  10851. $anchor = null;
  10852. }
  10853. if (!is_array($anchor)) {
  10854. return $empty;
  10855. }
  10856. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10857. if ($ccydh === '') {
  10858. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10859. }
  10860. try {
  10861. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  10862. } catch (\Throwable $e) {
  10863. $pos = [$anchor];
  10864. }
  10865. if (!is_array($pos) || $pos === []) {
  10866. $pos = [$anchor];
  10867. }
  10868. return [
  10869. 'ccydh' => $ccydh,
  10870. 'pos' => $pos,
  10871. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10872. ];
  10873. }
  10874. /**
  10875. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  10876. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  10877. */
  10878. public function auditAbandon()
  10879. {
  10880. if (!$this->request->isPost()) {
  10881. $this->error(__('Invalid parameters'));
  10882. }
  10883. $anchorIds = [];
  10884. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  10885. if ($batchRaw !== '') {
  10886. $decoded = json_decode($batchRaw, true);
  10887. if (is_array($decoded)) {
  10888. foreach ($decoded as $id) {
  10889. $s = trim((string)$id);
  10890. if ($s !== '') {
  10891. $anchorIds[] = $s;
  10892. }
  10893. }
  10894. }
  10895. }
  10896. if ($anchorIds === []) {
  10897. $single = trim((string)$this->request->post('scydgy_id', ''));
  10898. if ($single !== '') {
  10899. $anchorIds[] = $single;
  10900. }
  10901. }
  10902. if ($anchorIds === []) {
  10903. $this->error('请至少选择一条订单');
  10904. }
  10905. $processedCcydh = [];
  10906. $doneOrders = 0;
  10907. $allSids = [];
  10908. Db::startTrans();
  10909. try {
  10910. foreach ($anchorIds as $anchorId) {
  10911. $fromArchive = false;
  10912. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  10913. if (($bundle['pos'] ?? []) === []) {
  10914. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  10915. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10916. }
  10917. if (($bundle['pos'] ?? []) === []) {
  10918. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  10919. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10920. }
  10921. if (($bundle['pos'] ?? []) === []) {
  10922. continue;
  10923. }
  10924. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10925. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  10926. if (isset($processedCcydh[$dedupeKey])) {
  10927. continue;
  10928. }
  10929. $processedCcydh[$dedupeKey] = true;
  10930. $sids = $fromArchive
  10931. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  10932. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  10933. if ($sids === []) {
  10934. continue;
  10935. }
  10936. $doneOrders++;
  10937. foreach (array_keys($sids) as $sid) {
  10938. $allSids[(int)$sid] = true;
  10939. }
  10940. }
  10941. if ($doneOrders < 1) {
  10942. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  10943. }
  10944. Db::commit();
  10945. } catch (\Throwable $e) {
  10946. Db::rollback();
  10947. $this->error($e->getMessage());
  10948. }
  10949. $this->pickHiddenScydgySetCache = null;
  10950. $msg = $doneOrders > 1
  10951. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  10952. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  10953. $this->success($msg);
  10954. }
  10955. /**
  10956. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  10957. */
  10958. public function archiveAbandon()
  10959. {
  10960. return $this->auditAbandon();
  10961. }
  10962. /**
  10963. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  10964. */
  10965. public function purchaseApprovalReject()
  10966. {
  10967. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10968. $this->error(__('Invalid parameters'));
  10969. }
  10970. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  10971. $this->error(__('You have no permission'));
  10972. }
  10973. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  10974. $decoded = json_decode($batchRaw, true);
  10975. if (!is_array($decoded) || $decoded === []) {
  10976. $this->error('提交数据无效');
  10977. }
  10978. $done = 0;
  10979. Db::startTrans();
  10980. try {
  10981. foreach ($decoded as $item) {
  10982. if (!is_array($item)) {
  10983. continue;
  10984. }
  10985. $sid = (int)($item['scydgy_id'] ?? 0);
  10986. if (!$this->isValidScydgyRowId($sid)) {
  10987. continue;
  10988. }
  10989. $this->runPurchaseApprovalRejectForSid($sid);
  10990. $done++;
  10991. }
  10992. if ($done < 1) {
  10993. throw new \Exception('所选订单均不在待审批状态');
  10994. }
  10995. Db::commit();
  10996. } catch (\Throwable $e) {
  10997. Db::rollback();
  10998. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  10999. }
  11000. $this->pickHiddenScydgySetCache = null;
  11001. $this->success('已驳回并退回「协助审批下发」');
  11002. }
  11003. /**
  11004. * @throws \Exception
  11005. */
  11006. protected function runPurchaseApprovalRejectForSid(int $sid): void
  11007. {
  11008. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  11009. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  11010. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11011. $allIds = $this->purchaseOrderDetail($sid);
  11012. if ($allIds === []) {
  11013. throw new \Exception('未找到下发明细');
  11014. }
  11015. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11016. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11017. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11018. 'pick_company_name' => '',
  11019. ]);
  11020. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11021. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11022. $poId = 0;
  11023. try {
  11024. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11025. if (is_array($po)) {
  11026. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11027. }
  11028. } catch (\Throwable $e) {
  11029. }
  11030. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11031. }
  11032. /**
  11033. * 审核弹窗(旧入口,POST 已关闭)
  11034. */
  11035. public function review()
  11036. {
  11037. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11038. $this->error(__('You have no permission'));
  11039. }
  11040. if ($this->request->isPost()) {
  11041. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11042. }
  11043. $this->view->assign('pickMode', 0);
  11044. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11045. }
  11046. /**
  11047. * 审核弹窗获取公司列表
  11048. */
  11049. public function reviewCompanies()
  11050. {
  11051. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11052. $this->error(__('You have no permission'));
  11053. }
  11054. if (!$this->request->isAjax()) {
  11055. $this->error(__('Invalid parameters'));
  11056. }
  11057. $list = [];
  11058. try {
  11059. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11060. $rows = Db::table('customer')
  11061. ->where(function ($q) {
  11062. $q->where('status', 1)
  11063. ->whereOr('status', '1')
  11064. ->whereOr('status', '')
  11065. ->whereNull('status');
  11066. })
  11067. ->order('id', 'desc')
  11068. ->select();
  11069. } catch (\Throwable $e) {
  11070. $this->success('', '', []);
  11071. return;
  11072. }
  11073. if (!is_array($rows)) {
  11074. $this->success('', '', []);
  11075. return;
  11076. }
  11077. $detailColCandidates = [
  11078. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11079. 'company_detail', 'company_desc', 'address',
  11080. ];
  11081. foreach ($rows as $row) {
  11082. if (!is_array($row)) {
  11083. continue;
  11084. }
  11085. $norm = [];
  11086. foreach ($row as $k => $v) {
  11087. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11088. }
  11089. $row = $norm;
  11090. $st = $row['status'] ?? '';
  11091. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11092. continue;
  11093. }
  11094. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11095. if ($payload === null) {
  11096. continue;
  11097. }
  11098. $detail = '';
  11099. foreach ($detailColCandidates as $dk) {
  11100. if (!isset($row[$dk])) {
  11101. continue;
  11102. }
  11103. $dv = trim((string)$row[$dk]);
  11104. if ($dv !== '') {
  11105. $detail = $dv;
  11106. break;
  11107. }
  11108. }
  11109. $payload['detail'] = $detail;
  11110. $list[] = $this->maskSupplierContactFields($payload);
  11111. }
  11112. $this->success('', '', $list);
  11113. }
  11114. /**
  11115. * 采购确认-下发明细弹窗:
  11116. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11117. */
  11118. public function outward_detail()
  11119. {
  11120. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11121. if (is_array($ids)) {
  11122. $ids = isset($ids[0]) ? $ids[0] : '';
  11123. }
  11124. $ids = trim((string)$ids);
  11125. if ($ids === '') {
  11126. $this->error(__('Invalid parameters'));
  11127. }
  11128. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11129. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11130. $wffTab = 'all';
  11131. }
  11132. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11133. $purchaseOrderId = 0;
  11134. $po = null;
  11135. try {
  11136. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11137. if (is_array($po)) {
  11138. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11139. }
  11140. } catch (\Throwable $e) {
  11141. $purchaseOrderId = 0;
  11142. $po = null;
  11143. }
  11144. if (!$isPurchaseConfirm && is_array($po)) {
  11145. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11146. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11147. $isPurchaseConfirm = true;
  11148. }
  11149. }
  11150. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11151. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11152. $confirmProcessCount = 1;
  11153. $confirmPickGroups = [];
  11154. $processDisplayRows = [];
  11155. $allDetailsBySid = [];
  11156. $requiredSidList = [];
  11157. $sidList = [$ids];
  11158. if ($isPurchaseConfirm) {
  11159. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11160. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11161. if ($mergeRows !== []) {
  11162. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11163. }
  11164. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11165. if ($confirmBundle['pos'] !== []) {
  11166. $sidList = [];
  11167. foreach ($confirmBundle['pos'] as $poRow) {
  11168. if (!is_array($poRow)) {
  11169. continue;
  11170. }
  11171. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11172. if (!$this->isValidScydgyRowId($sid)) {
  11173. continue;
  11174. }
  11175. $sidList[] = (string)$sid;
  11176. $requiredSidList[] = $sid;
  11177. }
  11178. }
  11179. if ($sidList === []) {
  11180. $sidList = [$ids];
  11181. $requiredSidList = [(int)$ids];
  11182. }
  11183. $confirmProcessCount = max(1, count($requiredSidList));
  11184. if (is_array($po) && $purchaseOrderId <= 0) {
  11185. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11186. }
  11187. }
  11188. $rows = [];
  11189. try {
  11190. if (count($sidList) === 1) {
  11191. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11192. } else {
  11193. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11194. }
  11195. } catch (\Throwable $e) {
  11196. $rows = [];
  11197. }
  11198. if ($isPurchaseConfirm) {
  11199. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11200. }
  11201. foreach ($rows as &$r) {
  11202. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11203. $r['id'] = $r['ID'];
  11204. }
  11205. if (isset($r['createtime'])) {
  11206. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11207. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11208. } else {
  11209. $r['createtime_text'] = (string)$r['createtime'];
  11210. }
  11211. } else {
  11212. $r['createtime_text'] = '';
  11213. }
  11214. if (is_array($r)) {
  11215. $r = $this->maskSupplierContactFields($r);
  11216. }
  11217. }
  11218. unset($r);
  11219. $pickedCompanyName = '';
  11220. $manualPicked = 0;
  11221. $manualPickReason = '';
  11222. $quoteVisible = 0;
  11223. $bidOpenVerified = 0;
  11224. if ($isPurchaseConfirm) {
  11225. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11226. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11227. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11228. }
  11229. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11230. $confirmBundle['pos'] = [$po];
  11231. }
  11232. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11233. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11234. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11235. if ($manualPickInfo['company'] !== '') {
  11236. $pickedCompanyName = $manualPickInfo['company'];
  11237. }
  11238. if ($pickedCompanyName === '') {
  11239. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11240. if (!is_array($poRow)) {
  11241. continue;
  11242. }
  11243. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11244. if ($pn !== '') {
  11245. $pickedCompanyName = $pn;
  11246. break;
  11247. }
  11248. }
  11249. }
  11250. // 再兜底:直接读当前主单字段
  11251. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11252. $manualPicked = 1;
  11253. if ($manualPickReason === '') {
  11254. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11255. }
  11256. if ($pickedCompanyName === '') {
  11257. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11258. }
  11259. }
  11260. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11261. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11262. }
  11263. $this->view->assign('rows', $rows ?: []);
  11264. $this->view->assign('rowCount', count($rows ?: []));
  11265. $this->view->assign('scydgyId', $ids);
  11266. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11267. $this->view->assign('headTitle', $headTitle);
  11268. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11269. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11270. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11271. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11272. $this->view->assign('processDisplayRows', $processDisplayRows);
  11273. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11274. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11275. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11276. $this->view->assign('manualPicked', $manualPicked);
  11277. $this->view->assign('manualPickReason', $manualPickReason);
  11278. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11279. $this->view->assign('quoteVisible', $quoteVisible);
  11280. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11281. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11282. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11283. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11284. $sysRqDisplay = '—';
  11285. if ($isPurchaseConfirm) {
  11286. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11287. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11288. );
  11289. }
  11290. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11291. $this->view->assign('sysRq', $isPurchaseConfirm
  11292. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11293. : '');
  11294. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11295. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11296. : '');
  11297. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11298. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11299. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11300. if ($isPurchaseConfirm) {
  11301. return $this->view->fetch();
  11302. }
  11303. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11304. $this->view->engine->layout(false);
  11305. try {
  11306. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11307. $this->view->assign('dialogBody', $bodyHtml);
  11308. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11309. } finally {
  11310. if ($restoreLayout) {
  11311. $this->view->engine->layout($restoreLayout);
  11312. }
  11313. }
  11314. }
  11315. /**
  11316. * 月度导出记录表(不存在时自动创建)
  11317. */
  11318. protected function ensurePurchaseMonthExportLogTable(): void
  11319. {
  11320. try {
  11321. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11322. } catch (\Throwable $e) {
  11323. Db::execute(
  11324. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11325. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11326. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11327. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11328. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11329. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11330. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11331. `createtime` int(10) unsigned DEFAULT NULL,
  11332. PRIMARY KEY (`id`),
  11333. KEY `idx_ym` (`ym`),
  11334. KEY `idx_ct` (`createtime`)
  11335. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11336. );
  11337. }
  11338. }
  11339. /**
  11340. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11341. *
  11342. * @param array<int, mixed> $dbRows
  11343. * @return array<int, array<string, mixed>>
  11344. */
  11345. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11346. {
  11347. $keyword = trim((string)$this->request->get('search', ''));
  11348. if ($keyword === '') {
  11349. $keyword = trim((string)$this->request->request('search', ''));
  11350. }
  11351. $filter = $this->request->get('filter', '');
  11352. $op = $this->request->get('op', '');
  11353. if (is_string($filter) && $filter !== '') {
  11354. $filterArr = (array)json_decode($filter, true);
  11355. } else {
  11356. $filterArr = is_array($filter) ? $filter : [];
  11357. }
  11358. if (is_string($op) && $op !== '') {
  11359. $opArr = (array)json_decode($op, true);
  11360. } else {
  11361. $opArr = is_array($op) ? $op : [];
  11362. }
  11363. if ($keyword === '' && $filterArr === []) {
  11364. return array_values(array_filter($dbRows, 'is_array'));
  11365. }
  11366. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  11367. $out = [];
  11368. foreach ($dbRows as $row) {
  11369. if (!is_array($row)) {
  11370. continue;
  11371. }
  11372. if ($keyword !== '') {
  11373. $hit = false;
  11374. foreach ($searchFields as $f) {
  11375. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  11376. $hit = true;
  11377. break;
  11378. }
  11379. }
  11380. if (!$hit) {
  11381. continue;
  11382. }
  11383. }
  11384. $passFilter = true;
  11385. foreach ($filterArr as $field => $val) {
  11386. $field = (string)$field;
  11387. $val = trim((string)$val);
  11388. if ($field === '' || $val === '') {
  11389. continue;
  11390. }
  11391. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  11392. continue;
  11393. }
  11394. $cell = (string)($row[$field] ?? '');
  11395. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  11396. if ($mode === '=' || $mode === 'EQUAL') {
  11397. if (strcasecmp($cell, $val) !== 0) {
  11398. $passFilter = false;
  11399. break;
  11400. }
  11401. } elseif (mb_stripos($cell, $val) === false) {
  11402. $passFilter = false;
  11403. break;
  11404. }
  11405. }
  11406. if (!$passFilter) {
  11407. continue;
  11408. }
  11409. $out[] = $row;
  11410. }
  11411. return $out;
  11412. }
  11413. /**
  11414. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  11415. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  11416. */
  11417. public function export_month_outward()
  11418. {
  11419. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  11420. $this->error(__('You have no permission'));
  11421. }
  11422. $bundle = $this->prepareMonthOutwardExportBundle();
  11423. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11424. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  11425. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  11426. $spreadsheet = new Spreadsheet();
  11427. $sheet = $spreadsheet->getActiveSheet();
  11428. $sheet->setTitle('外协加工明细');
  11429. $mon = (int)substr($ym, 5, 2);
  11430. $sheet->mergeCells('A1:H1');
  11431. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  11432. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  11433. $sheet->getStyle('A1')->getAlignment()
  11434. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11435. ->setVertical(Alignment::VERTICAL_CENTER);
  11436. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  11437. $col = 'A';
  11438. foreach ($headers as $h) {
  11439. $sheet->setCellValue($col . '2', $h);
  11440. $col++;
  11441. }
  11442. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  11443. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11444. $rowNum = 3;
  11445. $sumSubtotalCounts = 0;
  11446. $grandAmount = 0.0;
  11447. $globalSeq = 0;
  11448. if ($groups === []) {
  11449. $sheet->mergeCells('A3:H3');
  11450. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  11451. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11452. $rowNum = 4;
  11453. } else {
  11454. foreach ($groups as $items) {
  11455. if ($items === []) {
  11456. continue;
  11457. }
  11458. $groupLineCount = count($items);
  11459. $subAmount = 0.0;
  11460. foreach ($items as $line) {
  11461. $globalSeq++;
  11462. $dr = $line['detail'];
  11463. $amt = $this->procuremenExportAmount($dr);
  11464. $subAmount += $amt;
  11465. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  11466. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  11467. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  11468. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  11469. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  11470. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  11471. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  11472. $sheet->setCellValue('H' . $rowNum, $amt);
  11473. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  11474. $rowNum++;
  11475. }
  11476. $sumSubtotalCounts += $groupLineCount;
  11477. $grandAmount += $subAmount;
  11478. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11479. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  11480. $sheet->getStyle('G' . $rowNum)->getAlignment()
  11481. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11482. ->setVertical(Alignment::VERTICAL_CENTER);
  11483. $rowNum++;
  11484. }
  11485. }
  11486. $sheet->setCellValue('A' . $rowNum, '总计');
  11487. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  11488. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11489. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  11490. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11491. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  11492. $lastRow = $rowNum;
  11493. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  11494. 'borders' => [
  11495. 'allBorders' => [
  11496. 'borderStyle' => Border::BORDER_THIN,
  11497. 'color' => ['rgb' => '000000'],
  11498. ],
  11499. ],
  11500. ]);
  11501. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11502. if ($lastRow >= 3) {
  11503. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11504. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11505. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11506. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11507. }
  11508. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  11509. $sheet->getColumnDimension('A')->setWidth(7);
  11510. $sheet->getColumnDimension('B')->setWidth(16);
  11511. $sheet->getColumnDimension('C')->setWidth(52);
  11512. $sheet->getColumnDimension('D')->setWidth(32);
  11513. $sheet->getColumnDimension('E')->setWidth(12);
  11514. $sheet->getColumnDimension('F')->setWidth(44);
  11515. $sheet->getColumnDimension('G')->setWidth(26);
  11516. $sheet->getColumnDimension('H')->setWidth(13);
  11517. $sheet->getRowDimension(1)->setRowHeight(28);
  11518. $ymCompact = str_replace('-', '', $ym);
  11519. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  11520. $filename = $fileBase . '.xlsx';
  11521. try {
  11522. $this->ensurePurchaseMonthExportLogTable();
  11523. list($adminId, $adminName) = $this->GetUseName();
  11524. Db::table('purchase_month_export_log')->insert([
  11525. 'ym' => $ym,
  11526. 'admin_id' => (int)$adminId,
  11527. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  11528. 'row_count' => count($exportLines),
  11529. 'total_amount' => round($grandAmount, 2),
  11530. 'createtime' => time(),
  11531. ]);
  11532. } catch (\Throwable $e) {
  11533. Log::write('month export log: ' . $e->getMessage(), 'error');
  11534. }
  11535. if (ob_get_length()) {
  11536. ob_end_clean();
  11537. }
  11538. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  11539. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11540. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11541. header('Cache-Control: max-age=0');
  11542. $writer = new Xlsx($spreadsheet);
  11543. $writer->save('php://output');
  11544. $spreadsheet->disconnectWorksheets();
  11545. unset($spreadsheet);
  11546. exit;
  11547. }
  11548. /**
  11549. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  11550. */
  11551. public function export_month_quote()
  11552. {
  11553. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  11554. $this->error(__('You have no permission'));
  11555. }
  11556. $bundle = $this->prepareMonthOutwardExportBundle();
  11557. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11558. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  11559. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  11560. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  11561. $spreadsheet = new Spreadsheet();
  11562. $sheet = $spreadsheet->getActiveSheet();
  11563. $sheet->setTitle('供应商报价明细');
  11564. $mon = (int)substr($ym, 5, 2);
  11565. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  11566. $sheet->getColumnDimension('A')->setWidth(7);
  11567. $sheet->getColumnDimension('B')->setWidth(16);
  11568. $sheet->getColumnDimension('C')->setWidth(52);
  11569. $sheet->getColumnDimension('D')->setWidth(26);
  11570. $sheet->getColumnDimension('E')->setWidth(32);
  11571. $sheet->getColumnDimension('F')->setWidth(12);
  11572. $sheet->getColumnDimension('G')->setWidth(14);
  11573. $sheet->getColumnDimension('H')->setWidth(12);
  11574. if ($quoteLastRow < 1) {
  11575. $quoteLastRow = 3;
  11576. }
  11577. $ymCompact = str_replace('-', '', $ym);
  11578. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  11579. if (ob_get_length()) {
  11580. ob_end_clean();
  11581. }
  11582. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  11583. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11584. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11585. header('Cache-Control: max-age=0');
  11586. $writer = new Xlsx($spreadsheet);
  11587. $writer->save('php://output');
  11588. $spreadsheet->disconnectWorksheets();
  11589. unset($spreadsheet);
  11590. exit;
  11591. }
  11592. /**
  11593. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  11594. *
  11595. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  11596. */
  11597. protected function prepareMonthOutwardExportBundle(): array
  11598. {
  11599. $this->request->filter(['strip_tags', 'trim']);
  11600. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  11601. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  11602. $ym = date('Y-m');
  11603. }
  11604. $dbRows = [];
  11605. try {
  11606. $query = Db::table('purchase_order');
  11607. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11608. $dbRows = $query->select();
  11609. } catch (\Throwable $e) {
  11610. $dbRows = [];
  11611. }
  11612. if (!is_array($dbRows)) {
  11613. $dbRows = [];
  11614. }
  11615. $completeTsMap = [];
  11616. $sidList = [];
  11617. foreach ($dbRows as $dbRow) {
  11618. if (!is_array($dbRow)) {
  11619. continue;
  11620. }
  11621. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  11622. if ($sid > 0) {
  11623. $sidList[$sid] = true;
  11624. }
  11625. }
  11626. if ($sidList !== []) {
  11627. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  11628. }
  11629. $searchKw = trim((string)$this->request->get('search', ''));
  11630. if ($searchKw === '') {
  11631. $searchKw = trim((string)$this->request->request('search', ''));
  11632. }
  11633. $filterRaw = $this->request->get('filter', '');
  11634. $filterArrTmp = [];
  11635. if (is_string($filterRaw) && $filterRaw !== '') {
  11636. $filterArrTmp = (array)json_decode($filterRaw, true);
  11637. } elseif (is_array($filterRaw)) {
  11638. $filterArrTmp = $filterRaw;
  11639. }
  11640. $hasSearch = ($searchKw !== '');
  11641. if (!$hasSearch) {
  11642. foreach ($filterArrTmp as $fv) {
  11643. if (trim((string)$fv) !== '') {
  11644. $hasSearch = true;
  11645. break;
  11646. }
  11647. }
  11648. }
  11649. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  11650. if (!is_array($dbRow)) {
  11651. return false;
  11652. }
  11653. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  11654. if ($done['ts'] <= 0) {
  11655. return false;
  11656. }
  11657. if ($hasSearch) {
  11658. return true;
  11659. }
  11660. return date('Y-m', $done['ts']) === $ym;
  11661. }));
  11662. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  11663. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  11664. $mainBySid = [];
  11665. foreach ($pool as $rw) {
  11666. if (!is_array($rw)) {
  11667. continue;
  11668. }
  11669. $rid = (int)($rw['ID'] ?? 0);
  11670. if ($rid > 0) {
  11671. $mainBySid[$rid] = $rw;
  11672. }
  11673. }
  11674. if ($mainBySid === []) {
  11675. $detailRows = [];
  11676. } else {
  11677. try {
  11678. $detailRows = Db::table('purchase_order_detail')
  11679. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11680. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11681. ->order('status', 'desc')
  11682. ->order('CCYDH', 'asc')
  11683. ->order('company_name', 'asc')
  11684. ->order('id', 'asc')
  11685. ->select();
  11686. } catch (\Throwable $e) {
  11687. try {
  11688. $detailRows = Db::table('purchase_order_detail')
  11689. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11690. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11691. ->order('status', 'desc')
  11692. ->order('CCYDH', 'asc')
  11693. ->order('company_name', 'asc')
  11694. ->order('ID', 'asc')
  11695. ->select();
  11696. } catch (\Throwable $e2) {
  11697. $detailRows = [];
  11698. }
  11699. }
  11700. }
  11701. if (!is_array($detailRows)) {
  11702. $detailRows = [];
  11703. }
  11704. $exportLines = [];
  11705. $detailSidSeen = [];
  11706. foreach ($detailRows as $dr) {
  11707. if (!is_array($dr)) {
  11708. continue;
  11709. }
  11710. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11711. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11712. continue;
  11713. }
  11714. if (isset($detailSidSeen[$sid])) {
  11715. continue;
  11716. }
  11717. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  11718. continue;
  11719. }
  11720. $detailSidSeen[$sid] = true;
  11721. $m = $mainBySid[$sid];
  11722. $exportLines[] = [
  11723. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11724. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11725. 'company_name' => (string)($dr['company_name'] ?? ''),
  11726. 'CDF' => (string)($m['CDF'] ?? ''),
  11727. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11728. 'gx' => $this->procuremenExportGxText($m),
  11729. 'detail' => $dr,
  11730. ];
  11731. }
  11732. foreach ($detailRows as $dr) {
  11733. if (!is_array($dr)) {
  11734. continue;
  11735. }
  11736. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11737. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  11738. continue;
  11739. }
  11740. $detailSidSeen[$sid] = true;
  11741. $m = $mainBySid[$sid];
  11742. $exportLines[] = [
  11743. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11744. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11745. 'company_name' => (string)($dr['company_name'] ?? ''),
  11746. 'CDF' => (string)($m['CDF'] ?? ''),
  11747. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11748. 'gx' => $this->procuremenExportGxText($m),
  11749. 'detail' => $dr,
  11750. ];
  11751. }
  11752. foreach ($mainBySid as $sid => $m) {
  11753. if (isset($detailSidSeen[$sid])) {
  11754. continue;
  11755. }
  11756. $company = trim((string)($m['pick_company_name'] ?? ''));
  11757. $exportLines[] = [
  11758. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  11759. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  11760. 'company_name' => $company,
  11761. 'CDF' => (string)($m['CDF'] ?? ''),
  11762. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11763. 'gx' => $this->procuremenExportGxText($m),
  11764. 'detail' => [],
  11765. ];
  11766. }
  11767. $groups = [];
  11768. foreach ($exportLines as $line) {
  11769. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  11770. if (!isset($groups[$k])) {
  11771. $groups[$k] = [];
  11772. }
  11773. $groups[$k][] = $line;
  11774. }
  11775. ksort($groups, SORT_STRING);
  11776. return [
  11777. 'ym' => $ym,
  11778. 'mainBySid' => $mainBySid,
  11779. 'detailRows' => $detailRows,
  11780. 'exportLines' => $exportLines,
  11781. 'groups' => $groups,
  11782. ];
  11783. }
  11784. /**
  11785. * 导出用:工序列文案
  11786. */
  11787. protected function procuremenExportGxText(array $r)
  11788. {
  11789. $a = trim((string)($r['CDXMC'] ?? ''));
  11790. $b = trim((string)($r['CGYMC'] ?? ''));
  11791. if ($a !== '' && $b !== '') {
  11792. return $a . ':' . $b;
  11793. }
  11794. return $a !== '' ? $a : $b;
  11795. }
  11796. /**
  11797. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  11798. */
  11799. protected function procuremenExportAmount(array $r)
  11800. {
  11801. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  11802. if (!array_key_exists($k, $r)) {
  11803. continue;
  11804. }
  11805. $v = $r[$k];
  11806. if ($v === null || $v === '') {
  11807. continue;
  11808. }
  11809. if (is_numeric($v)) {
  11810. return (float)$v;
  11811. }
  11812. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  11813. if ($v !== '' && is_numeric($v)) {
  11814. return (float)$v;
  11815. }
  11816. }
  11817. return 0.0;
  11818. }
  11819. /**
  11820. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  11821. *
  11822. * @param array<int, array<string, mixed>> $detailRows
  11823. * @param array<int, array<string, mixed>> $mainBySid
  11824. * @return array<int, array<string, mixed>>
  11825. */
  11826. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  11827. {
  11828. $lines = [];
  11829. foreach ($detailRows as $dr) {
  11830. if (!is_array($dr)) {
  11831. continue;
  11832. }
  11833. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11834. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11835. continue;
  11836. }
  11837. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  11838. continue;
  11839. }
  11840. $cn = trim((string)($dr['company_name'] ?? ''));
  11841. if ($cn === '') {
  11842. continue;
  11843. }
  11844. $m = $mainBySid[$sid];
  11845. $am = trim((string)($dr['amount'] ?? ''));
  11846. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  11847. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  11848. $amountText = $amountFilled
  11849. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  11850. : '未填写';
  11851. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  11852. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  11853. if ($deliveryShow === '' && $deliveryRaw !== '') {
  11854. $deliveryShow = $deliveryRaw;
  11855. }
  11856. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  11857. ? $deliveryShow
  11858. : '未填写';
  11859. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  11860. $lines[] = [
  11861. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11862. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11863. 'gx' => $this->procuremenExportGxText($m),
  11864. 'company_name' => $cn,
  11865. 'amount_text' => $amountText,
  11866. 'amount_num' => $amountFilled ? $amountNum : null,
  11867. 'delivery_text' => $deliveryText,
  11868. 'picked_text' => $picked ? '中标' : '未中标',
  11869. 'picked' => $picked,
  11870. ];
  11871. }
  11872. $winnerSupplierByOrder = [];
  11873. foreach ($lines as $line) {
  11874. $dh = trim((string)($line['CCYDH'] ?? ''));
  11875. $cn = trim((string)($line['company_name'] ?? ''));
  11876. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  11877. $winnerSupplierByOrder[$dh][$cn] = true;
  11878. }
  11879. }
  11880. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  11881. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  11882. if ($c !== 0) {
  11883. return $c;
  11884. }
  11885. $dh = trim((string)($a['CCYDH'] ?? ''));
  11886. $aCn = trim((string)($a['company_name'] ?? ''));
  11887. $bCn = trim((string)($b['company_name'] ?? ''));
  11888. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  11889. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  11890. if ($aSupplierWin !== $bSupplierWin) {
  11891. return $aSupplierWin ? -1 : 1;
  11892. }
  11893. $c = strcmp($aCn, $bCn);
  11894. if ($c !== 0) {
  11895. return $c;
  11896. }
  11897. if (!empty($a['picked']) !== !empty($b['picked'])) {
  11898. return !empty($a['picked']) ? -1 : 1;
  11899. }
  11900. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  11901. if ($c !== 0) {
  11902. return $c;
  11903. }
  11904. return 0;
  11905. });
  11906. return $lines;
  11907. }
  11908. /**
  11909. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  11910. *
  11911. * @param array<int, array<string, mixed>> $quoteLines
  11912. */
  11913. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  11914. {
  11915. $mon = (int)substr($ym, 5, 2);
  11916. $titleRow = $startRow;
  11917. $headerRow = $startRow + 1;
  11918. $dataStartRow = $startRow + 2;
  11919. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  11920. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  11921. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  11922. $sheet->getStyle('A' . $titleRow)->getAlignment()
  11923. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11924. ->setVertical(Alignment::VERTICAL_CENTER);
  11925. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  11926. $col = 'A';
  11927. foreach ($headers as $h) {
  11928. $sheet->setCellValue($col . $headerRow, $h);
  11929. $col++;
  11930. }
  11931. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  11932. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11933. $rowNum = $dataStartRow;
  11934. if ($quoteLines === []) {
  11935. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  11936. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  11937. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11938. $rowNum = $dataStartRow + 1;
  11939. } else {
  11940. $i = 0;
  11941. foreach ($quoteLines as $line) {
  11942. $i++;
  11943. $sheet->setCellValue('A' . $rowNum, $i);
  11944. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  11945. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  11946. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  11947. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  11948. if ($line['amount_num'] !== null) {
  11949. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  11950. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  11951. } else {
  11952. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  11953. }
  11954. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  11955. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  11956. if (!empty($line['picked'])) {
  11957. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11958. }
  11959. $rowNum++;
  11960. }
  11961. }
  11962. $lastRow = $rowNum - 1;
  11963. if ($lastRow >= $headerRow) {
  11964. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  11965. 'borders' => [
  11966. 'allBorders' => [
  11967. 'borderStyle' => Border::BORDER_THIN,
  11968. 'color' => ['rgb' => '000000'],
  11969. ],
  11970. ],
  11971. ]);
  11972. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11973. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11974. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11975. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11976. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  11977. if ($lastRow >= $dataStartRow) {
  11978. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  11979. }
  11980. }
  11981. return $lastRow;
  11982. }
  11983. /**
  11984. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  11985. */
  11986. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  11987. {
  11988. if ($lastRow < $dataStartRow || $headerRow < 1) {
  11989. return;
  11990. }
  11991. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  11992. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11993. ->setVertical(Alignment::VERTICAL_CENTER);
  11994. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  11995. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11996. ->setVertical(Alignment::VERTICAL_CENTER);
  11997. if ($lastCol > 'B') {
  11998. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  11999. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12000. ->setVertical(Alignment::VERTICAL_CENTER);
  12001. }
  12002. }
  12003. /**
  12004. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  12005. */
  12006. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  12007. {
  12008. $s = trim($ccydh);
  12009. if ($s === '') {
  12010. return 'ORDER';
  12011. }
  12012. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12013. $s = trim($s, '._-');
  12014. if ($s === '') {
  12015. return 'ORDER';
  12016. }
  12017. if (function_exists('mb_substr')) {
  12018. return mb_substr($s, 0, 80, 'UTF-8');
  12019. }
  12020. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12021. }
  12022. /**
  12023. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12024. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12025. *
  12026. * @return array{objectKey: string, webPath: string}
  12027. */
  12028. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12029. {
  12030. $sid = (int)$scydgyId;
  12031. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12032. $y = date('Y');
  12033. $m = date('m');
  12034. $d = date('d');
  12035. $basename = $safeOrder . '_' . $sid . '.pdf';
  12036. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12037. return [
  12038. 'objectKey' => $objectKey,
  12039. 'webPath' => '/' . $objectKey,
  12040. ];
  12041. }
  12042. /**
  12043. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12044. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12045. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12046. *
  12047. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12048. */
  12049. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12050. {
  12051. if (!$this->isValidScydgyRowId($scydgyId)) {
  12052. return '';
  12053. }
  12054. $ids = trim((string)$scydgyId);
  12055. $prep = $this->prepareProcuremenDetailsView($ids);
  12056. if (!$prep['ok']) {
  12057. return '';
  12058. }
  12059. $ccydh = $prep['ccydh'];
  12060. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12061. $objectKey = $paths['objectKey'];
  12062. $webPath = $paths['webPath'];
  12063. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  12064. $this->view->assign([
  12065. 'pdf_export' => 1,
  12066. 'pdfMetaLine' => $meta,
  12067. ]);
  12068. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12069. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12070. $this->view->engine->layout(false);
  12071. try {
  12072. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12073. } catch (\Throwable $e) {
  12074. if ($restoreLayout) {
  12075. $this->view->engine->layout($restoreLayout);
  12076. }
  12077. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12078. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12079. return '';
  12080. }
  12081. if ($restoreLayout) {
  12082. $this->view->engine->layout($restoreLayout);
  12083. }
  12084. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12085. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12086. if (!is_dir($tempDir)) {
  12087. @mkdir($tempDir, 0755, true);
  12088. }
  12089. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12090. try {
  12091. $mpdf = new \Mpdf\Mpdf([
  12092. 'mode' => 'utf-8',
  12093. 'format' => 'A4',
  12094. 'margin_left' => 12,
  12095. 'margin_right' => 12,
  12096. 'margin_top' => 14,
  12097. 'margin_bottom' => 14,
  12098. 'tempDir' => $tempDir,
  12099. 'autoScriptToLang' => true,
  12100. 'autoLangToFont' => true,
  12101. ]);
  12102. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12103. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12104. $mpdf->SetBasePath('http://127.0.0.1/');
  12105. $mpdf->WriteHTML($html);
  12106. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12107. } catch (\Throwable $e) {
  12108. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12109. if (is_file($tempPdf)) {
  12110. @unlink($tempPdf);
  12111. }
  12112. return '';
  12113. }
  12114. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12115. if ($ossUrl !== '') {
  12116. @unlink($tempPdf);
  12117. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12118. return $ossUrl;
  12119. }
  12120. $pi = pathinfo($objectKey);
  12121. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12122. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12123. if ($baseFile === '') {
  12124. @unlink($tempPdf);
  12125. return '';
  12126. }
  12127. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12128. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12129. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12130. @unlink($tempPdf);
  12131. return '';
  12132. }
  12133. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12134. if (!@copy($tempPdf, $fullPath)) {
  12135. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12136. @unlink($tempPdf);
  12137. return '';
  12138. }
  12139. @unlink($tempPdf);
  12140. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12141. return $webPath;
  12142. }
  12143. /**
  12144. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12145. */
  12146. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12147. {
  12148. if ($scydgyId <= 0 || $webPath === '') {
  12149. return;
  12150. }
  12151. try {
  12152. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12153. } catch (\Throwable $e) {
  12154. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12155. }
  12156. }
  12157. /**
  12158. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12159. *
  12160. * @param array<string, string> $vars
  12161. * @return array<string, string>
  12162. */
  12163. protected function normalizeSmsTemplateVars(array $vars): array
  12164. {
  12165. $out = [];
  12166. foreach ($vars as $k => $v) {
  12167. $out[(string)$k] = trim((string)$v);
  12168. }
  12169. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12170. $out['contact_name'] = $out['company_name'];
  12171. }
  12172. return $out;
  12173. }
  12174. /**
  12175. * 按手机号或公司名称查 customer 表联系人姓名
  12176. */
  12177. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12178. {
  12179. $phone = trim($phone);
  12180. $companyName = trim($companyName);
  12181. try {
  12182. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12183. $row = Db::table('customer')
  12184. ->where(function ($q) use ($phone) {
  12185. $q->where('phone', $phone)->whereOr('account', $phone);
  12186. })
  12187. ->order('id', 'asc')
  12188. ->find();
  12189. if (is_array($row)) {
  12190. $nm = trim((string)($row['username'] ?? ''));
  12191. if ($nm !== '') {
  12192. return $nm;
  12193. }
  12194. }
  12195. }
  12196. if ($companyName !== '') {
  12197. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12198. if (is_array($row)) {
  12199. return trim((string)($row['username'] ?? ''));
  12200. }
  12201. }
  12202. } catch (\Throwable $e) {
  12203. }
  12204. return '';
  12205. }
  12206. /**
  12207. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  12208. */
  12209. protected function plainTextToHtmlEmailBody(string $text): string
  12210. {
  12211. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12212. $parts = explode("\n", $text);
  12213. $out = [];
  12214. foreach ($parts as $line) {
  12215. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12216. $out[] = $line;
  12217. } else {
  12218. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12219. }
  12220. }
  12221. return implode("<br>\n", $out);
  12222. }
  12223. /**
  12224. * 短信场景:去掉链接类变量,避免误填 URL
  12225. *
  12226. * @param array<string, string> $vars
  12227. * @return array<string, string>
  12228. */
  12229. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12230. {
  12231. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12232. return $vars;
  12233. }
  12234. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12235. $vars[$k] = '';
  12236. }
  12237. return $vars;
  12238. }
  12239. /**
  12240. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12241. *
  12242. * @param array<string, string> $vars
  12243. */
  12244. protected function renderNotifyTemplate(string $scene, array $vars): string
  12245. {
  12246. $vars = $this->normalizeSmsTemplateVars($vars);
  12247. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12248. $row = $this->loadNotifyTemplateRow($scene);
  12249. if ($row === null) {
  12250. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12251. }
  12252. $tpl = trim((string)($row['content'] ?? ''));
  12253. if ($tpl === '') {
  12254. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12255. }
  12256. foreach ($vars as $k => $v) {
  12257. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12258. }
  12259. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12260. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12261. return $tpl;
  12262. }
  12263. protected function resolveProcuremenEmailSubject(string $scene): string
  12264. {
  12265. // 询价通知业务员:模版名称即邮件主题(可含 {ccydh})
  12266. if ($scene === 'rfq_salesman_email') {
  12267. $row = $this->loadNotifyTemplateRow($scene);
  12268. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12269. if ($title !== '') {
  12270. return $title;
  12271. }
  12272. return '协助采购询价通知';
  12273. }
  12274. $map = [
  12275. 'review_email' => '您有新的协助加工订单',
  12276. ];
  12277. $subject = trim((string)($map[$scene] ?? ''));
  12278. if ($subject === '') {
  12279. $this->error('未配置邮件主题:' . $scene);
  12280. }
  12281. return $subject;
  12282. }
  12283. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12284. {
  12285. $map = [
  12286. 'review_email' => '协助下发-邮箱',
  12287. 'review_sms' => '协助下发-短信',
  12288. 'confirm_ok' => '采购确认-通过',
  12289. 'confirm_fail' => '采购确认-未通过',
  12290. 'bid_open' => '开标双重验证',
  12291. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12292. ];
  12293. $label = $map[$scene] ?? $scene;
  12294. if ($titleRequired) {
  12295. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12296. }
  12297. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12298. }
  12299. /**
  12300. * 是否开启协助通知演练(不发真实短信/邮件)
  12301. */
  12302. protected function isProcuremenNotifyDryRun(): bool
  12303. {
  12304. return (bool)Config::get('procuremen_notify_dry_run');
  12305. }
  12306. /**
  12307. * @param array<string, mixed> $payload
  12308. */
  12309. protected function recordNotifyDryRunPreview(array $payload): void
  12310. {
  12311. $this->notifyDryRunPreview[] = $payload;
  12312. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  12313. }
  12314. /**
  12315. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  12316. * @throws \Exception
  12317. */
  12318. protected function smsbao($phone, $content)
  12319. {
  12320. if ($this->isProcuremenNotifyDryRun()) {
  12321. $this->recordNotifyDryRunPreview([
  12322. 'scene' => 'sms_only',
  12323. 'phone' => $phone,
  12324. 'sms_content' => $content,
  12325. ]);
  12326. return;
  12327. }
  12328. $statusStr = [
  12329. '0' => '短信发送成功',
  12330. '-1' => '参数不全',
  12331. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  12332. '30' => '密码错误',
  12333. '40' => '账号不存在',
  12334. '41' => '余额不足',
  12335. '42' => '帐户已过期',
  12336. '43' => 'IP地址限制',
  12337. '50' => '内容含有敏感词',
  12338. ];
  12339. $smsapi = 'http://api.smsbao.com/';
  12340. $user = 'zhuwei123';
  12341. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  12342. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  12343. $result = @file_get_contents($sendurl);
  12344. if ($result === false) {
  12345. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  12346. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  12347. }
  12348. $result = trim((string)$result);
  12349. if ($result !== '0') {
  12350. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  12351. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  12352. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  12353. }
  12354. }
  12355. }