Procuremen.php 500 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenSchema;
  8. use app\common\library\ProcuremenStatus;
  9. use app\common\library\ProcuremenSupplierScore;
  10. use app\common\library\ProcuremenTime;
  11. use PHPMailer\PHPMailer\PHPMailer;
  12. use think\Config;
  13. use think\Cache;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  16. use PhpOffice\PhpSpreadsheet\Style\Border;
  17. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  19. use think\Db;
  20. use think\Log;
  21. class Procuremen extends Backend
  22. {
  23. /**
  24. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  25. */
  26. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  27. /**
  28. * Procuremen模型对象
  29. * @var \app\admin\model\Procuremen
  30. */
  31. protected $model = null;
  32. /**
  33. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  34. */
  35. protected $notifyDryRunPreview = [];
  36. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  37. protected $procuremenRedisCache = null;
  38. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  39. protected $pickHiddenScydgySetCache = null;
  40. /** 邮件发送日志表结构已就绪缓存键 */
  41. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  42. /**
  43. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  44. * @var array
  45. */
  46. protected $noNeedRight = [
  47. 'pickreview', 'review', 'reviewcompanies',
  48. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  49. 'auditmanualpick',
  50. // 与 rfqlist 同权,方法内校验
  51. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  52. 'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  53. ];
  54. public function _initialize()
  55. {
  56. parent::_initialize();
  57. $this->model = new \app\admin\model\Procuremen;
  58. $this->maybeMigrateLegacyWflowStatusText();
  59. $this->assignProcuremenAuthConfig();
  60. try {
  61. ProcuremenSchema::ensureAll();
  62. } catch (\Throwable $e) {
  63. }
  64. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  65. $this->ensurePurchaseEmailSendLogTableOnce();
  66. }
  67. }
  68. /**
  69. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  70. */
  71. protected function maybeMigrateLegacyWflowStatusText(): void
  72. {
  73. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  74. if (is_file($flagFile)) {
  75. return;
  76. }
  77. $map = [
  78. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  79. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  80. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  81. '3' => ProcuremenStatus::WFLOW_APPROVED,
  82. ];
  83. try {
  84. foreach ($map as $num => $text) {
  85. Db::table('purchase_order')
  86. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  87. ->update(['wflow_status' => $text]);
  88. }
  89. @file_put_contents($flagFile, date('c'));
  90. } catch (\Throwable $e) {
  91. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  92. }
  93. }
  94. /**
  95. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  96. *
  97. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  98. */
  99. protected function hasProcuremenPerm(array $actions): bool
  100. {
  101. foreach ($actions as $action) {
  102. $action = strtolower(trim((string)$action));
  103. if ($action === '') {
  104. continue;
  105. }
  106. if (strpos($action, 'procuremen/') !== 0) {
  107. $action = 'procuremen/' . $action;
  108. }
  109. if ($this->auth->check($action)) {
  110. return true;
  111. }
  112. }
  113. $suffixes = [];
  114. foreach ($actions as $action) {
  115. $action = strtolower(trim((string)$action));
  116. $action = preg_replace('#^procuremen/#', '', $action);
  117. if ($action !== '') {
  118. $suffixes[$action] = true;
  119. }
  120. }
  121. if ($suffixes === []) {
  122. return false;
  123. }
  124. try {
  125. foreach ($this->auth->getRuleList() as $rule) {
  126. $rule = strtolower((string)$rule);
  127. if (strpos($rule, 'procuremen/') !== 0) {
  128. continue;
  129. }
  130. foreach (array_keys($suffixes) as $suffix) {
  131. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  132. return true;
  133. }
  134. }
  135. }
  136. } catch (\Throwable $e) {
  137. }
  138. return false;
  139. }
  140. /**
  141. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  142. *
  143. * @param string[] $actions
  144. */
  145. protected function hasProcuremenPermStrict(array $actions): bool
  146. {
  147. foreach ($actions as $action) {
  148. $action = strtolower(trim((string)$action));
  149. if ($action === '') {
  150. continue;
  151. }
  152. if (strpos($action, 'procuremen/') !== 0) {
  153. $action = 'procuremen/' . $action;
  154. }
  155. if ($this->auth->check($action)) {
  156. return true;
  157. }
  158. }
  159. return false;
  160. }
  161. /**
  162. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  163. *
  164. * @param string[] $titles
  165. */
  166. protected function authHasAssignedRuleTitle(array $titles): bool
  167. {
  168. $titles = array_values(array_filter(array_map('trim', $titles)));
  169. if ($titles === []) {
  170. return false;
  171. }
  172. try {
  173. $ids = $this->auth->getRuleIds();
  174. if (in_array('*', $ids, true)) {
  175. return true;
  176. }
  177. if ($ids === []) {
  178. return false;
  179. }
  180. $rows = Db::name('auth_rule')
  181. ->where('status', 'normal')
  182. ->whereIn('id', $ids)
  183. ->column('title');
  184. foreach ($rows as $title) {
  185. $t = trim((string)$title);
  186. if ($t !== '' && in_array($t, $titles, true)) {
  187. return true;
  188. }
  189. }
  190. } catch (\Throwable $e) {
  191. }
  192. return false;
  193. }
  194. protected function procuremenCanPickDelete(): bool
  195. {
  196. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  197. return true;
  198. }
  199. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  200. }
  201. protected function procuremenCanComplete(): bool
  202. {
  203. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  204. return true;
  205. }
  206. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  207. }
  208. protected function procuremenCanDispatch(): bool
  209. {
  210. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  211. }
  212. /**
  213. * 前端按钮显隐(Config.procuremenAuth)
  214. */
  215. protected function assignProcuremenAuthConfig(): void
  216. {
  217. $authMap = [
  218. 'pickreview' => $this->procuremenCanDispatch(),
  219. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  220. 'pickdelete' => $this->procuremenCanPickDelete(),
  221. 'completedirectly' => $this->procuremenCanComplete(),
  222. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  223. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  224. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  225. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  226. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  227. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  228. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  229. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  230. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  231. 'details' => $this->hasProcuremenPerm(['details']),
  232. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  233. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  234. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  235. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  236. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  237. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  238. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  239. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  240. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  241. 'add' => $this->hasProcuremenPerm(['add']),
  242. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  243. // 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
  244. 'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
  245. 'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
  246. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
  247. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
  248. // 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
  249. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
  250. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
  251. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
  252. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  253. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  254. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
  255. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  256. ];
  257. $this->assignconfig('procuremenAuth', $authMap);
  258. }
  259. /**
  260. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  261. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  262. *
  263. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  264. */
  265. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  266. {
  267. static $mprocCfgLoaded = false;
  268. if (!$mprocCfgLoaded) {
  269. $mprocCfgLoaded = true;
  270. if (is_file(APP_PATH . 'extra/mproc.php')) {
  271. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  272. }
  273. }
  274. $eid = (int)$purchaseOrderDetailId;
  275. $base = $this->resolveMprocMobilePublicBaseUrl();
  276. if ($base === '') {
  277. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  278. }
  279. $path = trim((string)Config::get('mproc.mobile_index_path'));
  280. if ($path === '') {
  281. $path = '/index.php/index/index/index';
  282. } else {
  283. $path = '/' . ltrim($path, '/');
  284. }
  285. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  286. if ($eid > 0) {
  287. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  288. }
  289. return $base . $path . '?main_tab=orders';
  290. }
  291. /**
  292. * 邮件/短信外链:须为带点的公网域名
  293. */
  294. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  295. {
  296. $u = trim((string)$baseUrl);
  297. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  298. return false;
  299. }
  300. $host = parse_url($u, PHP_URL_HOST);
  301. if (!is_string($host) || $host === '') {
  302. return false;
  303. }
  304. if (strcasecmp($host, 'localhost') === 0) {
  305. return false;
  306. }
  307. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  308. return false;
  309. }
  310. if (strpos($host, '.') === false) {
  311. return false;
  312. }
  313. return true;
  314. }
  315. /**
  316. * 解析用于协助邮件/短信的手机端站点根
  317. */
  318. protected function resolveMprocMobilePublicBaseUrl()
  319. {
  320. $candidates = [];
  321. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  322. $candidates[] = trim((string)Config::get('site.indexurl'));
  323. $cdn = trim((string)Config::get('site.cdnurl'));
  324. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  325. $candidates[] = rtrim($cdn, '/');
  326. }
  327. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  328. $candidates[] = $reqBase;
  329. foreach ($candidates as $c) {
  330. if ($c === '') {
  331. continue;
  332. }
  333. $c = rtrim($c, '/');
  334. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  335. return $c;
  336. }
  337. }
  338. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  339. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  340. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  341. return $reqBase;
  342. }
  343. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  344. return '';
  345. }
  346. /**
  347. * 获取 Redis 中 procuremen_redis
  348. */
  349. protected function ProcuremenRedis(): array
  350. {
  351. if ($this->procuremenRedisCache !== null) {
  352. return $this->procuremenRedisCache;
  353. }
  354. try {
  355. $redis = redis();
  356. $raw = $redis->get('procuremen_redis');
  357. if ($raw === false || $raw === '') {
  358. $this->procuremenRedisCache = [];
  359. return $this->procuremenRedisCache;
  360. }
  361. $decoded = json_decode($raw, true);
  362. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  363. $this->procuremenRedisCache = [];
  364. return $this->procuremenRedisCache;
  365. }
  366. $this->procuremenRedisCache = $decoded['data'];
  367. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  368. if ($this->loadProcuremenSidebarYmList() === []) {
  369. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  370. }
  371. return $this->procuremenRedisCache;
  372. } catch (\Throwable $e) {
  373. $this->procuremenRedisCache = [];
  374. return $this->procuremenRedisCache;
  375. }
  376. }
  377. /**
  378. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  379. *
  380. * @return array<int, array<string, mixed>>
  381. */
  382. protected function procuremenFetchErpPoolFromDb(): array
  383. {
  384. try {
  385. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  386. $endTime = date('Y-m-d 23:59:59');
  387. $list = Db::table('scydgy')
  388. ->alias('a')
  389. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  390. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  391. ->where([
  392. 'a.bwjg' => 1,
  393. 'a.iEndBz' => 0,
  394. 'a.iType' => 0,
  395. 'a.iStatus' => 10,
  396. ])
  397. ->where('a.dStamp', '>=', $startTime)
  398. ->where('a.dStamp', '<=', $endTime)
  399. ->order('a.dStamp', 'desc')
  400. ->select();
  401. if (!is_array($list)) {
  402. return [];
  403. }
  404. try {
  405. $redis = redis();
  406. $payload = [
  407. 'code' => 200,
  408. 'msg' => 'success',
  409. 'data' => $list,
  410. ];
  411. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  412. $this->procuremenRedisCache = $list;
  413. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  414. $this->clearPickMonthPoolCaches();
  415. $this->warmPickMonthPoolCachesFromPool($list);
  416. } catch (\Throwable $e) {
  417. }
  418. return $list;
  419. } catch (\Throwable $e) {
  420. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  421. return [];
  422. }
  423. }
  424. /**
  425. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  426. *
  427. * @return array<int, array<string, mixed>>
  428. */
  429. protected function procuremenEnsureRedisPool(): array
  430. {
  431. $pool = $this->ProcuremenRedis();
  432. if (is_array($pool) && $pool !== []) {
  433. return $pool;
  434. }
  435. static $warmed = false;
  436. if ($warmed) {
  437. return is_array($pool) ? $pool : [];
  438. }
  439. $warmed = true;
  440. return $this->procuremenFetchErpPoolFromDb();
  441. }
  442. /**
  443. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  444. *
  445. * @param array<string, mixed> $row
  446. */
  447. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  448. {
  449. $t = $this->procuremenRowListSortTime($row, $primary);
  450. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  451. return null;
  452. }
  453. $mo = (int)$m[2];
  454. if ($mo < 1 || $mo > 12) {
  455. return null;
  456. }
  457. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  458. }
  459. /**
  460. * @param array<int, array{year:string, months:array}> $sidebar
  461. * @return array<int, array{year:string, months:array}>
  462. */
  463. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  464. {
  465. $ym = trim($ym);
  466. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  467. return $sidebar;
  468. }
  469. foreach ($sidebar as $block) {
  470. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  471. continue;
  472. }
  473. foreach ($block['months'] as $item) {
  474. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  475. return $sidebar;
  476. }
  477. }
  478. }
  479. $y = substr($ym, 0, 4);
  480. $mo = (int)substr($ym, 5, 2);
  481. $sidebar[] = [
  482. 'year' => $y,
  483. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  484. ];
  485. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  486. }
  487. /**
  488. * @param array<int, array{year:string, months:array}> $sidebar
  489. * @return string[]
  490. */
  491. protected function flattenProcuremenSidebarYms(array $sidebar): array
  492. {
  493. $yms = [];
  494. foreach ($sidebar as $block) {
  495. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  496. continue;
  497. }
  498. foreach ($block['months'] as $item) {
  499. if (!is_array($item)) {
  500. continue;
  501. }
  502. $ym = trim((string)($item['ym'] ?? ''));
  503. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  504. $yms[$ym] = true;
  505. }
  506. }
  507. }
  508. return array_keys($yms);
  509. }
  510. /**
  511. * 左侧菜单(协助初选)
  512. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  513. */
  514. protected function GetIndexYearMonths()
  515. {
  516. $ymList = $this->ensureProcuremenPickSidebarYmList();
  517. if ($ymList === []) {
  518. $def = date('Y-m');
  519. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  520. }
  521. return $this->buildYearMonthSidebar($ymList);
  522. }
  523. /**
  524. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  525. *
  526. * @return string[]
  527. */
  528. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  529. {
  530. static $memo = null;
  531. if (!$forceRefresh && is_array($memo)) {
  532. return $memo;
  533. }
  534. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  535. if ($fromDb !== []) {
  536. $this->saveProcuremenSidebarYmList($fromDb);
  537. $memo = $fromDb;
  538. return $memo;
  539. }
  540. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  541. $cached = $this->loadProcuremenSidebarYmList();
  542. if ($cached !== []) {
  543. $memo = $cached;
  544. return $memo;
  545. }
  546. $memo = [date('Y-m')];
  547. return $memo;
  548. }
  549. /**
  550. * @return string[] 形如 2026-07
  551. */
  552. protected function loadProcuremenSidebarYmList(): array
  553. {
  554. try {
  555. $raw = redis()->get('procuremen_redis_yms');
  556. if ($raw === false || $raw === null || $raw === '') {
  557. return [];
  558. }
  559. $decoded = json_decode((string)$raw, true);
  560. if (!is_array($decoded)) {
  561. return [];
  562. }
  563. $out = [];
  564. foreach ($decoded as $ym) {
  565. $ym = trim((string)$ym);
  566. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  567. $out[$ym] = true;
  568. }
  569. }
  570. return array_keys($out);
  571. } catch (\Throwable $e) {
  572. return [];
  573. }
  574. }
  575. /**
  576. * @param string[] $ymList
  577. */
  578. protected function saveProcuremenSidebarYmList(array $ymList): void
  579. {
  580. $out = [];
  581. foreach ($ymList as $ym) {
  582. $ym = trim((string)$ym);
  583. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  584. $out[$ym] = true;
  585. }
  586. }
  587. if ($out === []) {
  588. return;
  589. }
  590. try {
  591. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  592. } catch (\Throwable $e) {
  593. }
  594. }
  595. /**
  596. * @param array<int, array<string, mixed>> $pool
  597. * @return string[]
  598. */
  599. protected function extractYearMonthsFromPoolRows(array $pool): array
  600. {
  601. $ymSet = [];
  602. foreach ($pool as $r) {
  603. if (!is_array($r)) {
  604. continue;
  605. }
  606. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  607. continue;
  608. }
  609. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  610. if ($ym !== null) {
  611. $ymSet[$ym] = true;
  612. }
  613. }
  614. return array_keys($ymSet);
  615. }
  616. /**
  617. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  618. *
  619. * @return string[]
  620. */
  621. protected function queryProcuremenPickSidebarYmListLight(): array
  622. {
  623. try {
  624. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  625. $endTime = date('Y-m-d 23:59:59');
  626. $sql = 'SELECT DISTINCT DATE_FORMAT('
  627. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  628. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  629. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  630. . ' FROM scydgy a'
  631. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  632. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  633. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  634. $rows = Db::query($sql, [$startTime, $endTime]);
  635. if (!is_array($rows)) {
  636. return [];
  637. }
  638. $out = [];
  639. foreach ($rows as $r) {
  640. $ym = trim((string)($r['ym'] ?? ''));
  641. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  642. $out[$ym] = true;
  643. }
  644. }
  645. return array_keys($out);
  646. } catch (\Throwable $e) {
  647. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  648. return [];
  649. }
  650. }
  651. /**
  652. * @return string[] 含当月在内的近 N 个自然月
  653. */
  654. protected function buildRecentCalendarYmList(int $months = 12): array
  655. {
  656. $months = max(1, min(24, $months));
  657. $out = [];
  658. $base = strtotime(date('Y-m-01'));
  659. for ($i = 0; $i < $months; $i++) {
  660. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  661. }
  662. return $out;
  663. }
  664. /**
  665. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  666. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  667. *
  668. * @return array<int, array<string, mixed>>
  669. */
  670. protected function loadPickPoolForYm(string $ym): array
  671. {
  672. $ym = trim($ym);
  673. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  674. return [];
  675. }
  676. $hit = $this->readPickMonthPoolCache($ym);
  677. if ($hit !== null) {
  678. return $hit;
  679. }
  680. return $this->queryPickPoolForYmFromDb($ym);
  681. }
  682. /**
  683. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  684. */
  685. protected function readPickMonthPoolCache(string $ym): ?array
  686. {
  687. try {
  688. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  689. if ($raw === false || $raw === null || $raw === '') {
  690. return null;
  691. }
  692. $decoded = json_decode((string)$raw, true);
  693. if (!is_array($decoded)) {
  694. return null;
  695. }
  696. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  697. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  698. return $decoded['rows'];
  699. }
  700. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  701. if ($decoded === []) {
  702. try {
  703. redis()->del('procuremen_pick_pool:' . $ym);
  704. } catch (\Throwable $e) {
  705. }
  706. return null;
  707. }
  708. if (isset($decoded[0]) && is_array($decoded[0])) {
  709. return $decoded;
  710. }
  711. return null;
  712. } catch (\Throwable $e) {
  713. return null;
  714. }
  715. }
  716. /**
  717. * @param array<int, array<string, mixed>> $rows
  718. */
  719. protected function writePickMonthPoolCache(string $ym, array $rows): void
  720. {
  721. try {
  722. redis()->setex(
  723. 'procuremen_pick_pool:' . $ym,
  724. 600,
  725. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  726. );
  727. } catch (\Throwable $e) {
  728. }
  729. }
  730. /**
  731. * @param array<int, array<string, mixed>> $pool
  732. * @return array<int, array<string, mixed>>
  733. */
  734. protected function filterPoolRowsByYm(array $pool, string $ym): array
  735. {
  736. $out = [];
  737. foreach ($pool as $r) {
  738. if (!is_array($r)) {
  739. continue;
  740. }
  741. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  742. continue;
  743. }
  744. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  745. $out[] = $r;
  746. }
  747. }
  748. return $out;
  749. }
  750. /**
  751. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  752. *
  753. * @return array<int, array<string, mixed>>
  754. */
  755. protected function queryPickPoolForYmFromDb(string $ym): array
  756. {
  757. $monthStart = $ym . '-01 00:00:00';
  758. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  759. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  760. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  761. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  762. try {
  763. $list = Db::table('scydgy')
  764. ->alias('a')
  765. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  766. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  767. ->where([
  768. 'a.bwjg' => 1,
  769. 'a.iEndBz' => 0,
  770. 'a.iType' => 0,
  771. 'a.iStatus' => 10,
  772. ])
  773. ->where('a.dStamp', '>=', $queryStart)
  774. ->where('a.dStamp', '<=', $queryEnd)
  775. ->order('a.dStamp', 'desc')
  776. ->select();
  777. } catch (\Throwable $e) {
  778. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  779. return [];
  780. }
  781. if (!is_array($list)) {
  782. $list = [];
  783. }
  784. $out = $this->filterPoolRowsByYm($list, $ym);
  785. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  786. $this->writePickMonthPoolCache($ym, $out);
  787. try {
  788. $yms = $this->loadProcuremenSidebarYmList();
  789. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  790. $yms[] = $ym;
  791. $this->saveProcuremenSidebarYmList($yms);
  792. }
  793. } catch (\Throwable $e) {
  794. }
  795. return $out;
  796. }
  797. /**
  798. * 整包写入后拆成按月小缓存,供初选列表秒开
  799. *
  800. * @param array<int, array<string, mixed>> $pool
  801. */
  802. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  803. {
  804. if ($pool === []) {
  805. return;
  806. }
  807. $byYm = [];
  808. foreach ($pool as $r) {
  809. if (!is_array($r)) {
  810. continue;
  811. }
  812. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  813. continue;
  814. }
  815. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  816. if ($rowYm === null) {
  817. continue;
  818. }
  819. $byYm[$rowYm][] = $r;
  820. }
  821. if ($byYm === []) {
  822. return;
  823. }
  824. try {
  825. $redis = redis();
  826. foreach ($byYm as $rowYm => $rows) {
  827. $redis->setex(
  828. 'procuremen_pick_pool:' . $rowYm,
  829. 600,
  830. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  831. );
  832. }
  833. try {
  834. $redis->del('procuremen_pick_hidden_scydgy_v1');
  835. } catch (\Throwable $e) {
  836. }
  837. } catch (\Throwable $e) {
  838. }
  839. }
  840. /**
  841. * 刷新整包后清理近月缓存,避免脏读
  842. */
  843. protected function clearPickMonthPoolCaches(int $months = 24): void
  844. {
  845. try {
  846. $redis = redis();
  847. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  848. try {
  849. $redis->del('procuremen_pick_pool:' . $ym);
  850. } catch (\Throwable $e) {
  851. }
  852. }
  853. } catch (\Throwable $e) {
  854. }
  855. $this->invalidatePickHiddenScydgyCache();
  856. }
  857. /**
  858. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  859. */
  860. protected function invalidatePickHiddenScydgyCache(): void
  861. {
  862. $this->pickHiddenScydgySetCache = null;
  863. try {
  864. redis()->del('procuremen_pick_hidden_scydgy_v1');
  865. } catch (\Throwable $e) {
  866. }
  867. }
  868. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  869. protected function procuremenReleaseSessionLock(): void
  870. {
  871. if (session_status() === PHP_SESSION_ACTIVE) {
  872. @session_write_close();
  873. }
  874. }
  875. /**
  876. * @param string[] $ymList 形如 2026-06
  877. * @return array<int, array{year:string, months:array}>
  878. */
  879. protected function buildYearMonthSidebar(array $ymList): array
  880. {
  881. rsort($ymList, SORT_STRING);
  882. $byYear = [];
  883. foreach ($ymList as $ym) {
  884. $y = substr($ym, 0, 4);
  885. $mo = (int)substr($ym, 5, 2);
  886. if (!isset($byYear[$y])) {
  887. $byYear[$y] = [];
  888. }
  889. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  890. }
  891. krsort($byYear, SORT_NUMERIC);
  892. foreach ($byYear as $y => $items) {
  893. usort($byYear[$y], function ($a, $b) {
  894. return strcmp($b['ym'], $a['ym']);
  895. });
  896. }
  897. $sidebar = [];
  898. foreach ($byYear as $y => $months) {
  899. $sidebar[] = ['year' => $y, 'months' => $months];
  900. }
  901. return $sidebar;
  902. }
  903. /**
  904. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  905. */
  906. protected function GetIssuedOrderYearMonths(string $stage): array
  907. {
  908. $ymSet = [];
  909. try {
  910. $query = Db::table('purchase_order');
  911. $this->applyPurchaseOrderNotDeletedWhere($query);
  912. if ($stage === 'audit') {
  913. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  914. } elseif ($stage === 'confirm') {
  915. $this->applyPurchaseOrderConfirmStageWhere($query);
  916. } else {
  917. return $this->GetIndexYearMonths();
  918. }
  919. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  920. if (is_array($rows)) {
  921. foreach ($rows as $r) {
  922. if (!is_array($r)) {
  923. continue;
  924. }
  925. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  926. if ($ym !== null) {
  927. $ymSet[$ym] = true;
  928. }
  929. }
  930. }
  931. } catch (\Throwable $e) {
  932. $ymSet = [];
  933. }
  934. $ymList = array_keys($ymSet);
  935. if ($ymList === []) {
  936. $def = $this->resolveProcuremenDefaultYm($stage);
  937. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  938. }
  939. return $this->buildYearMonthSidebar($ymList);
  940. }
  941. /**
  942. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  943. */
  944. protected function resolveProcuremenDefaultYm(string $stage): string
  945. {
  946. if ($stage === 'pick') {
  947. $yms = $this->ensureProcuremenPickSidebarYmList();
  948. if ($yms !== []) {
  949. rsort($yms, SORT_STRING);
  950. return $yms[0];
  951. }
  952. return date('Y-m');
  953. }
  954. try {
  955. $query = Db::table('purchase_order');
  956. $this->applyPurchaseOrderNotDeletedWhere($query);
  957. if ($stage === 'audit') {
  958. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  959. } elseif ($stage === 'confirm') {
  960. $this->applyPurchaseOrderConfirmStageWhere($query);
  961. } else {
  962. return date('Y-m');
  963. }
  964. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  965. if ($latest === null || $latest === '') {
  966. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  967. }
  968. $t = $this->formatProcuremenDetailTime($latest);
  969. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  970. return $m[1] . '-' . $m[2];
  971. }
  972. } catch (\Throwable $e) {
  973. }
  974. return date('Y-m');
  975. }
  976. protected function applyPurchaseOrderNotDeletedWhere($query): void
  977. {
  978. $query->whereRaw(
  979. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  980. );
  981. }
  982. /**
  983. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  984. */
  985. protected function applyPurchaseOrderConfirmStageWhere($query): void
  986. {
  987. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  988. $quoted = [];
  989. foreach ($vals as $v) {
  990. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  991. }
  992. if ($quoted === []) {
  993. $query->whereRaw('1 = 0');
  994. return;
  995. }
  996. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  997. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  998. }
  999. /**
  1000. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1001. *
  1002. * @param array<string, mixed> $row
  1003. * @return array<string, mixed>
  1004. */
  1005. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1006. {
  1007. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1008. $pick = trim((string)($row['pick_time'] ?? ''));
  1009. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1010. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1011. $t = trim((string)($row[$key] ?? ''));
  1012. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1013. $row['pick_time'] = $t;
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. return $row;
  1019. }
  1020. /**
  1021. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1022. */
  1023. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1024. {
  1025. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1026. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1027. }
  1028. if ($pool === []) {
  1029. $def = $this->resolveProcuremenDefaultYm($stage);
  1030. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1031. }
  1032. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1033. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1034. return false;
  1035. }
  1036. $monthStart = $ym . '-01 00:00:00';
  1037. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1038. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1039. return $probe !== [];
  1040. };
  1041. if ($tryYm($requestedYm)) {
  1042. return $requestedYm;
  1043. }
  1044. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1045. if ($tryYm($fallback)) {
  1046. return $fallback;
  1047. }
  1048. $bestYm = '';
  1049. $bestTime = '';
  1050. foreach ($pool as $row) {
  1051. if (!is_array($row)) {
  1052. continue;
  1053. }
  1054. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1055. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1056. continue;
  1057. }
  1058. $ymRow = $m[1];
  1059. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1060. $bestTime = $t;
  1061. $bestYm = $ymRow;
  1062. }
  1063. }
  1064. if ($bestYm !== '') {
  1065. return $bestYm;
  1066. }
  1067. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1068. }
  1069. protected function isPurchaseOrderDetailVoid(array $row): bool
  1070. {
  1071. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1072. return true;
  1073. }
  1074. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1075. }
  1076. /**
  1077. * 仅当前有效下发明细(排除废弃归档)
  1078. */
  1079. protected function applyActivePurchaseOrderDetailWhere($query): void
  1080. {
  1081. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1082. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1083. }
  1084. /**
  1085. * @param array<string, mixed> $detailRow
  1086. */
  1087. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1088. {
  1089. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1090. return false;
  1091. }
  1092. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1093. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1094. }
  1095. /**
  1096. * 废弃退回初选:下发明细标记归档,不物理删除
  1097. *
  1098. * @param array<int, int|string> $scydgyIds
  1099. */
  1100. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1101. {
  1102. $ids = [];
  1103. foreach ($scydgyIds as $sid) {
  1104. $n = (int)$sid;
  1105. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1106. $ids[$n] = true;
  1107. }
  1108. }
  1109. if ($ids === []) {
  1110. return;
  1111. }
  1112. $void = ProcuremenStatus::POD_VOID;
  1113. Db::table('purchase_order_detail')
  1114. ->where('scydgy_id', 'in', array_keys($ids))
  1115. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1116. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1117. ->update([
  1118. 'status' => $void,
  1119. 'status_name' => $void,
  1120. ]);
  1121. }
  1122. /**
  1123. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1124. */
  1125. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1126. {
  1127. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1128. $norm = function (string $col) use ($p): string {
  1129. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1130. };
  1131. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1132. $parts = [];
  1133. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1134. if ($key === 'createtime') {
  1135. $parts[] = $createtime;
  1136. } else {
  1137. $parts[] = $norm($key);
  1138. }
  1139. }
  1140. return 'COALESCE(' . implode(', ', $parts) . ')';
  1141. }
  1142. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1143. {
  1144. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1145. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1146. }
  1147. /**
  1148. * @return array<int, array<string, mixed>>
  1149. */
  1150. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1151. {
  1152. $this->ensurePurchaseOrderCzlyqColumn();
  1153. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1154. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1155. try {
  1156. $query = Db::table('purchase_order')->field($fields);
  1157. $this->applyPurchaseOrderNotDeletedWhere($query);
  1158. if ($stage === 'audit') {
  1159. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1160. } elseif ($stage === 'confirm') {
  1161. $this->applyPurchaseOrderConfirmStageWhere($query);
  1162. } else {
  1163. return [];
  1164. }
  1165. $query->order('pick_time', 'desc')->order('id', 'desc');
  1166. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1167. $monthStart = $ym . '-01 00:00:00';
  1168. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1169. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1170. }
  1171. $rows = $query->select();
  1172. } catch (\Throwable $e) {
  1173. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1174. $rows = [];
  1175. }
  1176. return is_array($rows) ? $rows : [];
  1177. }
  1178. /**
  1179. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1180. */
  1181. protected function resolveProcuremenListStage(): string
  1182. {
  1183. $tab = trim((string)$this->request->request('wff_tab', ''));
  1184. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1185. return $tab;
  1186. }
  1187. $action = strtolower((string)$this->request->action());
  1188. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1189. return $action;
  1190. }
  1191. return 'pick';
  1192. }
  1193. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1194. {
  1195. $this->procuremenReleaseSessionLock();
  1196. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1197. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1198. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1199. $indexPhpRoot = $rootTrue . '/index.php';
  1200. }
  1201. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1202. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1203. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1204. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1205. $this->view->assign('defaultYm', $defaultYm);
  1206. $this->view->assign('sidebarYearMonths', $sidebar);
  1207. $this->view->assign('procuremenStage', $stage);
  1208. $this->view->assign('procuremenPageTitle', $pageTitle);
  1209. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1210. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1211. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1212. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1213. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1214. }
  1215. /**
  1216. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1217. *
  1218. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1219. */
  1220. protected function buildProcuremenFilterOptions(string $stage): array
  1221. {
  1222. $buckets = [
  1223. 'czlyq' => [],
  1224. 'CCLBMMC' => [],
  1225. 'cywyxm' => [],
  1226. 'CGYMC' => [],
  1227. ];
  1228. $maxPerField = 300;
  1229. try {
  1230. if ($stage === 'pick') {
  1231. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1232. return $buckets;
  1233. }
  1234. if (in_array($stage, ['audit', 'confirm'], true)) {
  1235. $this->ensurePurchaseOrderCzlyqColumn();
  1236. foreach (array_keys($buckets) as $field) {
  1237. try {
  1238. $query = Db::table('purchase_order')->field($field);
  1239. $this->applyPurchaseOrderNotDeletedWhere($query);
  1240. if ($stage === 'audit') {
  1241. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1242. } else {
  1243. $this->applyPurchaseOrderConfirmStageWhere($query);
  1244. }
  1245. $query->where($field, '<>', '')->whereNotNull($field);
  1246. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1247. if (!is_array($vals)) {
  1248. continue;
  1249. }
  1250. foreach ($vals as $v) {
  1251. $v = trim((string)$v);
  1252. if ($v !== '') {
  1253. $buckets[$field][$v] = $v;
  1254. }
  1255. }
  1256. } catch (\Throwable $e) {
  1257. // 单字段失败不影响其它
  1258. }
  1259. }
  1260. }
  1261. } catch (\Throwable $e) {
  1262. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1263. }
  1264. foreach ($buckets as &$set) {
  1265. if ($set !== []) {
  1266. ksort($set, SORT_STRING);
  1267. }
  1268. }
  1269. unset($set);
  1270. return $buckets;
  1271. }
  1272. /**
  1273. * filter JSON 是否含有效条件
  1274. *
  1275. * @param array<string, mixed> $filterArr
  1276. */
  1277. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1278. {
  1279. foreach ($filterArr as $v) {
  1280. if (is_array($v)) {
  1281. if (array_filter($v, function ($x) {
  1282. return $x !== '' && $x !== null;
  1283. })) {
  1284. return true;
  1285. }
  1286. } elseif ($v !== '' && $v !== null) {
  1287. return true;
  1288. }
  1289. }
  1290. return false;
  1291. }
  1292. /**
  1293. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1294. *
  1295. * @param array<string, mixed> $filterArr
  1296. * @param array<string, mixed> $opArr
  1297. */
  1298. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1299. {
  1300. if ($search !== '') {
  1301. return false;
  1302. }
  1303. foreach ($filterArr as $fk => $fv) {
  1304. if (is_array($fv)) {
  1305. continue;
  1306. }
  1307. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1308. continue;
  1309. }
  1310. if ($fv === null) {
  1311. continue;
  1312. }
  1313. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1314. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1315. if ($sym === '' || $sym === '=') {
  1316. continue;
  1317. }
  1318. return false;
  1319. }
  1320. return true;
  1321. }
  1322. /**
  1323. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1324. *
  1325. * @param array<int, mixed> $rows
  1326. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1327. */
  1328. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1329. {
  1330. $buckets = [
  1331. 'czlyq' => [],
  1332. 'CCLBMMC' => [],
  1333. 'cywyxm' => [],
  1334. 'CGYMC' => [],
  1335. ];
  1336. foreach ($rows as $r) {
  1337. if (!is_array($r)) {
  1338. continue;
  1339. }
  1340. foreach ($buckets as $field => &$set) {
  1341. if (count($set) >= $maxPerField) {
  1342. continue;
  1343. }
  1344. $v = trim((string)($r[$field] ?? ''));
  1345. if ($v !== '') {
  1346. $set[$v] = $v;
  1347. }
  1348. }
  1349. unset($set);
  1350. $full = true;
  1351. foreach ($buckets as $set) {
  1352. if (count($set) < $maxPerField) {
  1353. $full = false;
  1354. break;
  1355. }
  1356. }
  1357. if ($full) {
  1358. break;
  1359. }
  1360. }
  1361. foreach ($buckets as &$set) {
  1362. if ($set !== []) {
  1363. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1364. $normalized = [];
  1365. foreach ($set as $k => $v) {
  1366. $s = trim((string)(is_scalar($v) ? $v : $k));
  1367. if ($s === '') {
  1368. continue;
  1369. }
  1370. $normalized[$s] = $s;
  1371. }
  1372. ksort($normalized, SORT_STRING);
  1373. $set = $normalized;
  1374. }
  1375. }
  1376. unset($set);
  1377. return $buckets;
  1378. }
  1379. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1380. public function pick()
  1381. {
  1382. $this->request->filter(['strip_tags', 'trim']);
  1383. if (!$this->request->isAjax()) {
  1384. $this->assignProcuremenListPage('pick', '协助下发');
  1385. return $this->view->fetch('procuremen/index');
  1386. }
  1387. return $this->index();
  1388. }
  1389. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1390. public function audit()
  1391. {
  1392. $this->request->filter(['strip_tags', 'trim']);
  1393. if (!$this->request->isAjax()) {
  1394. $this->assignProcuremenListPage('audit', '确认供应商');
  1395. return $this->view->fetch('procuremen/index');
  1396. }
  1397. return $this->index();
  1398. }
  1399. /** 采购确认(定标) */
  1400. public function confirm()
  1401. {
  1402. $this->request->filter(['strip_tags', 'trim']);
  1403. if (!$this->request->isAjax()) {
  1404. $this->assignProcuremenListPage('confirm', '采购确认');
  1405. return $this->view->fetch('procuremen/index');
  1406. }
  1407. return $this->index();
  1408. }
  1409. /**
  1410. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1411. */
  1412. public function index()
  1413. {
  1414. $this->request->filter(['strip_tags', 'trim']);
  1415. if (!$this->request->isAjax()) {
  1416. $this->assignProcuremenListPage('pick', '协助下发');
  1417. return $this->view->fetch('procuremen/index');
  1418. }
  1419. if ($this->request->request('keyField')) {
  1420. return $this->selectpage();
  1421. }
  1422. $this->procuremenReleaseSessionLock();
  1423. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1424. $limit = max(10, min(500, (int)$limit));
  1425. $ym = $this->request->request('ym', '');
  1426. $ym = is_string($ym) ? trim($ym) : '';
  1427. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1428. $wffTab = $this->resolveProcuremenListStage();
  1429. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1430. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1431. ? $this->resolveProcuremenDefaultYm($wffTab)
  1432. : date('Y-m');
  1433. }
  1434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1435. $ym = date('Y-m');
  1436. }
  1437. $monthStart = $ym . '-01 00:00:00';
  1438. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1439. $search = trim((string)$this->request->get('search', ''));
  1440. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1441. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1442. if (!is_array($filterArr)) {
  1443. $filterArr = [];
  1444. }
  1445. if (!is_array($opArr)) {
  1446. $opArr = [];
  1447. }
  1448. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1449. $bidOpenStatusFilter = '';
  1450. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1451. if (!array_key_exists($bidFk, $filterArr)) {
  1452. continue;
  1453. }
  1454. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1455. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1456. }
  1457. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1458. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1459. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1460. try {
  1461. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1462. if ($wffTab === 'audit') {
  1463. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1464. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1465. );
  1466. } elseif ($wffTab === 'confirm') {
  1467. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1468. if ($dbRows === []) {
  1469. try {
  1470. $dbRows = Db::table('purchase_order')
  1471. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1472. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1473. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  1474. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1475. ->order('pick_time', 'desc')->order('id', 'desc')
  1476. ->select();
  1477. } catch (\Throwable $e) {
  1478. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1479. $dbRows = [];
  1480. }
  1481. }
  1482. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1483. if ($pool === []) {
  1484. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1485. }
  1486. } else {
  1487. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1488. if ($applyMonthRange) {
  1489. $pool = $this->loadPickPoolForYm($ym);
  1490. } else {
  1491. $pool = $this->procuremenEnsureRedisPool();
  1492. }
  1493. if (!is_array($pool)) {
  1494. $pool = [];
  1495. }
  1496. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1497. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1498. if ($pool !== [] && $hideSet !== []) {
  1499. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1500. if (!is_array($r)) {
  1501. return false;
  1502. }
  1503. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1504. return $id <= 0 || !isset($hideSet[$id]);
  1505. }));
  1506. }
  1507. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1508. if ($pool === []) {
  1509. return json([
  1510. 'total' => 0,
  1511. 'rows' => [],
  1512. 'activeYm' => $ym,
  1513. 'filterOptions' => (
  1514. (int)$offset === 0
  1515. && !$hasActiveSearch
  1516. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1517. )
  1518. ? $this->extractProcuremenFilterOptionsFromRows([])
  1519. : new \stdClass(),
  1520. ]);
  1521. }
  1522. }
  1523. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1524. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1525. $monthStart = $ym . '-01 00:00:00';
  1526. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1527. }
  1528. $filtered = $this->filterProcuremenIndexPool(
  1529. $pool,
  1530. $monthStart,
  1531. $monthEnd,
  1532. $applyMonthRange,
  1533. $search,
  1534. $filterArr,
  1535. $opArr,
  1536. $listTimePrimary
  1537. );
  1538. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1539. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1540. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1541. }
  1542. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1543. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1544. }
  1545. $sortField = 'ID';
  1546. if (is_string($sort) && $sort !== '') {
  1547. $parts = explode(',', $sort);
  1548. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1549. if ($sortField === '') {
  1550. $sortField = 'ID';
  1551. }
  1552. }
  1553. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1554. $nFiltered = count($filtered);
  1555. if ($nFiltered > 1) {
  1556. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1557. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1558. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1559. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1560. if ($ta === $tb) {
  1561. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1562. }
  1563. if ($ta === '') {
  1564. return 1;
  1565. }
  1566. if ($tb === '') {
  1567. return -1;
  1568. }
  1569. return strcmp($ta, $tb) * $ord;
  1570. });
  1571. } elseif ($sortField === 'ID') {
  1572. $sortKeys = [];
  1573. foreach ($filtered as $i => $row) {
  1574. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1575. }
  1576. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1577. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1578. } elseif ($sortField === 'CCYDH') {
  1579. usort($filtered, function ($a, $b) use ($ord) {
  1580. $sa = trim((string)($a['CCYDH'] ?? ''));
  1581. $sb = trim((string)($b['CCYDH'] ?? ''));
  1582. if ($sa === $sb) {
  1583. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1584. }
  1585. if ($sa === '') {
  1586. return 1;
  1587. }
  1588. if ($sb === '') {
  1589. return -1;
  1590. }
  1591. return strcmp($sa, $sb) * $ord;
  1592. });
  1593. } else {
  1594. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1595. $va = $a[$sortField] ?? null;
  1596. $vb = $b[$sortField] ?? null;
  1597. $sa = (string)$va;
  1598. $sb = (string)$vb;
  1599. if ($sa === $sb) {
  1600. return 0;
  1601. }
  1602. return strcmp($sa, $sb) * $ord;
  1603. });
  1604. }
  1605. }
  1606. $offset = max(0, (int)$offset);
  1607. $limit = max(1, (int)$limit);
  1608. $rows = array_slice($filtered, $offset, $limit);
  1609. foreach ($rows as &$rw) {
  1610. if (!is_array($rw)) {
  1611. continue;
  1612. }
  1613. $rid = (int)($rw['ID'] ?? 0);
  1614. $rw['_iss_out'] = ($wffTab !== 'pick');
  1615. }
  1616. unset($rw);
  1617. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1618. $idList = [];
  1619. foreach ($rows as $rw) {
  1620. if (!is_array($rw)) {
  1621. continue;
  1622. }
  1623. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1624. foreach ($rw['_order_merge_rows'] as $mr) {
  1625. $mid = (int)($mr['ID'] ?? 0);
  1626. if ($this->isValidScydgyRowId($mid)) {
  1627. $idList[$mid] = true;
  1628. }
  1629. }
  1630. }
  1631. $id = (int)($rw['ID'] ?? 0);
  1632. if ($this->isValidScydgyRowId($id)) {
  1633. $idList[$id] = true;
  1634. }
  1635. }
  1636. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1637. foreach ($rows as &$rw) {
  1638. if (!is_array($rw)) {
  1639. continue;
  1640. }
  1641. $mergeIds = [];
  1642. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1643. foreach ($rw['_order_merge_rows'] as $mr) {
  1644. $mid = (int)($mr['ID'] ?? 0);
  1645. if ($this->isValidScydgyRowId($mid)) {
  1646. $mergeIds[$mid] = true;
  1647. }
  1648. }
  1649. }
  1650. $rid = (int)($rw['ID'] ?? 0);
  1651. if ($this->isValidScydgyRowId($rid)) {
  1652. $mergeIds[$rid] = true;
  1653. }
  1654. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1655. $rw['po_detail_count'] = $s['cnt'];
  1656. $rw['po_amount_fill_cnt'] = $s['amt'];
  1657. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1658. }
  1659. unset($rw);
  1660. }
  1661. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1662. $idList = [];
  1663. foreach ($rows as $rw) {
  1664. if (!is_array($rw)) {
  1665. continue;
  1666. }
  1667. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1668. foreach ($rw['_order_merge_rows'] as $mr) {
  1669. $mid = (int)($mr['ID'] ?? 0);
  1670. if ($this->isValidScydgyRowId($mid)) {
  1671. $idList[$mid] = true;
  1672. }
  1673. }
  1674. }
  1675. $id = (int)($rw['ID'] ?? 0);
  1676. if ($this->isValidScydgyRowId($id)) {
  1677. $idList[$id] = true;
  1678. }
  1679. }
  1680. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1681. $bidOpenSet = [];
  1682. $manualPickSet = [];
  1683. if ($wffTab === 'audit') {
  1684. $ccydhList = [];
  1685. foreach ($rows as $rw0) {
  1686. if (!is_array($rw0)) {
  1687. continue;
  1688. }
  1689. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1690. if ($c0 !== '') {
  1691. $ccydhList[] = $c0;
  1692. }
  1693. }
  1694. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1695. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1696. }
  1697. foreach ($rows as &$rw) {
  1698. if (!is_array($rw)) {
  1699. continue;
  1700. }
  1701. $mergeIds = [];
  1702. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1703. foreach ($rw['_order_merge_rows'] as $mr) {
  1704. $mid = (int)($mr['ID'] ?? 0);
  1705. if ($this->isValidScydgyRowId($mid)) {
  1706. $mergeIds[$mid] = true;
  1707. }
  1708. }
  1709. }
  1710. $rid = (int)($rw['ID'] ?? 0);
  1711. if ($this->isValidScydgyRowId($rid)) {
  1712. $mergeIds[$rid] = true;
  1713. }
  1714. $buckets = [];
  1715. foreach (array_keys($mergeIds) as $mid) {
  1716. if (isset($quoteBucket[$mid])) {
  1717. $buckets[] = $quoteBucket[$mid];
  1718. }
  1719. }
  1720. $supplierText = $buckets !== []
  1721. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1722. : '';
  1723. if ($wffTab === 'confirm') {
  1724. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1725. if ($picked === '') {
  1726. // 兜底:从合并工序行取
  1727. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1728. foreach ($rw['_order_merge_rows'] as $mr) {
  1729. if (!is_array($mr)) {
  1730. continue;
  1731. }
  1732. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1733. if ($pn !== '') {
  1734. $picked = $pn;
  1735. break;
  1736. }
  1737. }
  1738. }
  1739. }
  1740. $rw['picked_supplier_name'] = $picked;
  1741. } else {
  1742. $rw['notify_supplier_text'] = $supplierText;
  1743. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1744. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1745. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1746. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1747. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1748. if ($verified) {
  1749. $rw['bid_open_status_text'] = '已开标';
  1750. } elseif ($manualPicked) {
  1751. $rw['bid_open_status_text'] = '已指定供应商';
  1752. } else {
  1753. $rw['bid_open_status_text'] = '待开标';
  1754. }
  1755. }
  1756. }
  1757. unset($rw);
  1758. }
  1759. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1760. $this->enrichProcuremenListMilestoneTimes($rows);
  1761. $this->syncCollapsedOrderQtyPriceForList($rows);
  1762. }
  1763. if ($wffTab === 'all' && count($rows) > 0) {
  1764. $this->mergePurchaseOrder($rows);
  1765. }
  1766. if ($wffTab === 'pick' && count($rows) > 0) {
  1767. $this->mergePurchaseOrder($rows);
  1768. }
  1769. foreach ($rows as &$rwClean) {
  1770. if (is_array($rwClean)) {
  1771. unset($rwClean['_order_merge_rows']);
  1772. if (array_key_exists('NGZL', $rwClean)) {
  1773. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1774. }
  1775. }
  1776. }
  1777. unset($rwClean);
  1778. return json([
  1779. 'total' => count($filtered),
  1780. 'rows' => $rows,
  1781. 'activeYm' => $ym,
  1782. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1783. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1784. ? $this->ensureProcuremenPickSidebarYmList()
  1785. : [],
  1786. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1787. 'filterOptions' => (
  1788. (int)$offset === 0
  1789. && !$hasActiveSearch
  1790. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1791. )
  1792. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1793. : new \stdClass(),
  1794. ]);
  1795. } catch (\Throwable $e) {
  1796. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1797. return json([
  1798. 'total' => 0,
  1799. 'rows' => [],
  1800. ]);
  1801. }
  1802. }
  1803. /**
  1804. * @param array<int, array<string, mixed>> $pool
  1805. * @return int[]
  1806. */
  1807. protected function extractScydgyIdsFromPool(array $pool): array
  1808. {
  1809. $ids = [];
  1810. foreach ($pool as $r) {
  1811. if (!is_array($r)) {
  1812. continue;
  1813. }
  1814. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1815. if ($id > 0) {
  1816. $ids[$id] = $id;
  1817. }
  1818. }
  1819. return array_values($ids);
  1820. }
  1821. /**
  1822. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1823. *
  1824. * @param int[] $scydgyIds
  1825. * @return array<int, true>
  1826. */
  1827. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1828. {
  1829. $hideSet = [];
  1830. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1831. return $id > 0;
  1832. }));
  1833. if ($scydgyIds === []) {
  1834. return $hideSet;
  1835. }
  1836. // 分批,避免 whereIn 过长
  1837. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1838. try {
  1839. $poIds = Db::table('purchase_order')
  1840. ->where('scydgy_id', 'in', $chunk)
  1841. ->where(function ($q) {
  1842. $q->whereIn('wflow_status', array_merge(
  1843. ProcuremenStatus::wflowPendingConfirmValues(),
  1844. ProcuremenStatus::wflowPendingApprovalValues()
  1845. ))
  1846. ->whereOr(function ($q1) {
  1847. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1848. })
  1849. ->whereOr(function ($q2) {
  1850. $q2->whereNotNull('pick_time')
  1851. ->where('pick_time', '<>', '')
  1852. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1853. })
  1854. ->whereOr(function ($q3) {
  1855. $q3->whereNotNull('mod_rq')
  1856. ->where('mod_rq', '<>', '')
  1857. ->where('mod_rq', 'not like', '0000-00-00%');
  1858. });
  1859. })
  1860. ->column('scydgy_id');
  1861. if (is_array($poIds)) {
  1862. foreach ($poIds as $pid) {
  1863. $k = (int)$pid;
  1864. if ($k !== 0) {
  1865. $hideSet[$k] = true;
  1866. }
  1867. }
  1868. }
  1869. } catch (\Throwable $e) {
  1870. }
  1871. try {
  1872. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1873. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1874. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1875. if (is_array($detIds)) {
  1876. foreach ($detIds as $pid) {
  1877. $k = (int)$pid;
  1878. if ($this->isValidScydgyRowId($k)) {
  1879. $hideSet[$k] = true;
  1880. }
  1881. }
  1882. }
  1883. } catch (\Throwable $e) {
  1884. }
  1885. }
  1886. return $hideSet;
  1887. }
  1888. /**
  1889. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1890. *
  1891. * @return array<int, true>
  1892. */
  1893. protected function loadPickHiddenScydgySet(): array
  1894. {
  1895. if ($this->pickHiddenScydgySetCache !== null) {
  1896. return $this->pickHiddenScydgySetCache;
  1897. }
  1898. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1899. try {
  1900. $raw = redis()->get($cacheKey);
  1901. if ($raw !== false && $raw !== null && $raw !== '') {
  1902. $ids = json_decode((string)$raw, true);
  1903. if (is_array($ids)) {
  1904. $hideSet = [];
  1905. foreach ($ids as $pid) {
  1906. $k = (int)$pid;
  1907. if ($k !== 0) {
  1908. $hideSet[$k] = true;
  1909. }
  1910. }
  1911. $this->pickHiddenScydgySetCache = $hideSet;
  1912. return $hideSet;
  1913. }
  1914. }
  1915. } catch (\Throwable $e) {
  1916. }
  1917. $hideSet = [];
  1918. try {
  1919. $poIds = Db::table('purchase_order')
  1920. ->where(function ($q) {
  1921. $q->whereIn('wflow_status', array_merge(
  1922. ProcuremenStatus::wflowPendingConfirmValues(),
  1923. ProcuremenStatus::wflowPendingApprovalValues()
  1924. ))
  1925. ->whereOr(function ($q1) {
  1926. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1927. })
  1928. ->whereOr(function ($q2) {
  1929. $q2->whereNotNull('pick_time')
  1930. ->where('pick_time', '<>', '')
  1931. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1932. })
  1933. ->whereOr(function ($q3) {
  1934. $q3->whereNotNull('mod_rq')
  1935. ->where('mod_rq', '<>', '')
  1936. ->where('mod_rq', 'not like', '0000-00-00%');
  1937. });
  1938. })
  1939. ->column('scydgy_id');
  1940. if (is_array($poIds)) {
  1941. foreach ($poIds as $pid) {
  1942. $k = (int)$pid;
  1943. if ($k !== 0) {
  1944. $hideSet[$k] = true;
  1945. }
  1946. }
  1947. }
  1948. } catch (\Throwable $e) {
  1949. }
  1950. try {
  1951. $detIdsQuery = Db::table('purchase_order_detail');
  1952. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1953. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1954. if (is_array($detIds)) {
  1955. foreach ($detIds as $pid) {
  1956. $k = (int)$pid;
  1957. if ($this->isValidScydgyRowId($k)) {
  1958. $hideSet[$k] = true;
  1959. }
  1960. }
  1961. }
  1962. } catch (\Throwable $e) {
  1963. }
  1964. $this->pickHiddenScydgySetCache = $hideSet;
  1965. try {
  1966. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  1967. } catch (\Throwable $e) {
  1968. }
  1969. return $hideSet;
  1970. }
  1971. /**
  1972. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1973. *
  1974. * @return array<int, array<string, mixed>>
  1975. */
  1976. protected function loadPickManualOrderRows(): array
  1977. {
  1978. try {
  1979. $dbRows = Db::table('purchase_order')
  1980. ->where('scydgy_id', '<', 0)
  1981. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  1982. ->order('scydgy_id', 'asc')
  1983. ->select();
  1984. } catch (\Throwable $e) {
  1985. try {
  1986. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1987. } catch (\Throwable $e2) {
  1988. return [];
  1989. }
  1990. }
  1991. if (!is_array($dbRows) || $dbRows === []) {
  1992. return [];
  1993. }
  1994. $detailSidSet = [];
  1995. try {
  1996. $negIds = [];
  1997. foreach ($dbRows as $dbRow) {
  1998. if (!is_array($dbRow)) {
  1999. continue;
  2000. }
  2001. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2002. if ($sid < 0) {
  2003. $negIds[$sid] = true;
  2004. }
  2005. }
  2006. if ($negIds !== []) {
  2007. $detQuery = Db::table('purchase_order_detail')
  2008. ->where('scydgy_id', 'in', array_keys($negIds));
  2009. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2010. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2011. if (is_array($detRows)) {
  2012. foreach ($detRows as $did) {
  2013. $detailSidSet[(int)$did] = true;
  2014. }
  2015. }
  2016. }
  2017. } catch (\Throwable $e) {
  2018. }
  2019. $pool = [];
  2020. foreach ($dbRows as $dbRow) {
  2021. if (!is_array($dbRow)) {
  2022. continue;
  2023. }
  2024. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2025. if ($sid >= 0) {
  2026. continue;
  2027. }
  2028. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2029. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2030. continue;
  2031. }
  2032. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2033. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2034. continue;
  2035. }
  2036. if (isset($detailSidSet[$sid])) {
  2037. continue;
  2038. }
  2039. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2040. $r['_is_manual'] = 1;
  2041. $pool[] = $r;
  2042. }
  2043. return $pool;
  2044. }
  2045. /**
  2046. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2047. */
  2048. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2049. {
  2050. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2051. foreach ($keys as $k) {
  2052. $t = trim((string)($row[$k] ?? ''));
  2053. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2054. return $t;
  2055. }
  2056. }
  2057. return '';
  2058. }
  2059. /**
  2060. * 分配手工新增工序行 ID(负数递减)
  2061. */
  2062. protected function allocateManualScydgyId(): int
  2063. {
  2064. try {
  2065. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2066. $min = (int)$min;
  2067. return $min < 0 ? $min - 1 : -1;
  2068. } catch (\Throwable $e) {
  2069. return -1;
  2070. }
  2071. }
  2072. /**
  2073. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  2074. */
  2075. protected function allocateManualOrderCcydh(): string
  2076. {
  2077. $prefix = 'YW' . date('Ymd');
  2078. $maxSeq = 0;
  2079. try {
  2080. $rows = Db::table('purchase_order')
  2081. ->where('CCYDH', 'like', $prefix . '%')
  2082. ->column('CCYDH');
  2083. if (is_array($rows)) {
  2084. foreach ($rows as $ccydh) {
  2085. $ccydh = trim((string)$ccydh);
  2086. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  2087. $maxSeq = max($maxSeq, (int)$m[1]);
  2088. }
  2089. }
  2090. }
  2091. } catch (\Throwable $e) {
  2092. }
  2093. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  2094. }
  2095. /**
  2096. * purchase_order.mod_rq 是否有有效软删除时间
  2097. */
  2098. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2099. {
  2100. $t = trim((string)$modRq);
  2101. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2102. }
  2103. /**
  2104. * 列表行 → purchase_order 写入字段
  2105. *
  2106. * @return array<string, mixed>
  2107. */
  2108. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2109. {
  2110. return [
  2111. 'scydgy_id' => $scydgyId,
  2112. 'CCYDH' => $row['CCYDH'] ?? null,
  2113. 'CYJMC' => $row['CYJMC'] ?? null,
  2114. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2115. 'CDXMC' => $row['CDXMC'] ?? null,
  2116. 'CGYBH' => $row['CGYBH'] ?? null,
  2117. 'CGYMC' => $row['CGYMC'] ?? null,
  2118. 'CDW' => $row['CDW'] ?? null,
  2119. 'czlyq' => $row['czlyq'] ?? null,
  2120. 'NGZL' => $row['NGZL'] ?? null,
  2121. 'CDF' => $row['CDF'] ?? null,
  2122. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2123. 'MBZ' => $row['MBZ'] ?? null,
  2124. 'bwjg' => $row['bwjg'] ?? null,
  2125. 'iStatus' => $row['iStatus'] ?? null,
  2126. 'dStamp' => $row['dStamp'] ?? null,
  2127. 'dputrecord' => $row['dputrecord'] ?? null,
  2128. 'cywyxm' => $row['cywyxm'] ?? null,
  2129. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2130. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2131. ];
  2132. }
  2133. /**
  2134. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2135. *
  2136. * @return array{po:?array<string,mixed>, hidden:bool}
  2137. */
  2138. protected function resolvePickRowPoContext(int $sid): array
  2139. {
  2140. $po = null;
  2141. try {
  2142. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2143. if (is_array($found)) {
  2144. $po = $found;
  2145. }
  2146. } catch (\Throwable $e) {
  2147. }
  2148. $hideSet = $this->loadPickHiddenScydgySet();
  2149. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2150. }
  2151. /**
  2152. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2153. */
  2154. protected function assertPickRowCanDelete(int $sid, array $row): void
  2155. {
  2156. $ctx = $this->resolvePickRowPoContext($sid);
  2157. $po = $ctx['po'];
  2158. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2159. return;
  2160. }
  2161. if (is_array($po)) {
  2162. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2163. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2164. }
  2165. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2166. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2167. }
  2168. }
  2169. if ($ctx['hidden']) {
  2170. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2171. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2172. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2173. }
  2174. }
  2175. /**
  2176. * 初选直接完结前校验
  2177. */
  2178. protected function assertPickRowCanComplete(int $sid, array $row): void
  2179. {
  2180. $ctx = $this->resolvePickRowPoContext($sid);
  2181. $po = $ctx['po'];
  2182. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2183. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2184. }
  2185. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2186. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2187. }
  2188. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2189. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2190. }
  2191. }
  2192. /**
  2193. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2194. */
  2195. protected function softDeleteProcuremenPickRow(array $row): void
  2196. {
  2197. $sid = $this->extractScydgyRowId($row);
  2198. if (!$this->isValidScydgyRowId($sid)) {
  2199. throw new \InvalidArgumentException('无效的行主键');
  2200. }
  2201. $this->assertPickRowCanDelete($sid, $row);
  2202. $po = $this->resolvePickRowPoContext($sid)['po'];
  2203. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2204. return;
  2205. }
  2206. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2207. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2208. }
  2209. $now = date('Y-m-d H:i:s');
  2210. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2211. if (is_array($exists)) {
  2212. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2213. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2214. } else {
  2215. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2216. $data['mod_rq'] = $now;
  2217. $data['createtime'] = $now;
  2218. Db::table('purchase_order')->insert($data);
  2219. $poIdLog = (int)Db::getLastInsID();
  2220. }
  2221. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2222. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2223. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2224. if ($gymcLog !== '') {
  2225. $logTail .= ' / ' . $gymcLog;
  2226. }
  2227. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2228. }
  2229. /**
  2230. * 手工新增协助工序(写入 purchase_order)
  2231. *
  2232. * @param array<string, mixed> $params
  2233. * @return int scydgy_id
  2234. */
  2235. protected function saveManualPickOrder(array $params): int
  2236. {
  2237. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2238. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2239. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  2240. if ($ccydh === '') {
  2241. $ccydh = $this->allocateManualOrderCcydh();
  2242. }
  2243. $now = date('Y-m-d H:i:s');
  2244. $sid = $this->allocateManualScydgyId();
  2245. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2246. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2247. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2248. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2249. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2250. $data = [
  2251. 'scydgy_id' => $sid,
  2252. 'CCYDH' => $ccydh,
  2253. 'CYJMC' => $cyjmc,
  2254. 'CGYMC' => $cgymc,
  2255. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2256. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2257. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2258. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2259. 'cGzzxMc' => $supplierName,
  2260. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2261. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2262. 'notify_salesman' => $notifySalesman,
  2263. 'rfq_salesman_notified' => 0,
  2264. 'rfq_salesman_notify_time' => null,
  2265. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2266. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2267. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2268. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2269. 'createtime' => $now,
  2270. 'dStamp' => $now,
  2271. 'dputrecord' => $now,
  2272. ];
  2273. Db::table('purchase_order')->insert($data);
  2274. $poId = (int)Db::getLastInsID();
  2275. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2276. return $sid;
  2277. }
  2278. protected function formatProcuremenRowLabel(array $row): string
  2279. {
  2280. $dh = trim((string)($row['CCYDH'] ?? ''));
  2281. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2282. if ($dh !== '' && $gymc !== '') {
  2283. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2284. }
  2285. if ($dh !== '') {
  2286. return '订单「' . $dh . '」';
  2287. }
  2288. if ($gymc !== '') {
  2289. return '工序「' . $gymc . '」';
  2290. }
  2291. $id = $this->extractScydgyRowId($row);
  2292. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2293. }
  2294. /**
  2295. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2296. */
  2297. protected function extractScydgyRowId(array $row): int
  2298. {
  2299. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2300. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2301. return (int)$row['scydgy_id'];
  2302. }
  2303. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2304. return (int)$row['SCYDGY_ID'];
  2305. }
  2306. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2307. }
  2308. protected function isValidScydgyRowId(int $id): bool
  2309. {
  2310. return ProcuremenGuard::isValidScydgyId($id);
  2311. }
  2312. protected function isManualScydgyRowId(int $id): bool
  2313. {
  2314. return $id < 0;
  2315. }
  2316. /**
  2317. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2318. *
  2319. * @param int[] $scydgyIds
  2320. * @return array<int, string[]>
  2321. */
  2322. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2323. {
  2324. $out = [];
  2325. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2326. if ($scydgyIds === []) {
  2327. return $out;
  2328. }
  2329. try {
  2330. $rows = Db::table('purchase_order_detail')
  2331. ->where('scydgy_id', 'in', $scydgyIds)
  2332. ->field('scydgy_id,company_name')
  2333. ->order('company_name', 'asc')
  2334. ->select();
  2335. } catch (\Throwable $e) {
  2336. $rows = [];
  2337. }
  2338. if (!is_array($rows)) {
  2339. return $out;
  2340. }
  2341. foreach ($rows as $r) {
  2342. if (!is_array($r)) {
  2343. continue;
  2344. }
  2345. $sid = (int)($r['scydgy_id'] ?? 0);
  2346. $cn = trim((string)($r['company_name'] ?? ''));
  2347. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2348. continue;
  2349. }
  2350. if (!isset($out[$sid])) {
  2351. $out[$sid] = [];
  2352. }
  2353. if (!in_array($cn, $out[$sid], true)) {
  2354. $out[$sid][] = $cn;
  2355. }
  2356. }
  2357. return $out;
  2358. }
  2359. /**
  2360. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2361. *
  2362. * @param string[] $names
  2363. */
  2364. protected function formatNotifySupplierDisplay(array $names): string
  2365. {
  2366. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2367. return trim((string)$n);
  2368. }, $names))));
  2369. if ($names === []) {
  2370. return '';
  2371. }
  2372. sort($names, SORT_STRING);
  2373. return implode("\n", $names);
  2374. }
  2375. /**
  2376. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2377. *
  2378. * @param int[] $scydgyIds
  2379. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2380. */
  2381. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2382. {
  2383. $out = [];
  2384. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2385. if ($scydgyIds === []) {
  2386. return $out;
  2387. }
  2388. try {
  2389. $rows = Db::table('purchase_order_detail')
  2390. ->where('scydgy_id', 'in', $scydgyIds)
  2391. ->field('scydgy_id,company_name,amount')
  2392. ->select();
  2393. } catch (\Throwable $e) {
  2394. $rows = [];
  2395. }
  2396. if (!is_array($rows)) {
  2397. return $out;
  2398. }
  2399. foreach ($rows as $r) {
  2400. if (!is_array($r)) {
  2401. continue;
  2402. }
  2403. $sid = (int)($r['scydgy_id'] ?? 0);
  2404. $cn = trim((string)($r['company_name'] ?? ''));
  2405. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2406. continue;
  2407. }
  2408. if (!isset($out[$sid])) {
  2409. $out[$sid] = ['all' => [], 'quoted' => []];
  2410. }
  2411. $out[$sid]['all'][$cn] = true;
  2412. $am = trim((string)($r['amount'] ?? ''));
  2413. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2414. $out[$sid]['quoted'][$cn] = true;
  2415. }
  2416. }
  2417. return $out;
  2418. }
  2419. /**
  2420. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2421. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2422. */
  2423. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2424. {
  2425. $merged = ['all' => [], 'quoted' => []];
  2426. foreach ($buckets as $b) {
  2427. if (!is_array($b)) {
  2428. continue;
  2429. }
  2430. foreach ($b['all'] ?? [] as $cn => $_) {
  2431. $merged['all'][$cn] = true;
  2432. }
  2433. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2434. $merged['quoted'][$cn] = true;
  2435. }
  2436. }
  2437. return $merged;
  2438. }
  2439. /**
  2440. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2441. */
  2442. protected function formatQuotedSupplierLines(array $bucket): string
  2443. {
  2444. $all = array_keys($bucket['all'] ?? []);
  2445. if ($all === []) {
  2446. return '';
  2447. }
  2448. sort($all, SORT_STRING);
  2449. $lines = [];
  2450. foreach ($all as $cn) {
  2451. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2452. $lines[] = $cn . '(' . $status . ')';
  2453. }
  2454. return implode("\n", $lines);
  2455. }
  2456. /**
  2457. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2458. */
  2459. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2460. {
  2461. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2462. $this->view->engine->layout(false);
  2463. try {
  2464. $bodyHtml = $this->view->fetch($view);
  2465. $this->view->assign('dialogBody', $bodyHtml);
  2466. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2467. return $this->view->fetch('procuremen/dialog_lite_shell');
  2468. } finally {
  2469. if ($restoreLayout) {
  2470. $this->view->engine->layout($restoreLayout);
  2471. }
  2472. }
  2473. }
  2474. /**
  2475. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2476. */
  2477. protected function resolveBundleSysRq(array $bundle): string
  2478. {
  2479. foreach ($bundle['pos'] ?? [] as $po) {
  2480. if (!is_array($po)) {
  2481. continue;
  2482. }
  2483. $sr = trim((string)($po['sys_rq'] ?? ''));
  2484. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2485. return $sr;
  2486. }
  2487. }
  2488. return '';
  2489. }
  2490. /**
  2491. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2492. */
  2493. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2494. {
  2495. $raw = trim((string)$sysRq);
  2496. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2497. return true;
  2498. }
  2499. $ts = strtotime(str_replace('T', ' ', $raw));
  2500. if ($ts === false || $ts <= 0) {
  2501. return true;
  2502. }
  2503. return time() >= $ts;
  2504. }
  2505. /**
  2506. * 开标前校验:必须已过报价截止时间
  2507. *
  2508. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2509. */
  2510. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2511. {
  2512. $sysRq = $this->resolveBundleSysRq($bundle);
  2513. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2514. $this->error('未到招标截止日期');
  2515. }
  2516. }
  2517. /**
  2518. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2519. *
  2520. * @param array<string, mixed> $d
  2521. * @param string $deliveryYmd
  2522. */
  2523. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2524. {
  2525. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2526. return max(0, (int)$d['lead_days']);
  2527. }
  2528. if ($deliveryYmd === '') {
  2529. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2530. }
  2531. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2532. return null;
  2533. }
  2534. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2535. $t2 = strtotime($m[1] . ' 00:00:00');
  2536. if ($t1 === false || $t2 === false) {
  2537. return null;
  2538. }
  2539. return max(0, (int)round(($t2 - $t1) / 86400));
  2540. }
  2541. /**
  2542. * @param int|null $days
  2543. */
  2544. protected function formatProcuremenLeadDaysText($days): string
  2545. {
  2546. if ($days === null || $days === '') {
  2547. return '未填写';
  2548. }
  2549. if (!is_numeric($days)) {
  2550. return '未填写';
  2551. }
  2552. return ((int)$days) . '天';
  2553. }
  2554. /**
  2555. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2556. *
  2557. * @param array<string, mixed> $line
  2558. */
  2559. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2560. {
  2561. $amountFilled = !empty($line['amount_filled']);
  2562. $deliveryFilled = !empty($line['delivery_filled']);
  2563. $leadFilled = !empty($line['lead_days_filled']);
  2564. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2565. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2566. $line['amount_show'] = '';
  2567. if (array_key_exists('amount_text', $line)) {
  2568. $line['amount_text'] = $line['unit_price_text'];
  2569. }
  2570. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2571. $line['delivery_show'] = $deliveryText;
  2572. if (array_key_exists('delivery_text', $line)) {
  2573. $line['delivery_text'] = $deliveryText;
  2574. }
  2575. $line['delivery_ymd'] = '';
  2576. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2577. $line['lead_days_show'] = $leadText;
  2578. $line['lead_days_text'] = $leadText;
  2579. $line['lead_days'] = '';
  2580. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2581. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2582. $line['subtotal_num'] = null;
  2583. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2584. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2585. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2586. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2587. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2588. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2589. $line['amount_filled'] = false;
  2590. $line['delivery_filled'] = false;
  2591. $line['lead_days_filled'] = false;
  2592. $line['is_quoted'] = false;
  2593. if (array_key_exists('quote_label', $line)) {
  2594. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2595. }
  2596. }
  2597. protected function ensurePurchaseOrderBidOpenTable(): void
  2598. {
  2599. static $ready = false;
  2600. if ($ready) {
  2601. return;
  2602. }
  2603. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2604. try {
  2605. if (Cache::get($cacheKey)) {
  2606. $ready = true;
  2607. return;
  2608. }
  2609. } catch (\Throwable $e) {
  2610. }
  2611. try {
  2612. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2613. $ready = true;
  2614. try {
  2615. Cache::set($cacheKey, 1, 86400);
  2616. } catch (\Throwable $e) {
  2617. }
  2618. } catch (\Throwable $e) {
  2619. Db::execute(
  2620. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2621. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2622. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2623. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2624. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2625. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2626. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2627. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2628. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2629. `createtime` datetime DEFAULT NULL,
  2630. PRIMARY KEY (`id`),
  2631. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2632. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2633. );
  2634. $ready = true;
  2635. try {
  2636. Cache::set($cacheKey, 1, 86400);
  2637. } catch (\Throwable $e2) {
  2638. }
  2639. }
  2640. }
  2641. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2642. {
  2643. $ccydh = trim($ccydh);
  2644. if ($ccydh === '') {
  2645. return false;
  2646. }
  2647. $this->ensurePurchaseOrderBidOpenTable();
  2648. try {
  2649. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2650. return is_array($row);
  2651. } catch (\Throwable $e) {
  2652. return false;
  2653. }
  2654. }
  2655. /**
  2656. * 批量查询订单是否已开标验证
  2657. *
  2658. * @param array<int, string> $ccydhs
  2659. * @return array<string, bool> ccydh => true
  2660. */
  2661. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2662. {
  2663. $set = [];
  2664. $list = [];
  2665. foreach ($ccydhs as $c) {
  2666. $c = trim((string)$c);
  2667. if ($c !== '') {
  2668. $list[$c] = true;
  2669. }
  2670. }
  2671. if ($list === []) {
  2672. return $set;
  2673. }
  2674. $this->ensurePurchaseOrderBidOpenTable();
  2675. try {
  2676. $rows = Db::table('purchase_order_bid_open')
  2677. ->where('ccydh', 'in', array_keys($list))
  2678. ->field('ccydh')
  2679. ->select();
  2680. foreach ($rows as $row) {
  2681. if (!is_array($row)) {
  2682. continue;
  2683. }
  2684. $c = trim((string)($row['ccydh'] ?? ''));
  2685. if ($c !== '') {
  2686. $set[$c] = true;
  2687. }
  2688. }
  2689. } catch (\Throwable $e) {
  2690. return [];
  2691. }
  2692. return $set;
  2693. }
  2694. /**
  2695. * 批量查询订单是否已指定供应商(免开标)
  2696. *
  2697. * @param array<int, string> $ccydhs
  2698. * @return array<string, bool> ccydh => true
  2699. */
  2700. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2701. {
  2702. $set = [];
  2703. $list = [];
  2704. foreach ($ccydhs as $c) {
  2705. $c = trim((string)$c);
  2706. if ($c !== '') {
  2707. $list[$c] = true;
  2708. }
  2709. }
  2710. if ($list === []) {
  2711. return $set;
  2712. }
  2713. $this->ensurePurchaseOrderManualPickColumns();
  2714. try {
  2715. $rows = Db::table('purchase_order')
  2716. ->where('CCYDH', 'in', array_keys($list))
  2717. ->where('manual_pick', 1)
  2718. ->field('CCYDH')
  2719. ->select();
  2720. foreach ($rows as $row) {
  2721. if (!is_array($row)) {
  2722. continue;
  2723. }
  2724. $c = trim((string)($row['CCYDH'] ?? ''));
  2725. if ($c !== '') {
  2726. $set[$c] = true;
  2727. }
  2728. }
  2729. } catch (\Throwable $e) {
  2730. return [];
  2731. }
  2732. return $set;
  2733. }
  2734. /**
  2735. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2736. *
  2737. * @param array<int, array<string, mixed>> $pool
  2738. * @return array<int, array<string, mixed>>
  2739. */
  2740. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2741. {
  2742. $status = trim($status);
  2743. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2744. return $pool;
  2745. }
  2746. $ccydhList = [];
  2747. foreach ($pool as $rw) {
  2748. if (!is_array($rw)) {
  2749. continue;
  2750. }
  2751. $c = trim((string)($rw['CCYDH'] ?? ''));
  2752. if ($c !== '') {
  2753. $ccydhList[] = $c;
  2754. }
  2755. }
  2756. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2757. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2758. $out = [];
  2759. foreach ($pool as $rw) {
  2760. if (!is_array($rw)) {
  2761. continue;
  2762. }
  2763. $c = trim((string)($rw['CCYDH'] ?? ''));
  2764. if ($c !== '' && isset($bidOpenSet[$c])) {
  2765. $t = '已开标';
  2766. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2767. $t = '已指定供应商';
  2768. } else {
  2769. $t = '待开标';
  2770. }
  2771. if ($t === $status) {
  2772. $out[] = $rw;
  2773. }
  2774. }
  2775. return $out;
  2776. }
  2777. /**
  2778. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2779. *
  2780. * @param array<string, mixed> $group
  2781. */
  2782. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2783. {
  2784. if ($quoteVisible) {
  2785. $group['remark_quote_pending'] = 0;
  2786. return;
  2787. }
  2788. $group['remark'] = '';
  2789. $group['remark_quote_pending'] = 0;
  2790. }
  2791. /**
  2792. * @param array{ccydh?:string} $bundle
  2793. */
  2794. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2795. {
  2796. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2797. }
  2798. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2799. {
  2800. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2801. return true;
  2802. }
  2803. return $this->isProcuremenManualPickedForBundle($bundle);
  2804. }
  2805. /**
  2806. * 确保 purchase_order 自选供应商字段
  2807. */
  2808. protected function ensurePurchaseOrderManualPickColumns(): void
  2809. {
  2810. static $done = false;
  2811. if ($done) {
  2812. return;
  2813. }
  2814. $done = true;
  2815. $adds = [
  2816. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2817. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2818. ];
  2819. foreach ($adds as $col => $ddl) {
  2820. try {
  2821. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2822. if (!is_array($cols) || $cols === []) {
  2823. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2824. }
  2825. } catch (\Throwable $e) {
  2826. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2827. }
  2828. }
  2829. }
  2830. /**
  2831. * 是否已自选供应商(免开标查看报价)
  2832. *
  2833. * @param array{pos?:array} $bundle
  2834. */
  2835. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2836. {
  2837. $this->ensurePurchaseOrderManualPickColumns();
  2838. foreach ($bundle['pos'] ?? [] as $poRow) {
  2839. if (!is_array($poRow)) {
  2840. continue;
  2841. }
  2842. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2843. return true;
  2844. }
  2845. }
  2846. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2847. if ($ccydh === '') {
  2848. return false;
  2849. }
  2850. try {
  2851. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2852. return $v !== null && $v !== false && (int)$v > 0;
  2853. } catch (\Throwable $e) {
  2854. return false;
  2855. }
  2856. }
  2857. /**
  2858. * @param array{pos?:array} $bundle
  2859. * @return array{company:string,reason:string}
  2860. */
  2861. protected function resolveProcuremenManualPickInfo(array $bundle): array
  2862. {
  2863. $this->ensurePurchaseOrderManualPickColumns();
  2864. foreach ($bundle['pos'] ?? [] as $poRow) {
  2865. if (!is_array($poRow)) {
  2866. continue;
  2867. }
  2868. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  2869. continue;
  2870. }
  2871. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  2872. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  2873. return ['company' => $cn, 'reason' => $reason];
  2874. }
  2875. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2876. if ($ccydh === '') {
  2877. return ['company' => '', 'reason' => ''];
  2878. }
  2879. try {
  2880. $row = Db::table('purchase_order')
  2881. ->where('CCYDH', $ccydh)
  2882. ->where('manual_pick', 1)
  2883. ->field('pick_company_name,manual_pick_reason')
  2884. ->order('id', 'asc')
  2885. ->find();
  2886. } catch (\Throwable $e) {
  2887. $row = null;
  2888. }
  2889. if (!is_array($row)) {
  2890. return ['company' => '', 'reason' => ''];
  2891. }
  2892. return [
  2893. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  2894. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  2895. ];
  2896. }
  2897. protected function loadBidOpenAdminUser(int $adminId): ?array
  2898. {
  2899. if ($adminId <= 0) {
  2900. return null;
  2901. }
  2902. try {
  2903. $row = Db::name('admin')->where('id', $adminId)->find();
  2904. } catch (\Throwable $e) {
  2905. return null;
  2906. }
  2907. if (!is_array($row)) {
  2908. return null;
  2909. }
  2910. $status = strtolower(trim((string)($row['status'] ?? '')));
  2911. if ($status !== '' && $status !== 'normal') {
  2912. return null;
  2913. }
  2914. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2915. return null;
  2916. }
  2917. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2918. if (!preg_match('/^1\d{10}$/', $phone)) {
  2919. return null;
  2920. }
  2921. $name = trim((string)($row['nickname'] ?? ''));
  2922. if ($name === '') {
  2923. $name = trim((string)($row['username'] ?? ''));
  2924. }
  2925. return [
  2926. 'id' => (int)$row['id'],
  2927. 'username' => trim((string)($row['username'] ?? '')),
  2928. 'nickname' => $name,
  2929. 'mobile' => $phone,
  2930. ];
  2931. }
  2932. /**
  2933. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2934. */
  2935. protected function bidOpenVerifierAuthGroupRootId(): int
  2936. {
  2937. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2938. return $id > 0 ? $id : 10;
  2939. }
  2940. /**
  2941. * @return int[]
  2942. */
  2943. protected function loadBidOpenVerifierAuthGroupIds(): array
  2944. {
  2945. static $memo = [];
  2946. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2947. if (isset($memo[$rootId])) {
  2948. return $memo[$rootId];
  2949. }
  2950. try {
  2951. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2952. } catch (\Throwable $e) {
  2953. $memo[$rootId] = [$rootId];
  2954. return $memo[$rootId];
  2955. }
  2956. if (!is_array($groups) || $groups === []) {
  2957. $memo[$rootId] = [$rootId];
  2958. return $memo[$rootId];
  2959. }
  2960. $groupList = [];
  2961. foreach ($groups as $g) {
  2962. if (is_array($g)) {
  2963. $groupList[] = $g;
  2964. }
  2965. }
  2966. if ($groupList === []) {
  2967. $memo[$rootId] = [$rootId];
  2968. return $memo[$rootId];
  2969. }
  2970. $tree = \fast\Tree::instance();
  2971. $tree->init($groupList);
  2972. $ids = $tree->getChildrenIds($rootId, true);
  2973. if (!is_array($ids) || $ids === []) {
  2974. $memo[$rootId] = [$rootId];
  2975. return $memo[$rootId];
  2976. }
  2977. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2978. return $memo[$rootId];
  2979. }
  2980. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2981. {
  2982. if ($adminId <= 0) {
  2983. return false;
  2984. }
  2985. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2986. if ($groupIds === []) {
  2987. return false;
  2988. }
  2989. try {
  2990. return (bool)Db::name('auth_group_access')
  2991. ->where('uid', $adminId)
  2992. ->where('group_id', 'in', $groupIds)
  2993. ->count();
  2994. } catch (\Throwable $e) {
  2995. return false;
  2996. }
  2997. }
  2998. /**
  2999. * @return array<int, array<string, mixed>>
  3000. */
  3001. protected function listBidOpenVerifierCandidates(): array
  3002. {
  3003. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3004. if ($groupIds === []) {
  3005. return [];
  3006. }
  3007. try {
  3008. $adminIds = Db::name('auth_group_access')
  3009. ->where('group_id', 'in', $groupIds)
  3010. ->column('uid');
  3011. } catch (\Throwable $e) {
  3012. $adminIds = [];
  3013. }
  3014. $adminIds = is_array($adminIds)
  3015. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3016. : [];
  3017. if ($adminIds === []) {
  3018. return [];
  3019. }
  3020. try {
  3021. $rows = Db::name('admin')
  3022. ->where('status', 'normal')
  3023. ->where('id', 'in', $adminIds)
  3024. ->where('mobile', '<>', '')
  3025. ->order('id', 'asc')
  3026. ->select();
  3027. } catch (\Throwable $e) {
  3028. return [];
  3029. }
  3030. if (!is_array($rows)) {
  3031. return [];
  3032. }
  3033. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3034. $out = [];
  3035. foreach ($rows as $row) {
  3036. if (!is_array($row)) {
  3037. continue;
  3038. }
  3039. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3040. if ($one === null) {
  3041. continue;
  3042. }
  3043. $out[] = [
  3044. 'id' => $one['id'],
  3045. 'username' => $one['username'],
  3046. 'nickname' => $one['nickname'],
  3047. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3048. 'mobile' => mask_phone($one['mobile']),
  3049. 'mobile_plain' => (string)$one['mobile'],
  3050. ];
  3051. }
  3052. return $out;
  3053. }
  3054. /**
  3055. * @param int[] $adminIds
  3056. * @return array<int, string>
  3057. */
  3058. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3059. {
  3060. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3061. if ($adminIds === []) {
  3062. return [];
  3063. }
  3064. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3065. try {
  3066. $rows = Db::name('auth_group_access')
  3067. ->alias('aga')
  3068. ->join('auth_group ag', 'aga.group_id = ag.id')
  3069. ->where('aga.uid', 'in', $adminIds)
  3070. ->where('aga.group_id', 'in', $groupIds)
  3071. ->field('aga.uid,ag.name')
  3072. ->order('aga.uid', 'asc')
  3073. ->order('aga.group_id', 'asc')
  3074. ->select();
  3075. } catch (\Throwable $e) {
  3076. return [];
  3077. }
  3078. if (!is_array($rows)) {
  3079. return [];
  3080. }
  3081. $out = [];
  3082. foreach ($rows as $row) {
  3083. if (!is_array($row)) {
  3084. continue;
  3085. }
  3086. $uid = (int)($row['uid'] ?? 0);
  3087. $name = trim((string)($row['name'] ?? ''));
  3088. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3089. continue;
  3090. }
  3091. $out[$uid] = $name;
  3092. }
  3093. return $out;
  3094. }
  3095. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3096. {
  3097. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3098. }
  3099. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3100. {
  3101. return 'procuremen_bidopen_wait_' . $adminId;
  3102. }
  3103. protected function renderBidOpenVerifySms(string $code): string
  3104. {
  3105. $tpl = '';
  3106. try {
  3107. $row = $this->loadNotifyTemplateRow('bid_open');
  3108. if (is_array($row)) {
  3109. $tpl = trim((string)($row['content'] ?? ''));
  3110. }
  3111. } catch (\Throwable $e) {
  3112. $tpl = '';
  3113. }
  3114. if ($tpl === '') {
  3115. $tpl = '【可集达】您的短信验证码是{code}';
  3116. }
  3117. return str_replace('{code}', $code, $tpl);
  3118. }
  3119. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3120. {
  3121. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3122. }
  3123. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3124. {
  3125. $code = trim($code);
  3126. if (!preg_match('/^\d{6}$/', $code)) {
  3127. return false;
  3128. }
  3129. $mock = Config::get('mproc.mock_sms_code');
  3130. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3131. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3132. return true;
  3133. }
  3134. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3135. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3136. return false;
  3137. }
  3138. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3139. return true;
  3140. }
  3141. /**
  3142. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3143. */
  3144. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3145. {
  3146. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3147. if ($ccydh === '') {
  3148. throw new \InvalidArgumentException('订单号无效');
  3149. }
  3150. $this->ensurePurchaseOrderBidOpenTable();
  3151. list($operatorId, $operatorName) = $this->GetUseName();
  3152. $now = date('Y-m-d H:i:s');
  3153. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3154. $payload = [
  3155. 'ccydh' => $ccydh,
  3156. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3157. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3158. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3159. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3160. 'operator_id' => (int)$operatorId,
  3161. 'operator_name' => trim((string)$operatorName),
  3162. 'createtime' => $now,
  3163. ];
  3164. if (is_array($exists)) {
  3165. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3166. } else {
  3167. Db::table('purchase_order_bid_open')->insert($payload);
  3168. }
  3169. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3170. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3171. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3172. (int)$payload['verifier1_id'],
  3173. (int)$payload['verifier2_id'],
  3174. ]);
  3175. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3176. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3177. }
  3178. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3179. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3180. }
  3181. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3182. $seenSid = [];
  3183. foreach ($bundle['pos'] ?? [] as $poRow) {
  3184. if (!is_array($poRow)) {
  3185. continue;
  3186. }
  3187. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3188. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3189. continue;
  3190. }
  3191. $seenSid[$sid] = true;
  3192. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3193. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3194. }
  3195. if ($seenSid === []) {
  3196. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3197. if ($this->isValidScydgyRowId($anchor)) {
  3198. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3199. }
  3200. }
  3201. // 开标通过后计算并写入供应商服务评分
  3202. try {
  3203. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3204. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3205. } catch (\Throwable $e) {
  3206. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3207. }
  3208. }
  3209. /**
  3210. * 报价行展示字段默认值(模板安全访问)
  3211. *
  3212. * @param array<string, mixed> $line
  3213. * @return array<string, mixed>
  3214. */
  3215. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3216. {
  3217. if (!array_key_exists('amount_quote_pending', $line)) {
  3218. $line['amount_quote_pending'] = 0;
  3219. }
  3220. if (!array_key_exists('delivery_quote_pending', $line)) {
  3221. $line['delivery_quote_pending'] = 0;
  3222. }
  3223. if (!array_key_exists('quote_before_deadline', $line)) {
  3224. $line['quote_before_deadline'] = 0;
  3225. }
  3226. if (!array_key_exists('amount_filled', $line)) {
  3227. $line['amount_filled'] = 0;
  3228. }
  3229. if (!array_key_exists('delivery_filled', $line)) {
  3230. $line['delivery_filled'] = 0;
  3231. }
  3232. if (!array_key_exists('lead_days_filled', $line)) {
  3233. $line['lead_days_filled'] = 0;
  3234. }
  3235. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3236. $line['lead_days_quote_pending'] = 0;
  3237. }
  3238. if (!array_key_exists('lead_days_show', $line)) {
  3239. $line['lead_days_show'] = '未填写';
  3240. }
  3241. if (!array_key_exists('lead_days_text', $line)) {
  3242. $line['lead_days_text'] = $line['lead_days_show'];
  3243. }
  3244. return $line;
  3245. }
  3246. /**
  3247. * 审核弹窗:按供应商汇总报价明细
  3248. *
  3249. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3250. * @return array<int, array<string, mixed>>
  3251. */
  3252. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3253. {
  3254. $sids = [];
  3255. foreach ($bundle['pos'] ?? [] as $po) {
  3256. if (!is_array($po)) {
  3257. continue;
  3258. }
  3259. $sid = (int)($po['scydgy_id'] ?? 0);
  3260. if ($this->isValidScydgyRowId($sid)) {
  3261. $sids[$sid] = true;
  3262. }
  3263. }
  3264. if ($sids === []) {
  3265. return [];
  3266. }
  3267. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3268. $gymcMap = [];
  3269. $qtyBySid = [];
  3270. $orderedSids = [];
  3271. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3272. if (!is_array($mr)) {
  3273. continue;
  3274. }
  3275. $gid = $this->extractScydgyRowId($mr);
  3276. if ($this->isValidScydgyRowId($gid)) {
  3277. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3278. $orderedSids[] = $gid;
  3279. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3280. if ($qty === '') {
  3281. $qty = trim((string)($mr['NGZL'] ?? ''));
  3282. }
  3283. $qtyBySid[$gid] = $qty;
  3284. }
  3285. }
  3286. foreach ($bundle['pos'] ?? [] as $po) {
  3287. if (!is_array($po)) {
  3288. continue;
  3289. }
  3290. $gid = (int)($po['scydgy_id'] ?? 0);
  3291. if ($this->isValidScydgyRowId($gid)) {
  3292. $nm = trim((string)($po['CGYMC'] ?? ''));
  3293. if ($nm !== '') {
  3294. $gymcMap[$gid] = $nm;
  3295. }
  3296. if (!in_array($gid, $orderedSids, true)) {
  3297. $orderedSids[] = $gid;
  3298. }
  3299. }
  3300. }
  3301. try {
  3302. $detailsQuery = Db::table('purchase_order_detail')
  3303. ->where('scydgy_id', 'in', array_keys($sids));
  3304. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3305. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3306. } catch (\Throwable $e) {
  3307. try {
  3308. $detailsQuery = Db::table('purchase_order_detail')
  3309. ->where('scydgy_id', 'in', array_keys($sids));
  3310. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3311. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3312. } catch (\Throwable $e2) {
  3313. $details = [];
  3314. }
  3315. }
  3316. if (!is_array($details)) {
  3317. $details = [];
  3318. }
  3319. $byCompany = [];
  3320. foreach ($details as $d) {
  3321. if (!is_array($d)) {
  3322. continue;
  3323. }
  3324. $cn = trim((string)($d['company_name'] ?? ''));
  3325. if ($cn === '') {
  3326. continue;
  3327. }
  3328. if (!isset($byCompany[$cn])) {
  3329. $ph = trim((string)($d['phone'] ?? ''));
  3330. $username = trim((string)($d['username'] ?? ''));
  3331. if ($username === '') {
  3332. $username = $this->resolveCustomerContactName($ph, $cn);
  3333. }
  3334. $byCompany[$cn] = [
  3335. 'name' => $cn,
  3336. 'email' => trim((string)($d['email'] ?? '')),
  3337. 'phone' => $ph,
  3338. 'username' => $username,
  3339. 'remark' => '',
  3340. 'has_quote' => false,
  3341. 'lines_map' => [],
  3342. ];
  3343. }
  3344. if ($byCompany[$cn]['remark'] === '') {
  3345. $rm = '';
  3346. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3347. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3348. $rm = trim((string)$d[$rk]);
  3349. break;
  3350. }
  3351. }
  3352. if ($rm !== '') {
  3353. $byCompany[$cn]['remark'] = $rm;
  3354. }
  3355. }
  3356. $sid = (int)($d['scydgy_id'] ?? 0);
  3357. $am = trim((string)($d['amount'] ?? ''));
  3358. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3359. if ($gymc === '') {
  3360. $gymc = '工序';
  3361. }
  3362. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3363. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3364. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3365. $deliveryShow = $deliveryRaw;
  3366. }
  3367. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3368. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3369. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3370. $subtotal = null;
  3371. if ($amountNum !== null) {
  3372. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3373. }
  3374. $unitPriceText = $amountFilled
  3375. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3376. : '未填写';
  3377. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3378. $leadFilled = ($leadDays !== null);
  3379. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3380. $lineRow = [
  3381. 'cgymc' => $gymc,
  3382. 'amount' => $am,
  3383. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3384. 'amount_filled' => $amountFilled,
  3385. 'unit_price_text' => $unitPriceText,
  3386. 'delivery' => $deliveryRaw,
  3387. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3388. 'delivery_filled' => $deliveryFilled,
  3389. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3390. 'lead_days' => $leadFilled ? $leadDays : '',
  3391. 'lead_days_filled'=> $leadFilled,
  3392. 'lead_days_show' => $leadText,
  3393. 'lead_days_text' => $leadText,
  3394. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3395. 'subtotal_num' => $subtotal,
  3396. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3397. 'is_quoted' => $amountFilled,
  3398. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3399. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3400. ];
  3401. if (!$quoteVisible) {
  3402. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3403. }
  3404. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3405. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3406. }
  3407. foreach ($byCompany as $cn => $g) {
  3408. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3409. $lines = [];
  3410. $usedSids = [];
  3411. foreach ($orderedSids as $sid) {
  3412. if (!isset($linesMap[$sid])) {
  3413. continue;
  3414. }
  3415. $lines[] = $linesMap[$sid];
  3416. $usedSids[$sid] = true;
  3417. }
  3418. foreach ($linesMap as $sid => $ln) {
  3419. if (isset($usedSids[$sid])) {
  3420. continue;
  3421. }
  3422. $lines[] = $ln;
  3423. }
  3424. $total = count($lines);
  3425. $quoted = 0;
  3426. $groupTotal = 0.0;
  3427. $groupHasTotal = false;
  3428. if ($quoteVisible) {
  3429. foreach ($lines as $ln) {
  3430. $am = trim((string)($ln['amount'] ?? ''));
  3431. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3432. $quoted++;
  3433. }
  3434. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3435. $groupTotal += (float)$ln['subtotal_num'];
  3436. $groupHasTotal = true;
  3437. }
  3438. }
  3439. }
  3440. unset($byCompany[$cn]['lines_map']);
  3441. $byCompany[$cn]['lines'] = $lines;
  3442. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3443. $byCompany[$cn]['line_count'] = $total;
  3444. $byCompany[$cn]['has_total'] = $total > 0;
  3445. $byCompany[$cn]['has_remark'] = $total > 0;
  3446. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3447. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3448. // 工序行 + 备注行 + 总计行
  3449. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3450. }
  3451. $groups = array_values($byCompany);
  3452. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3453. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3454. }
  3455. /**
  3456. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3457. *
  3458. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3459. * @return array<int, array<string, mixed>>
  3460. */
  3461. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3462. {
  3463. $sids = [];
  3464. $poIdMap = [];
  3465. foreach ($bundle['pos'] ?? [] as $po) {
  3466. if (!is_array($po)) {
  3467. continue;
  3468. }
  3469. $sid = (int)($po['scydgy_id'] ?? 0);
  3470. if ($this->isValidScydgyRowId($sid)) {
  3471. $sids[$sid] = true;
  3472. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3473. }
  3474. }
  3475. if ($sids === []) {
  3476. return [];
  3477. }
  3478. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3479. $gymcMap = [];
  3480. $qtyBySid = [];
  3481. $orderedSids = [];
  3482. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3483. if (!is_array($mr)) {
  3484. continue;
  3485. }
  3486. $gid = $this->extractScydgyRowId($mr);
  3487. if ($this->isValidScydgyRowId($gid)) {
  3488. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3489. $orderedSids[] = $gid;
  3490. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3491. if ($qty === '') {
  3492. $qty = trim((string)($mr['NGZL'] ?? ''));
  3493. }
  3494. $qtyBySid[$gid] = $qty;
  3495. }
  3496. }
  3497. foreach ($bundle['pos'] ?? [] as $po) {
  3498. if (!is_array($po)) {
  3499. continue;
  3500. }
  3501. $gid = (int)($po['scydgy_id'] ?? 0);
  3502. if ($this->isValidScydgyRowId($gid)) {
  3503. $nm = trim((string)($po['CGYMC'] ?? ''));
  3504. if ($nm !== '') {
  3505. $gymcMap[$gid] = $nm;
  3506. }
  3507. }
  3508. }
  3509. try {
  3510. $details = Db::table('purchase_order_detail')
  3511. ->where('scydgy_id', 'in', array_keys($sids))
  3512. ->order('company_name', 'asc')
  3513. ->order('id', 'asc')
  3514. ->select();
  3515. } catch (\Throwable $e) {
  3516. try {
  3517. $details = Db::table('purchase_order_detail')
  3518. ->where('scydgy_id', 'in', array_keys($sids))
  3519. ->order('company_name', 'asc')
  3520. ->order('ID', 'asc')
  3521. ->select();
  3522. } catch (\Throwable $e2) {
  3523. $details = [];
  3524. }
  3525. }
  3526. if (!is_array($details)) {
  3527. $details = [];
  3528. }
  3529. $byCompany = [];
  3530. foreach ($details as $d) {
  3531. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3532. continue;
  3533. }
  3534. $cn = trim((string)($d['company_name'] ?? ''));
  3535. if ($cn === '') {
  3536. continue;
  3537. }
  3538. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3539. $sid = (int)($d['scydgy_id'] ?? 0);
  3540. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3541. continue;
  3542. }
  3543. if (!isset($byCompany[$cn])) {
  3544. $ph = trim((string)($d['phone'] ?? ''));
  3545. $username = trim((string)($d['username'] ?? ''));
  3546. if ($username === '') {
  3547. $username = $this->resolveCustomerContactName($ph, $cn);
  3548. }
  3549. $byCompany[$cn] = [
  3550. 'name' => $cn,
  3551. 'email' => trim((string)($d['email'] ?? '')),
  3552. 'phone' => $ph,
  3553. 'username' => $username,
  3554. 'remark' => '',
  3555. 'pick_lines' => [],
  3556. 'detail_picks' => [],
  3557. ];
  3558. }
  3559. if ($byCompany[$cn]['remark'] === '') {
  3560. $rm = '';
  3561. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3562. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3563. $rm = trim((string)$d[$rk]);
  3564. break;
  3565. }
  3566. }
  3567. if ($rm !== '') {
  3568. $byCompany[$cn]['remark'] = $rm;
  3569. }
  3570. }
  3571. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3572. if ($gymc === '') {
  3573. $gymc = '工序';
  3574. }
  3575. $am = trim((string)($d['amount'] ?? ''));
  3576. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3577. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3578. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3579. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3580. $deliveryShow = $deliveryRaw;
  3581. }
  3582. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3583. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3584. $subtotal = null;
  3585. if ($amountNum !== null) {
  3586. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3587. }
  3588. $unitPriceText = $amountFilled
  3589. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3590. : '未填写';
  3591. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3592. $leadFilled = ($leadDays !== null);
  3593. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3594. $pickLine = [
  3595. 'cgymc' => $gymc,
  3596. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3597. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3598. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3599. 'amount_filled' => $amountFilled,
  3600. 'delivery_filled' => $deliveryFilled,
  3601. 'unit_price_text' => $unitPriceText,
  3602. 'lead_days' => $leadFilled ? $leadDays : '',
  3603. 'lead_days_filled'=> $leadFilled,
  3604. 'lead_days_show' => $leadText,
  3605. 'lead_days_text' => $leadText,
  3606. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3607. 'subtotal_num' => $subtotal,
  3608. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3609. 'is_quoted' => $amountFilled,
  3610. ];
  3611. if (!$quoteVisible) {
  3612. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3613. }
  3614. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3615. $byCompany[$cn]['detail_picks'][$sid] = [
  3616. 'scydgy_id' => $sid,
  3617. 'detail_id' => $detailId,
  3618. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3619. 'cgymc' => $gymc,
  3620. ];
  3621. }
  3622. $out = [];
  3623. foreach ($byCompany as $g) {
  3624. $pickLinesMap = $g['pick_lines'] ?? [];
  3625. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3626. continue;
  3627. }
  3628. $pickLines = [];
  3629. $usedLineSids = [];
  3630. foreach ($orderedSids as $sid) {
  3631. if (!isset($pickLinesMap[$sid])) {
  3632. continue;
  3633. }
  3634. $pickLines[] = $pickLinesMap[$sid];
  3635. $usedLineSids[$sid] = true;
  3636. }
  3637. foreach ($pickLinesMap as $sid => $ln) {
  3638. if (isset($usedLineSids[$sid])) {
  3639. continue;
  3640. }
  3641. $pickLines[] = $ln;
  3642. }
  3643. $groupTotal = 0.0;
  3644. $groupHasTotal = false;
  3645. if ($quoteVisible) {
  3646. foreach ($pickLines as $ln) {
  3647. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3648. $groupTotal += (float)$ln['subtotal_num'];
  3649. $groupHasTotal = true;
  3650. }
  3651. }
  3652. }
  3653. $lineCount = count($pickLines);
  3654. $g['pick_lines'] = $pickLines;
  3655. $g['line_count'] = $lineCount;
  3656. $g['has_total'] = $lineCount > 0;
  3657. $g['has_remark'] = $lineCount > 0;
  3658. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3659. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3660. // 工序行 + 备注行 + 总计行
  3661. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3662. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3663. $detailPicks = [];
  3664. $usedPickSids = [];
  3665. foreach ($orderedSids as $sid) {
  3666. if (!isset($detailPicksMap[$sid])) {
  3667. continue;
  3668. }
  3669. $detailPicks[] = $detailPicksMap[$sid];
  3670. $usedPickSids[$sid] = true;
  3671. }
  3672. foreach ($detailPicksMap as $sid => $dp) {
  3673. if (isset($usedPickSids[$sid])) {
  3674. continue;
  3675. }
  3676. $detailPicks[] = $dp;
  3677. }
  3678. $g['detail_picks'] = $detailPicks;
  3679. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3680. unset($g['detail_picks']);
  3681. $out[] = $g;
  3682. }
  3683. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3684. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3685. }
  3686. /**
  3687. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3688. * @return array<int, int[]> scydgy_id => detail_id[]
  3689. */
  3690. protected function mapDetailIdsByScydgyId(array $details): array
  3691. {
  3692. $out = [];
  3693. foreach ($details as $d) {
  3694. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3695. continue;
  3696. }
  3697. $sid = (int)($d['scydgy_id'] ?? 0);
  3698. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3699. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3700. continue;
  3701. }
  3702. if (!isset($out[$sid])) {
  3703. $out[$sid] = [];
  3704. }
  3705. $out[$sid][] = $pk;
  3706. }
  3707. foreach ($out as $sid => $ids) {
  3708. $out[$sid] = array_values(array_unique($ids));
  3709. }
  3710. return $out;
  3711. }
  3712. /**
  3713. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3714. *
  3715. * @param array<string, mixed> $dbRow
  3716. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3717. */
  3718. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3719. {
  3720. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3721. $r = [
  3722. 'ID' => $sid,
  3723. 'scydgy_id' => $sid,
  3724. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3725. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3726. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3727. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3728. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3729. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3730. 'CDW' => $dbRow['CDW'] ?? '',
  3731. 'czlyq' => $dbRow['czlyq'] ?? '',
  3732. 'NGZL' => $dbRow['NGZL'] ?? '',
  3733. 'CDF' => $dbRow['CDF'] ?? '',
  3734. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3735. 'MBZ' => $dbRow['MBZ'] ?? '',
  3736. 'bwjg' => $dbRow['bwjg'] ?? '',
  3737. 'iStatus' => $dbRow['iStatus'] ?? '',
  3738. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3739. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3740. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3741. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3742. 'dStamp' => $dbRow['dStamp'] ?? '',
  3743. 'pick_time' => $dbRow['pick_time'] ?? '',
  3744. ];
  3745. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3746. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3747. if ($sid > 0 && isset($dStampMap[$sid])) {
  3748. $t = trim((string)$dStampMap[$sid]);
  3749. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3750. $r['dStamp'] = $dStampMap[$sid];
  3751. }
  3752. }
  3753. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3754. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3755. $ct = $dbRow['createtime'];
  3756. if (is_numeric($ct) && (int)$ct > 946684800) {
  3757. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3758. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3759. $r['dStamp'] = trim($ct);
  3760. }
  3761. }
  3762. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3763. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3764. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3765. $fallback = trim((string)($r['dStamp'] ?? ''));
  3766. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3767. $r['dputrecord'] = $fallback;
  3768. }
  3769. }
  3770. if (array_key_exists('id', $dbRow)) {
  3771. $r['purchase_order_id'] = (int)$dbRow['id'];
  3772. }
  3773. if ($sid < 0) {
  3774. $r['_is_manual'] = 1;
  3775. }
  3776. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3777. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3778. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3779. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3780. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3781. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3782. $r['pick_time'] = $pickFallback;
  3783. break;
  3784. }
  3785. }
  3786. }
  3787. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3788. if ($pickNm !== '') {
  3789. $r['pick_company_name'] = $pickNm;
  3790. $r['picked_supplier_name'] = $pickNm;
  3791. }
  3792. return $r;
  3793. }
  3794. /**
  3795. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3796. *
  3797. * @return array<int, array<string, mixed>>
  3798. */
  3799. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3800. {
  3801. $pool = [];
  3802. if (!is_array($dbRows) || $dbRows === []) {
  3803. return $pool;
  3804. }
  3805. $dStampMap = [];
  3806. $sidList = [];
  3807. foreach ($dbRows as $tmpRow) {
  3808. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3809. $sid = (int)$tmpRow['scydgy_id'];
  3810. if ($sid > 0) {
  3811. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3812. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3813. $sidList[$sid] = true;
  3814. }
  3815. }
  3816. }
  3817. }
  3818. if ($sidList !== []) {
  3819. try {
  3820. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3821. } catch (\Throwable $e) {
  3822. $dStampMap = [];
  3823. }
  3824. }
  3825. foreach ($dbRows as $dbRow) {
  3826. if (!is_array($dbRow)) {
  3827. continue;
  3828. }
  3829. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3830. }
  3831. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3832. $needCcydh = [];
  3833. foreach ($pool as $row) {
  3834. if (!is_array($row)) {
  3835. continue;
  3836. }
  3837. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3838. continue;
  3839. }
  3840. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3841. if ($ccydh !== '') {
  3842. $needCcydh[$ccydh] = true;
  3843. }
  3844. }
  3845. if ($needCcydh !== []) {
  3846. $czMap = [];
  3847. try {
  3848. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3849. } catch (\Throwable $e) {
  3850. $czMap = [];
  3851. }
  3852. if (is_array($czMap) && $czMap !== []) {
  3853. foreach ($pool as &$row) {
  3854. if (!is_array($row)) {
  3855. continue;
  3856. }
  3857. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3858. continue;
  3859. }
  3860. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3861. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3862. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3863. }
  3864. }
  3865. unset($row);
  3866. }
  3867. }
  3868. return $pool;
  3869. }
  3870. /**
  3871. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3872. *
  3873. * @param int[] $scydgyIds
  3874. * @return array<int, array<string, mixed>>
  3875. */
  3876. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3877. {
  3878. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3879. if ($scydgyIds === []) {
  3880. return [];
  3881. }
  3882. try {
  3883. $list = Db::table('purchase_order_detail')
  3884. ->where('scydgy_id', 'in', $scydgyIds)
  3885. ->field('scydgy_id,company_name,amount,delivery')
  3886. ->select();
  3887. } catch (\Throwable $e) {
  3888. $list = [];
  3889. }
  3890. return is_array($list) ? $list : [];
  3891. }
  3892. /**
  3893. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3894. *
  3895. * @param int[] $scydgyIds
  3896. * @param array<int, array<string, mixed>> $allRows
  3897. * @return array{cnt:int, amt:int, deliv:int}
  3898. */
  3899. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3900. {
  3901. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3902. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3903. if ($scydgyIds === [] || $allRows === []) {
  3904. return $out;
  3905. }
  3906. $idSet = array_flip($scydgyIds);
  3907. $all = [];
  3908. $withAmt = [];
  3909. $withDeliv = [];
  3910. foreach ($allRows as $r) {
  3911. if (!is_array($r)) {
  3912. continue;
  3913. }
  3914. $sid = (int)($r['scydgy_id'] ?? 0);
  3915. if (!isset($idSet[$sid])) {
  3916. continue;
  3917. }
  3918. $cn = trim((string)($r['company_name'] ?? ''));
  3919. if ($cn === '') {
  3920. continue;
  3921. }
  3922. $all[$cn] = true;
  3923. $am = $r['amount'] ?? null;
  3924. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3925. $withAmt[$cn] = true;
  3926. }
  3927. $dv = $r['delivery'] ?? null;
  3928. if ($dv !== null && trim((string)$dv) !== '') {
  3929. $withDeliv[$cn] = true;
  3930. }
  3931. }
  3932. return [
  3933. 'cnt' => count($all),
  3934. 'amt' => count($withAmt),
  3935. 'deliv' => count($withDeliv),
  3936. ];
  3937. }
  3938. /**
  3939. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  3940. *
  3941. * @param array<string, mixed> $row
  3942. */
  3943. protected function resolveProcuremenThisQuantity(array $row): string
  3944. {
  3945. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  3946. if ($q !== '') {
  3947. return $q;
  3948. }
  3949. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  3950. if (!is_scalar($ngzl)) {
  3951. return '';
  3952. }
  3953. $s = trim((string)$ngzl);
  3954. if ($s === '') {
  3955. return '';
  3956. }
  3957. if (is_numeric($s) && (float)$s === 0.0) {
  3958. return '';
  3959. }
  3960. return $s;
  3961. }
  3962. /**
  3963. * @param array<string, mixed> $row
  3964. */
  3965. protected function resolveProcuremenCeilingPrice(array $row): string
  3966. {
  3967. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  3968. }
  3969. /**
  3970. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  3971. *
  3972. * @param array<int, mixed> $parts
  3973. */
  3974. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  3975. {
  3976. $out = [];
  3977. foreach ($parts as $p) {
  3978. $s = trim((string)$p);
  3979. if ($s !== '') {
  3980. $out[] = $s;
  3981. }
  3982. }
  3983. return $out === [] ? '' : implode($sep, $out);
  3984. }
  3985. /**
  3986. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  3987. *
  3988. * @param array<int, array<string, mixed>> $rows
  3989. */
  3990. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  3991. {
  3992. if ($rows === []) {
  3993. return;
  3994. }
  3995. $idList = [];
  3996. foreach ($rows as $rw) {
  3997. if (!is_array($rw)) {
  3998. continue;
  3999. }
  4000. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4001. foreach ($rw['_order_merge_rows'] as $mr) {
  4002. if (!is_array($mr)) {
  4003. continue;
  4004. }
  4005. $mid = (int)($mr['ID'] ?? 0);
  4006. if ($this->isValidScydgyRowId($mid)) {
  4007. $idList[$mid] = true;
  4008. }
  4009. }
  4010. }
  4011. $id = (int)($rw['ID'] ?? 0);
  4012. if ($this->isValidScydgyRowId($id)) {
  4013. $idList[$id] = true;
  4014. }
  4015. }
  4016. if ($idList === []) {
  4017. return;
  4018. }
  4019. try {
  4020. $list = Db::table('purchase_order')
  4021. ->where('scydgy_id', 'in', array_keys($idList))
  4022. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4023. ->select();
  4024. } catch (\Throwable $e) {
  4025. return;
  4026. }
  4027. if (!is_array($list)) {
  4028. return;
  4029. }
  4030. $byId = [];
  4031. foreach ($list as $dbRow) {
  4032. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4033. continue;
  4034. }
  4035. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4036. }
  4037. foreach ($rows as &$rw) {
  4038. if (!is_array($rw)) {
  4039. continue;
  4040. }
  4041. $mergeRows = [];
  4042. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4043. $mergeRows = $rw['_order_merge_rows'];
  4044. } else {
  4045. $mergeRows = [$rw];
  4046. }
  4047. $qtyList = [];
  4048. $priceList = [];
  4049. $picked = '';
  4050. foreach ($mergeRows as $mr) {
  4051. if (!is_array($mr)) {
  4052. continue;
  4053. }
  4054. $sid = (int)($mr['ID'] ?? 0);
  4055. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4056. $src = $mr;
  4057. if (is_array($db)) {
  4058. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4059. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4060. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4061. if ($qDb !== '') {
  4062. $src['This_quantity'] = $qDb;
  4063. }
  4064. if ($pDb !== '') {
  4065. $src['ceilingPrice'] = $pDb;
  4066. }
  4067. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4068. $src['NGZL'] = $ngzlDb;
  4069. }
  4070. if ($picked === '') {
  4071. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4072. }
  4073. }
  4074. if ($picked === '') {
  4075. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4076. }
  4077. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4078. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4079. }
  4080. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4081. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4082. if ($picked !== '') {
  4083. $rw['pick_company_name'] = $picked;
  4084. $rw['picked_supplier_name'] = $picked;
  4085. }
  4086. }
  4087. unset($rw);
  4088. }
  4089. /**
  4090. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4091. *
  4092. * @param int[] $scydgyIds
  4093. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4094. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4095. */
  4096. protected function OrderDetailSummary(array $scydgyIds)
  4097. {
  4098. $out = [];
  4099. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4100. if ($scydgyIds === []) {
  4101. return $out;
  4102. }
  4103. $list = [];
  4104. try {
  4105. $list = Db::table('purchase_order_detail')
  4106. ->where('scydgy_id', 'in', $scydgyIds)
  4107. ->field('id,scydgy_id,amount,delivery')
  4108. ->select();
  4109. } catch (\Throwable $e) {
  4110. $list = [];
  4111. }
  4112. if (!is_array($list)) {
  4113. return $out;
  4114. }
  4115. foreach ($list as $r) {
  4116. if (!is_array($r)) {
  4117. continue;
  4118. }
  4119. $ids = (int)($r['scydgy_id'] ?? 0);
  4120. if (!$this->isValidScydgyRowId($ids)) {
  4121. continue;
  4122. }
  4123. if (!isset($out[$ids])) {
  4124. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4125. }
  4126. $out[$ids]['cnt']++;
  4127. $am = $r['amount'] ?? null;
  4128. if ($am !== null && $am !== '') {
  4129. if (!(is_string($am) && trim($am) === '')) {
  4130. $out[$ids]['amt']++;
  4131. }
  4132. }
  4133. $dv = $r['delivery'] ?? null;
  4134. if ($dv !== null && trim((string)$dv) !== '') {
  4135. $out[$ids]['deliv']++;
  4136. }
  4137. }
  4138. return $out;
  4139. }
  4140. /**
  4141. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4142. *
  4143. * @return array
  4144. */
  4145. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4146. {
  4147. $strContains = function ($haystack, $needle) {
  4148. if ($needle === '') {
  4149. return false;
  4150. }
  4151. $haystack = (string)$haystack;
  4152. if (function_exists('mb_stripos')) {
  4153. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4154. }
  4155. return stripos($haystack, $needle) !== false;
  4156. };
  4157. $stripAlias = function ($f) {
  4158. return preg_replace('/^[ab]\./i', '', (string)$f);
  4159. };
  4160. $searchColNames = [];
  4161. foreach (explode(',', $this->searchFields) as $colRaw) {
  4162. $c = $stripAlias(trim($colRaw));
  4163. if ($c !== '') {
  4164. $searchColNames[] = $c;
  4165. }
  4166. }
  4167. // 等值条件先行(表头下拉),减少后续日期解析量
  4168. $eqFilters = [];
  4169. $otherFilters = [];
  4170. foreach ($filterArr as $fk => $fv) {
  4171. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4172. continue;
  4173. }
  4174. if (is_array($fv)) {
  4175. continue;
  4176. }
  4177. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4178. continue;
  4179. }
  4180. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4181. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4182. $field = $stripAlias($fk);
  4183. if ($sym === '=' || $sym === '') {
  4184. $eqFilters[$field] = trim((string)$fv);
  4185. } else {
  4186. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4187. }
  4188. }
  4189. $ymTarget = '';
  4190. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4191. $ymTarget = $ymM[1];
  4192. }
  4193. $filtered = [];
  4194. foreach ($pool as $r) {
  4195. if (!is_array($r)) {
  4196. continue;
  4197. }
  4198. foreach ($eqFilters as $field => $fv) {
  4199. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4200. continue 2;
  4201. }
  4202. }
  4203. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4204. // 初选池不应含手工单;若混入则直接剔除
  4205. if ($isManual) {
  4206. continue;
  4207. }
  4208. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4209. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4210. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4211. continue;
  4212. }
  4213. if ($applyMonthRange) {
  4214. $mo = (int)$m[2];
  4215. if ($mo < 1 || $mo > 12) {
  4216. continue;
  4217. }
  4218. if ($ymTarget !== '') {
  4219. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4220. if ($ymRow !== $ymTarget) {
  4221. continue;
  4222. }
  4223. } else {
  4224. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4225. $rowMonthStart = $ymRow . '-01 00:00:00';
  4226. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4227. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4228. continue;
  4229. }
  4230. }
  4231. }
  4232. if ($search !== '') {
  4233. $hitSearch = false;
  4234. foreach ($searchColNames as $c) {
  4235. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4236. if ($cell !== '' && $strContains($cell, $search)) {
  4237. $hitSearch = true;
  4238. break;
  4239. }
  4240. }
  4241. if (!$hitSearch) {
  4242. continue;
  4243. }
  4244. }
  4245. foreach ($otherFilters as $item) {
  4246. $fv = $item['fv'];
  4247. $sym = $item['sym'];
  4248. $field = $item['field'];
  4249. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4250. $cellStr = trim((string)$cell);
  4251. switch ($sym) {
  4252. case '<>':
  4253. if ((string)$cell === (string)$fv) {
  4254. continue 3;
  4255. }
  4256. break;
  4257. case 'LIKE':
  4258. case 'NOT LIKE':
  4259. $needle = trim((string)$fv);
  4260. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4261. if ($sym === 'LIKE' && !$hit) {
  4262. continue 3;
  4263. }
  4264. if ($sym === 'NOT LIKE' && $hit) {
  4265. continue 3;
  4266. }
  4267. break;
  4268. case 'BETWEEN':
  4269. case 'RANGE':
  4270. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4271. if (count($parts) < 2) {
  4272. $parts = is_string($fv) ? explode(',', $fv) : [];
  4273. }
  4274. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4275. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4276. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4277. continue 3;
  4278. }
  4279. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4280. continue 3;
  4281. }
  4282. break;
  4283. case '>':
  4284. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4285. continue 3;
  4286. }
  4287. break;
  4288. case '>=':
  4289. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4290. continue 3;
  4291. }
  4292. break;
  4293. case '<':
  4294. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4295. continue 3;
  4296. }
  4297. break;
  4298. case '<=':
  4299. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4300. continue 3;
  4301. }
  4302. break;
  4303. default:
  4304. if ((string)$cell !== (string)$fv) {
  4305. continue 3;
  4306. }
  4307. break;
  4308. }
  4309. }
  4310. $filtered[] = $r;
  4311. }
  4312. return $filtered;
  4313. }
  4314. /**
  4315. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4316. */
  4317. public function snapshotToProcure()
  4318. {
  4319. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4320. $this->error(__('Invalid parameters'));
  4321. }
  4322. $row = json_decode($this->request->post('row_json', ''), true);
  4323. if (!is_array($row)) {
  4324. $this->error(__('Invalid parameters'));
  4325. }
  4326. try {
  4327. $ids = $this->extractScydgyRowId($row);
  4328. if (!$this->isValidScydgyRowId($ids)) {
  4329. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4330. }
  4331. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4332. $data = [
  4333. 'scydgy_id' => $ids,
  4334. 'CCYDH' => $row['CCYDH'] ?? null,
  4335. 'CYJMC' => $row['CYJMC'] ?? null,
  4336. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4337. 'CDXMC' => $row['CDXMC'] ?? null,
  4338. 'CGYBH' => $row['CGYBH'] ?? null,
  4339. 'CGYMC' => $row['CGYMC'] ?? null,
  4340. 'CDW' => $row['CDW'] ?? null,
  4341. 'czlyq' => $row['czlyq'] ?? null,
  4342. 'NGZL' => $row['NGZL'] ?? null,
  4343. 'CDF' => $row['CDF'] ?? null,
  4344. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4345. 'MBZ' => $row['MBZ'] ?? null,
  4346. 'bwjg' => $row['bwjg'] ?? null,
  4347. 'iStatus' => $row['iStatus'] ?? null,
  4348. 'dStamp' => $row['dStamp'] ?? null,
  4349. 'dputrecord' => $row['dputrecord'] ?? null,
  4350. 'cywyxm' => $row['cywyxm'] ?? null,
  4351. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4352. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4353. ];
  4354. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4355. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4356. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  4357. $this->success('操作成功');
  4358. return;
  4359. }
  4360. if ($exists) {
  4361. $upd = $data;
  4362. unset($upd['scydgy_id'], $upd['status']);
  4363. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4364. } else {
  4365. // 新增:不写 status(空/走库默认);仅写创建时间
  4366. $data['createtime'] = date('Y-m-d H:i:s');
  4367. Db::table('purchase_order')->insert($data);
  4368. }
  4369. } catch (\Throwable $e) {
  4370. $this->error($e->getMessage());
  4371. }
  4372. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4373. $this->success('操作成功');
  4374. }
  4375. /**
  4376. * 未发列表
  4377. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  4378. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4379. */
  4380. public function completeDirectly()
  4381. {
  4382. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4383. $this->error(__('参数错误'));
  4384. }
  4385. if (!$this->procuremenCanComplete()) {
  4386. $this->error(__('You have no permission'));
  4387. }
  4388. $row = json_decode($this->request->post('row_json', ''), true);
  4389. if (!is_array($row)) {
  4390. $this->error(__('Invalid parameters'));
  4391. }
  4392. $finishRaw = $this->request->post('finish', '1');
  4393. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4394. $poIdLog = null;
  4395. try {
  4396. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4397. $ids = $this->extractScydgyRowId($row);
  4398. if (!$this->isValidScydgyRowId($ids)) {
  4399. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4400. }
  4401. if ($asComplete) {
  4402. $this->assertPickRowCanComplete($ids, $row);
  4403. }
  4404. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4405. $data = [
  4406. 'scydgy_id' => $ids,
  4407. 'CCYDH' => $row['CCYDH'] ?? null,
  4408. 'CYJMC' => $row['CYJMC'] ?? null,
  4409. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4410. 'CDXMC' => $row['CDXMC'] ?? null,
  4411. 'CGYBH' => $row['CGYBH'] ?? null,
  4412. 'CGYMC' => $row['CGYMC'] ?? null,
  4413. 'CDW' => $row['CDW'] ?? null,
  4414. 'czlyq' => $row['czlyq'] ?? null,
  4415. 'NGZL' => $row['NGZL'] ?? null,
  4416. 'CDF' => $row['CDF'] ?? null,
  4417. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4418. 'MBZ' => $row['MBZ'] ?? null,
  4419. 'bwjg' => $row['bwjg'] ?? null,
  4420. 'iStatus' => $row['iStatus'] ?? null,
  4421. 'dStamp' => $row['dStamp'] ?? null,
  4422. 'dputrecord' => $row['dputrecord'] ?? null,
  4423. 'cywyxm' => $row['cywyxm'] ?? null,
  4424. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4425. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4426. ];
  4427. if ($asComplete) {
  4428. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4429. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4430. }
  4431. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4432. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4433. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  4434. $this->success('操作成功');
  4435. return;
  4436. }
  4437. if ($exists) {
  4438. $upd = $data;
  4439. unset($upd['scydgy_id']);
  4440. if (!$asComplete) {
  4441. unset($upd['status']);
  4442. }
  4443. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4444. } else {
  4445. // 新增:不写 status;完结时 $data 已含 status=1
  4446. $data['createtime'] = date('Y-m-d H:i:s');
  4447. Db::table('purchase_order')->insert($data);
  4448. }
  4449. } catch (\Throwable $e) {
  4450. $this->error($e->getMessage());
  4451. }
  4452. try {
  4453. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4454. if (is_array($rpo)) {
  4455. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4456. $poIdLog = $tid > 0 ? $tid : null;
  4457. }
  4458. } catch (\Throwable $e) {
  4459. $poIdLog = null;
  4460. }
  4461. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4462. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4463. if ($asComplete) {
  4464. $this->addOrderLog(
  4465. $ids,
  4466. 'mark_complete',
  4467. '点击「完结」,已标记为已完结',
  4468. $poIdLog
  4469. );
  4470. try {
  4471. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4472. if ($pdfPublicPath === '') {
  4473. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4474. }
  4475. } catch (\Throwable $e) {
  4476. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4477. }
  4478. } else {
  4479. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4480. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4481. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4482. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  4483. $this->addOrderLog(
  4484. $ids,
  4485. 'save_qty_price',
  4486. '保存本次数量、最高限价:' . $detail,
  4487. $poIdLog
  4488. );
  4489. }
  4490. $this->pickHiddenScydgySetCache = null;
  4491. $this->success("操作成功");
  4492. }
  4493. /**
  4494. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  4495. *
  4496. * @param array<int, array> $rows 引用传递当前页行
  4497. */
  4498. protected function mergePurchaseOrder(array &$rows)
  4499. {
  4500. if ($rows === []) {
  4501. return;
  4502. }
  4503. $ids = [];
  4504. foreach ($rows as $rw) {
  4505. if (!is_array($rw)) {
  4506. continue;
  4507. }
  4508. $id = (int)($rw['ID'] ?? 0);
  4509. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4510. if ($this->isValidScydgyRowId($id)) {
  4511. $ids[$id] = true;
  4512. }
  4513. }
  4514. $idList = array_keys($ids);
  4515. if ($idList === []) {
  4516. return;
  4517. }
  4518. try {
  4519. $list = Db::table('purchase_order')
  4520. ->where('scydgy_id', 'in', $idList)
  4521. ->field('scydgy_id,This_quantity,ceilingPrice')
  4522. ->select();
  4523. } catch (\Throwable $e) {
  4524. return;
  4525. }
  4526. if (!is_array($list)) {
  4527. return;
  4528. }
  4529. $byId = [];
  4530. foreach ($list as $dbRow) {
  4531. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4532. continue;
  4533. }
  4534. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4535. }
  4536. foreach ($rows as &$rw) {
  4537. if (!is_array($rw)) {
  4538. continue;
  4539. }
  4540. $sid = (int)($rw['ID'] ?? 0);
  4541. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4542. continue;
  4543. }
  4544. $db = $byId[$sid];
  4545. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  4546. if (array_key_exists('This_quantity', $db)) {
  4547. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4548. }
  4549. if (array_key_exists('ceilingPrice', $db)) {
  4550. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4551. } elseif (array_key_exists('ceiling_price', $db)) {
  4552. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4553. }
  4554. }
  4555. unset($rw);
  4556. }
  4557. /**
  4558. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4559. */
  4560. public function purchaseConfirmPick()
  4561. {
  4562. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4563. $this->error(__('Invalid parameters'));
  4564. }
  4565. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4566. $this->error(__('You have no permission'));
  4567. }
  4568. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4569. if ($batchRaw !== '') {
  4570. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4571. return;
  4572. }
  4573. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4574. $sid = (int)$scydgyId;
  4575. if (!$this->isValidScydgyRowId($sid)) {
  4576. $this->error('参数无效');
  4577. }
  4578. $parseIdList = function ($raw) {
  4579. if (is_array($raw)) {
  4580. $arr = $raw;
  4581. } else {
  4582. $decoded = json_decode((string)$raw, true);
  4583. $arr = is_array($decoded) ? $decoded : [];
  4584. }
  4585. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4586. };
  4587. $selectedRaw = $this->request->post('selected_ids', null);
  4588. if ($selectedRaw === null || $selectedRaw === '') {
  4589. $legacy = (int)$this->request->post('selected_id', 0);
  4590. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4591. } else {
  4592. $selectedIds = $parseIdList($selectedRaw);
  4593. }
  4594. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4595. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4596. try {
  4597. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4598. } catch (\InvalidArgumentException $e) {
  4599. $this->error($e->getMessage());
  4600. } catch (\Throwable $e) {
  4601. $this->error($e->getMessage());
  4602. }
  4603. $this->pickHiddenScydgySetCache = null;
  4604. $this->success('操作成功', '', $result);
  4605. }
  4606. /**
  4607. * 整单采购确认(多道工序一次提交)
  4608. */
  4609. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4610. {
  4611. $decoded = json_decode($batchRaw, true);
  4612. if (!is_array($decoded) || $decoded === []) {
  4613. $this->error('提交数据无效');
  4614. }
  4615. $picks = [];
  4616. foreach ($decoded as $item) {
  4617. if (!is_array($item)) {
  4618. continue;
  4619. }
  4620. $sid = (int)($item['scydgy_id'] ?? 0);
  4621. if (!$this->isValidScydgyRowId($sid)) {
  4622. continue;
  4623. }
  4624. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4625. if (!is_array($sel)) {
  4626. $sel = [(int)$sel];
  4627. }
  4628. $unsel = $item['unselected_ids'] ?? [];
  4629. if (!is_array($unsel)) {
  4630. $unsel = json_decode((string)$unsel, true);
  4631. $unsel = is_array($unsel) ? $unsel : [];
  4632. }
  4633. $picks[] = [
  4634. 'scydgy_id' => $sid,
  4635. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4636. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4637. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4638. ];
  4639. }
  4640. if ($picks === []) {
  4641. $this->error('提交数据无效');
  4642. }
  4643. Db::startTrans();
  4644. $results = [];
  4645. try {
  4646. foreach ($picks as $pick) {
  4647. $results[] = $this->runPurchaseConfirmPick(
  4648. (int)$pick['scydgy_id'],
  4649. $pick['selected_ids'],
  4650. $pick['unselected_ids'],
  4651. (int)$pick['purchase_order_id'],
  4652. false,
  4653. false
  4654. );
  4655. }
  4656. Db::commit();
  4657. } catch (\Throwable $e) {
  4658. Db::rollback();
  4659. $msg = $e->getMessage();
  4660. $this->error($msg !== '' ? $msg : '提交失败');
  4661. }
  4662. try {
  4663. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4664. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4665. } catch (\Throwable $e) {
  4666. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  4667. }
  4668. $this->pickHiddenScydgySetCache = null;
  4669. $this->success('操作成功', '', ['batch' => $results]);
  4670. }
  4671. /**
  4672. * @return array<string, mixed>
  4673. */
  4674. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4675. {
  4676. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4677. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4678. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4679. $scydgyId = (string)$sid;
  4680. if ($selectedIds === []) {
  4681. throw new \InvalidArgumentException('请至少勾选一条明细');
  4682. }
  4683. $inter = array_intersect($selectedIds, $unselectedIds);
  4684. if ($inter !== []) {
  4685. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4686. }
  4687. $allIds = $this->purchaseOrderDetail($sid);
  4688. if ($allIds === []) {
  4689. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4690. }
  4691. foreach ($selectedIds as $id) {
  4692. if (!in_array($id, $allIds, true)) {
  4693. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4694. }
  4695. }
  4696. foreach ($unselectedIds as $id) {
  4697. if (!in_array($id, $allIds, true)) {
  4698. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4699. }
  4700. }
  4701. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4702. sort($union, SORT_NUMERIC);
  4703. $expect = $allIds;
  4704. sort($expect, SORT_NUMERIC);
  4705. if ($union !== $expect) {
  4706. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4707. }
  4708. if ($manageTransaction) {
  4709. Db::startTrans();
  4710. }
  4711. try {
  4712. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4713. $aff = 0;
  4714. try {
  4715. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4716. } catch (\Throwable $e) {
  4717. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4718. }
  4719. if ($aff < 1) {
  4720. throw new \Exception('更新选中状态失败');
  4721. }
  4722. $poPayload = [
  4723. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4724. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4725. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4726. ];
  4727. if ($purchaseOrderId > 0) {
  4728. $poAff = (int)Db::table('purchase_order')
  4729. ->where('id', $purchaseOrderId)
  4730. ->where('scydgy_id', $sid)
  4731. ->update($poPayload);
  4732. if ($poAff < 1) {
  4733. throw new \Exception('主表订单不存在或与工序行不匹配');
  4734. }
  4735. } else {
  4736. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4737. if ($poAff < 1) {
  4738. throw new \Exception('未找到');
  4739. }
  4740. }
  4741. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4742. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4743. if ($manageTransaction) {
  4744. Db::commit();
  4745. }
  4746. } catch (\Throwable $e) {
  4747. if ($manageTransaction) {
  4748. Db::rollback();
  4749. }
  4750. throw $e;
  4751. }
  4752. $poIdFinal = $purchaseOrderId;
  4753. if ($poIdFinal <= 0) {
  4754. try {
  4755. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4756. if (is_array($rpo)) {
  4757. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4758. }
  4759. } catch (\Throwable $e) {
  4760. $poIdFinal = 0;
  4761. }
  4762. }
  4763. $pickNames = [];
  4764. foreach ($selectedIds as $pid) {
  4765. $dr = $this->purchaseOrderDetai($sid, $pid);
  4766. $nm = trim((string)($dr['company_name'] ?? ''));
  4767. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4768. }
  4769. $this->addOrderLog(
  4770. $sid,
  4771. 'purchase_confirm',
  4772. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4773. $poIdFinal > 0 ? $poIdFinal : null
  4774. );
  4775. if ($sendNotifications) {
  4776. try {
  4777. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4778. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4779. 'scydgy_id' => $sid,
  4780. 'selected_ids' => $selectedIds,
  4781. 'unselected_ids' => $unselectedIds,
  4782. 'purchase_order_id' => $purchaseOrderId,
  4783. ]]);
  4784. } catch (\Throwable $e) {
  4785. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4786. }
  4787. }
  4788. Log::write(sprintf(
  4789. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4790. $scydgyId,
  4791. $purchaseOrderId,
  4792. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4793. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4794. ), 'notice');
  4795. $pdfPublicPath = '';
  4796. try {
  4797. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4798. } catch (\Throwable $e) {
  4799. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4800. }
  4801. return [
  4802. 'scydgy_id' => $scydgyId,
  4803. 'purchase_order_id' => $purchaseOrderId,
  4804. 'selected_ids' => $selectedIds,
  4805. 'unselected_ids' => $unselectedIds,
  4806. 'purchase_confirm_pdf' => $pdfPublicPath,
  4807. ];
  4808. }
  4809. /**
  4810. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4811. *
  4812. * @param int[]|string[] $scydgyIds
  4813. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4814. */
  4815. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4816. {
  4817. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4818. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4819. if ($scydgyIds === []) {
  4820. return $empty;
  4821. }
  4822. $pos = [];
  4823. try {
  4824. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4825. } catch (\Throwable $e) {
  4826. $rows = [];
  4827. }
  4828. if (is_array($rows)) {
  4829. foreach ($rows as $po) {
  4830. if (is_array($po)) {
  4831. $pos[] = $po;
  4832. }
  4833. }
  4834. }
  4835. if ($pos === []) {
  4836. return $empty;
  4837. }
  4838. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4839. return [
  4840. 'ccydh' => $ccydh,
  4841. 'pos' => $pos,
  4842. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4843. ];
  4844. }
  4845. /**
  4846. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  4847. *
  4848. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4849. * @param array<int, array<string, mixed>> $picks
  4850. */
  4851. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4852. {
  4853. if ($picks === []) {
  4854. return;
  4855. }
  4856. $fallbackDetailId = 0;
  4857. $winners = [];
  4858. $losers = [];
  4859. foreach ($picks as $pick) {
  4860. if (!is_array($pick)) {
  4861. continue;
  4862. }
  4863. $sid = (int)($pick['scydgy_id'] ?? 0);
  4864. if (!$this->isValidScydgyRowId($sid)) {
  4865. continue;
  4866. }
  4867. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4868. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4869. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4870. $fallbackDetailId = (int)$selectedIds[0];
  4871. }
  4872. foreach ($selectedIds as $pid) {
  4873. $dr = $this->purchaseOrderDetai($sid, $pid);
  4874. if (!is_array($dr)) {
  4875. continue;
  4876. }
  4877. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4878. }
  4879. foreach ($unselectedIds as $pid) {
  4880. $dr = $this->purchaseOrderDetai($sid, $pid);
  4881. if (!is_array($dr)) {
  4882. continue;
  4883. }
  4884. $key = $this->notifySupplierDedupeKey($dr);
  4885. if (!isset($winners[$key])) {
  4886. $losers[$key] = $dr;
  4887. }
  4888. }
  4889. }
  4890. if ($winners === [] && $losers === []) {
  4891. return;
  4892. }
  4893. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4894. $sendSmsSafe = function ($phone, $content) {
  4895. $phone = trim((string)$phone);
  4896. if ($phone === '') {
  4897. return;
  4898. }
  4899. try {
  4900. $this->smsbao($phone, $content);
  4901. } catch (\Throwable $e) {
  4902. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4903. }
  4904. };
  4905. foreach ($winners as $dr) {
  4906. $cname = trim((string)($dr['company_name'] ?? ''));
  4907. $ph = trim((string)($dr['phone'] ?? ''));
  4908. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  4909. 'company_name' => $cname,
  4910. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4911. 'phone' => $ph,
  4912. ]));
  4913. $sendSmsSafe($ph, $sms);
  4914. }
  4915. foreach ($losers as $dr) {
  4916. $cname = trim((string)($dr['company_name'] ?? ''));
  4917. $ph = trim((string)($dr['phone'] ?? ''));
  4918. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  4919. 'company_name' => $cname,
  4920. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4921. 'phone' => $ph,
  4922. ]));
  4923. $sendSmsSafe($ph, $sms);
  4924. }
  4925. }
  4926. /**
  4927. * 短信去重键:优先手机号,否则公司名
  4928. */
  4929. protected function notifySupplierDedupeKey(array $detailRow): string
  4930. {
  4931. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  4932. if ($ph !== '') {
  4933. return 'p:' . $ph;
  4934. }
  4935. $cn = trim((string)($detailRow['company_name'] ?? ''));
  4936. return 'c:' . $cn;
  4937. }
  4938. /**
  4939. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  4940. *
  4941. * @param int[] $detailIds
  4942. */
  4943. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  4944. {
  4945. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  4946. if ($detailIds === []) {
  4947. return;
  4948. }
  4949. $payload = ['status_name' => $statusName];
  4950. try {
  4951. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  4952. } catch (\Throwable $e) {
  4953. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  4954. }
  4955. }
  4956. /**
  4957. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  4958. */
  4959. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  4960. {
  4961. try {
  4962. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  4963. } catch (\Throwable $e) {
  4964. return;
  4965. }
  4966. if (!is_array($rows)) {
  4967. return;
  4968. }
  4969. foreach ($rows as $dr) {
  4970. if (!is_array($dr)) {
  4971. continue;
  4972. }
  4973. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4974. if ($id <= 0) {
  4975. continue;
  4976. }
  4977. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  4978. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  4979. try {
  4980. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  4981. } catch (\Throwable $e) {
  4982. }
  4983. }
  4984. }
  4985. /**
  4986. * @param array<string, mixed> $detailRow
  4987. */
  4988. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  4989. {
  4990. $am = $detailRow['amount'] ?? null;
  4991. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  4992. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  4993. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  4994. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  4995. }
  4996. /**
  4997. * @return int[]
  4998. */
  4999. protected function purchaseOrderDetail(int $scydgyId): array
  5000. {
  5001. if (!$this->isValidScydgyRowId($scydgyId)) {
  5002. return [];
  5003. }
  5004. try {
  5005. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5006. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5007. $list = $listQuery->select();
  5008. } catch (\Throwable $e) {
  5009. return [];
  5010. }
  5011. if (!is_array($list)) {
  5012. return [];
  5013. }
  5014. $ids = [];
  5015. foreach ($list as $r) {
  5016. if (!is_array($r)) {
  5017. continue;
  5018. }
  5019. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5020. if ($pk > 0) {
  5021. $ids[] = $pk;
  5022. }
  5023. }
  5024. return array_values(array_unique($ids));
  5025. }
  5026. /**
  5027. * 获取当前登录用户信息 [id, 展示名]
  5028. */
  5029. protected function GetUseName(): array
  5030. {
  5031. $id = 0;
  5032. $name = '';
  5033. try {
  5034. if ($this->auth && $this->auth->isLogin()) {
  5035. $u = $this->auth->getUserInfo();
  5036. if (is_array($u)) {
  5037. $id = (int)($u['id'] ?? 0);
  5038. $name = trim((string)($u['nickname'] ?? ''));
  5039. if ($name === '') {
  5040. $name = trim((string)($u['username'] ?? ''));
  5041. }
  5042. }
  5043. }
  5044. } catch (\Throwable $e) {
  5045. }
  5046. if ($name === '') {
  5047. $name = '未知用户';
  5048. }
  5049. return [$id, $name];
  5050. }
  5051. /**
  5052. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5053. */
  5054. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5055. {
  5056. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5057. }
  5058. /**
  5059. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5060. *
  5061. * @param array<int, array<string, mixed>> $rows
  5062. */
  5063. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5064. {
  5065. $sidList = [];
  5066. foreach ($rows as $rw) {
  5067. if (!is_array($rw)) {
  5068. continue;
  5069. }
  5070. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5071. foreach ($rw['_order_merge_rows'] as $mr) {
  5072. $mid = (int)($mr['ID'] ?? 0);
  5073. if ($this->isValidScydgyRowId($mid)) {
  5074. $sidList[$mid] = true;
  5075. }
  5076. }
  5077. }
  5078. $id = (int)($rw['ID'] ?? 0);
  5079. if ($this->isValidScydgyRowId($id)) {
  5080. $sidList[$id] = true;
  5081. }
  5082. }
  5083. $sids = array_keys($sidList);
  5084. $issueBySid = [];
  5085. $confirmBySid = [];
  5086. $approveBySid = [];
  5087. if ($sids !== []) {
  5088. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5089. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5090. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5091. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5092. try {
  5093. $logs = Db::table('purchase_order_oper_log')
  5094. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5095. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5096. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5097. ->order('id', 'asc')
  5098. ->select();
  5099. } catch (\Throwable $e) {
  5100. $logs = [];
  5101. }
  5102. if (is_array($logs)) {
  5103. $issueSet = array_fill_keys($issueActs, true);
  5104. $confirmSet = array_fill_keys($confirmActs, true);
  5105. $approveSet = array_fill_keys($approveActs, true);
  5106. foreach ($logs as $lg) {
  5107. if (!is_array($lg)) {
  5108. continue;
  5109. }
  5110. $lg = ProcuremenOperLog::normalizeRow($lg);
  5111. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5112. if ($sid === 0) {
  5113. continue;
  5114. }
  5115. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5116. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5117. if ($t === '') {
  5118. continue;
  5119. }
  5120. if (isset($issueSet[$action])) {
  5121. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5122. $issueBySid[$sid] = $t;
  5123. }
  5124. }
  5125. if (isset($confirmSet[$action])) {
  5126. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5127. $confirmBySid[$sid] = $t;
  5128. }
  5129. }
  5130. if (isset($approveSet[$action])) {
  5131. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5132. $approveBySid[$sid] = $t;
  5133. }
  5134. }
  5135. }
  5136. }
  5137. }
  5138. foreach ($rows as &$rw) {
  5139. if (!is_array($rw)) {
  5140. continue;
  5141. }
  5142. $mergeSids = [];
  5143. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5144. foreach ($rw['_order_merge_rows'] as $mr) {
  5145. $mid = (int)($mr['ID'] ?? 0);
  5146. if ($this->isValidScydgyRowId($mid)) {
  5147. $mergeSids[] = $mid;
  5148. }
  5149. }
  5150. }
  5151. $rid = (int)($rw['ID'] ?? 0);
  5152. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5153. $mergeSids[] = $rid;
  5154. }
  5155. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5156. $issue = $pick;
  5157. $confirm = '';
  5158. $approve = '';
  5159. foreach ($mergeSids as $sid) {
  5160. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5161. $issue = $issueBySid[$sid];
  5162. }
  5163. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5164. $confirm = $confirmBySid[$sid];
  5165. }
  5166. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5167. $approve = $approveBySid[$sid];
  5168. }
  5169. }
  5170. if ($issue === '' && $pick !== '') {
  5171. $issue = $pick;
  5172. }
  5173. $rw['issue_time'] = $issue;
  5174. $rw['confirm_time'] = $confirm;
  5175. $rw['approve_time'] = $approve;
  5176. }
  5177. unset($rw);
  5178. }
  5179. /**
  5180. * 按主键取一条
  5181. */
  5182. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5183. {
  5184. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5185. return [];
  5186. }
  5187. try {
  5188. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5189. if (is_array($one)) {
  5190. return $one;
  5191. }
  5192. } catch (\Throwable $e) {
  5193. }
  5194. try {
  5195. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5196. if (is_array($one)) {
  5197. return $one;
  5198. }
  5199. } catch (\Throwable $e) {
  5200. }
  5201. return [];
  5202. }
  5203. /**
  5204. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5205. */
  5206. protected function formatProcuremenDetailTime($v): string
  5207. {
  5208. if ($v === null || $v === '') {
  5209. return '';
  5210. }
  5211. if (is_numeric($v) && (int)$v > 946684800) {
  5212. return date('Y-m-d H:i:s', (int)$v);
  5213. }
  5214. return ProcuremenTime::formatDisplayDateTime($v);
  5215. }
  5216. /**
  5217. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5218. */
  5219. protected function formatDeliveryYmd($v): string
  5220. {
  5221. if ($v === null || $v === '') {
  5222. return '';
  5223. }
  5224. $s = trim((string)$v);
  5225. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5226. return '';
  5227. }
  5228. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5229. return $m[1];
  5230. }
  5231. $ts = strtotime($s);
  5232. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5233. }
  5234. /**
  5235. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5236. */
  5237. protected function detailRowSupplierOperated(array $r): bool
  5238. {
  5239. $am = $r['amount'] ?? null;
  5240. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5241. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5242. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5243. return $okAmt || $okDel;
  5244. }
  5245. /**
  5246. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5247. */
  5248. protected function resolveDetailSupplierOperTime(array $r): string
  5249. {
  5250. if (!$this->detailRowSupplierOperated($r)) {
  5251. return '';
  5252. }
  5253. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5254. if ($t !== '') {
  5255. return $t;
  5256. }
  5257. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5258. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5259. continue;
  5260. }
  5261. $t = $this->formatProcuremenDetailTime($r[$col]);
  5262. if ($t !== '') {
  5263. return $t;
  5264. }
  5265. }
  5266. return '';
  5267. }
  5268. /**
  5269. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5270. */
  5271. protected function detailRowSupplierAccepted(array $r): bool
  5272. {
  5273. $am = $r['amount'] ?? null;
  5274. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5275. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5276. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5277. return $okAmt && $okDel;
  5278. }
  5279. /**
  5280. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5281. */
  5282. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5283. {
  5284. if ($detailCount > 0) {
  5285. return true;
  5286. }
  5287. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5288. return true;
  5289. }
  5290. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5291. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5292. return true;
  5293. }
  5294. return false;
  5295. }
  5296. /**
  5297. * 下发时间:优先 pick_time,其次首条下发明细时间
  5298. */
  5299. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5300. {
  5301. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5302. if ($issueTime !== '') {
  5303. return $issueTime;
  5304. }
  5305. foreach ($details as $dr) {
  5306. if (!is_array($dr)) {
  5307. continue;
  5308. }
  5309. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5310. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5311. $issueTime = $t;
  5312. }
  5313. }
  5314. if ($issueTime !== '') {
  5315. return $issueTime;
  5316. }
  5317. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5318. }
  5319. /**
  5320. * 直接点「完结」时间:优先操作记录 mark_complete
  5321. */
  5322. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5323. {
  5324. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5325. }
  5326. /**
  5327. * 操作记录时间(取指定 action 最近一条)
  5328. *
  5329. * @param string|array<int, string> $actions
  5330. */
  5331. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5332. {
  5333. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5334. }
  5335. /**
  5336. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5337. *
  5338. * @param array $main purchase_order 一行
  5339. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5340. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5341. */
  5342. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5343. {
  5344. $issueCnt = count($details);
  5345. $acceptCnt = 0;
  5346. $pickedName = '';
  5347. $pickedTime = '';
  5348. foreach ($details as $dr) {
  5349. if (!is_array($dr)) {
  5350. continue;
  5351. }
  5352. if ($this->detailRowSupplierAccepted($dr)) {
  5353. $acceptCnt++;
  5354. }
  5355. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5356. if ($pickedName === '') {
  5357. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5358. }
  5359. if ($pickedTime === '') {
  5360. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5361. if ($pickedTime === '') {
  5362. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5363. }
  5364. }
  5365. }
  5366. }
  5367. $hasMain = $main !== [];
  5368. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5369. if ($poTime === '') {
  5370. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5371. }
  5372. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5373. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5374. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5375. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5376. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5377. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5378. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5379. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5380. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5381. $inboundResult = '';
  5382. if ($scydgyId > 0) {
  5383. try {
  5384. $inRow = Db::table('purchase_order_inbound_score')
  5385. ->where('scydgy_id', $scydgyId)
  5386. ->field('result,updatetime,createtime')
  5387. ->find();
  5388. } catch (\Throwable $e) {
  5389. $inRow = null;
  5390. }
  5391. if (is_array($inRow) && $inRow !== []) {
  5392. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5393. if ($inboundScoreTime === '') {
  5394. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5395. }
  5396. }
  5397. }
  5398. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5399. $supplierTime = '';
  5400. if ($acceptCnt > 0) {
  5401. foreach ($details as $dr) {
  5402. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5403. continue;
  5404. }
  5405. $t = $this->resolveDetailSupplierOperTime($dr);
  5406. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5407. $supplierTime = $t;
  5408. }
  5409. }
  5410. }
  5411. $directComplete = ($mainCompleted && !$issued);
  5412. $doneTime = '';
  5413. if ($mainCompleted) {
  5414. if ($directComplete) {
  5415. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5416. }
  5417. if ($doneTime === '' && $inboundScoreTime !== '') {
  5418. $doneTime = $inboundScoreTime;
  5419. }
  5420. if ($doneTime === '') {
  5421. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5422. }
  5423. if ($doneTime === '') {
  5424. foreach ($details as $dr) {
  5425. if (!is_array($dr)) {
  5426. continue;
  5427. }
  5428. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5429. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5430. $doneTime = $t;
  5431. }
  5432. }
  5433. }
  5434. if ($doneTime === '') {
  5435. $doneTime = $poTime;
  5436. }
  5437. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5438. if ($doneTime === '' && $confirmApproveTime !== '') {
  5439. $doneTime = $confirmApproveTime;
  5440. }
  5441. }
  5442. if ($directComplete) {
  5443. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5444. $step1Done = $hasMain;
  5445. $step2Done = false;
  5446. $step3Done = false;
  5447. $step4Done = false;
  5448. $step5Done = false;
  5449. $stepInboundDone = $inboundScored;
  5450. $step6Done = $mainCompleted && $inboundScored;
  5451. } else {
  5452. $step1Done = $issued;
  5453. $step2Done = $issued;
  5454. $step3Done = $acceptCnt > 0;
  5455. $step4Done = $wflowPendingApproval;
  5456. if (!$step4Done) {
  5457. foreach ($details as $dr) {
  5458. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5459. $step4Done = true;
  5460. break;
  5461. }
  5462. }
  5463. }
  5464. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5465. $stepInboundDone = $inboundScored;
  5466. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5467. $step6Done = $mainCompleted && $inboundScored;
  5468. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5469. if ($mainCompleted && $issued) {
  5470. $step3Done = true;
  5471. $step4Done = true;
  5472. $step5Done = true;
  5473. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5474. if ($supplierTime === '') {
  5475. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5476. if ($fillT !== '') {
  5477. $supplierTime = $fillT;
  5478. }
  5479. }
  5480. if ($pickedTime === '') {
  5481. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5482. if ($fillT !== '') {
  5483. $pickedTime = $fillT;
  5484. }
  5485. }
  5486. if ($auditSelectTime === '') {
  5487. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5488. if ($fillT !== '') {
  5489. $auditSelectTime = $fillT;
  5490. }
  5491. }
  5492. if ($confirmApproveTime === '') {
  5493. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5494. if ($fillT !== '') {
  5495. $confirmApproveTime = $fillT;
  5496. }
  5497. }
  5498. }
  5499. }
  5500. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5501. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5502. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5503. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5504. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5505. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5506. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5507. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5508. $deadlineLines = [];
  5509. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5510. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5511. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5512. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5513. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5514. }
  5515. }
  5516. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5517. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5518. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5519. if ($deliveryDisp === '') {
  5520. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5521. }
  5522. if ($deliveryDisp !== '') {
  5523. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5524. }
  5525. }
  5526. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5527. $deadlineText = implode("\n", $deadlineLines);
  5528. $prefixOperTime = static function (string $t): string {
  5529. $t = trim($t);
  5530. if ($t === '' || $t === '—') {
  5531. return $t;
  5532. }
  5533. if (strpos($t, '操作时间') === 0) {
  5534. return $t;
  5535. }
  5536. return '操作时间:' . $t;
  5537. };
  5538. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5539. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5540. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5541. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5542. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5543. $steps = [
  5544. [
  5545. 'title' => '未发',
  5546. 'subtitle' => '',
  5547. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5548. 'done' => $step1Done,
  5549. ],
  5550. [
  5551. 'title' => '下发',
  5552. 'subtitle' => $deadlineText,
  5553. 'time' => $prefixOperTime($step2Time),
  5554. 'done' => $step2Done,
  5555. ],
  5556. [
  5557. 'title' => '供应商接单',
  5558. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5559. 'time' => '',
  5560. 'done' => $step3Done,
  5561. ],
  5562. [
  5563. 'title' => '待确认',
  5564. 'subtitle' => $step4Done
  5565. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5566. : ($issued ? '待选供应商' : ''),
  5567. 'time' => $prefixOperTime($step4Time),
  5568. 'done' => $step4Done,
  5569. ],
  5570. [
  5571. 'title' => '待审批',
  5572. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5573. 'time' => $prefixOperTime($step5Time),
  5574. 'done' => $step5Done,
  5575. ],
  5576. [
  5577. 'title' => '是否合格',
  5578. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5579. 'time' => $prefixOperTime($stepInboundTime),
  5580. 'done' => $stepInboundDone,
  5581. ],
  5582. [
  5583. 'title' => '已完结',
  5584. 'subtitle' => '',
  5585. 'time' => $prefixOperTime($step6Time),
  5586. 'done' => $step6Done,
  5587. ],
  5588. ];
  5589. $currentIdx = count($steps) - 1;
  5590. if ($directComplete) {
  5591. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5592. if (!$step6Done) {
  5593. foreach ($steps as $i => $s) {
  5594. if (($s['title'] ?? '') === '是否合格') {
  5595. $currentIdx = $i;
  5596. break;
  5597. }
  5598. }
  5599. }
  5600. } else {
  5601. foreach ($steps as $i => $s) {
  5602. if (!$s['done']) {
  5603. $currentIdx = $i;
  5604. break;
  5605. }
  5606. }
  5607. }
  5608. $nSteps = count($steps);
  5609. foreach ($steps as $idx => &$s) {
  5610. $s['current'] = ($idx === $currentIdx);
  5611. if ($idx === 0) {
  5612. $s['pdf_left_bg'] = '';
  5613. } else {
  5614. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5615. }
  5616. if ($idx >= $nSteps - 1) {
  5617. $s['pdf_right_bg'] = '';
  5618. } else {
  5619. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5620. }
  5621. }
  5622. unset($s);
  5623. $labelMap = [
  5624. 'CCYDH' => '订单号',
  5625. 'CYJMC' => '印件名称',
  5626. 'CCLBMMC' => '承揽部门',
  5627. 'CGYMC' => '工序名称',
  5628. 'CDW' => '单位',
  5629. 'czlyq' => '类型',
  5630. 'NGZL' => '工作量',
  5631. 'CDF' => '单价',
  5632. 'cGzzxMc' => '工作中心',
  5633. 'MBZ' => '备注',
  5634. 'This_quantity' => '本次数量',
  5635. 'ceilingPrice' => '最高限价',
  5636. ];
  5637. $orderSummary = [];
  5638. foreach ($labelMap as $key => $lab) {
  5639. if (!array_key_exists($key, $main)) {
  5640. continue;
  5641. }
  5642. $val = $main[$key];
  5643. if ($val === null) {
  5644. $val = '';
  5645. } elseif (!is_scalar($val)) {
  5646. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5647. } else {
  5648. $val = (string)$val;
  5649. }
  5650. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5651. }
  5652. $orderSummary[] = [
  5653. 'label' => '是否合格',
  5654. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5655. ];
  5656. $orderSummaryGrid = [];
  5657. $n = count($orderSummary);
  5658. for ($i = 0; $i < $n; $i += 2) {
  5659. $left = $orderSummary[$i];
  5660. $hasRight = ($i + 1) < $n;
  5661. $orderSummaryGrid[] = [
  5662. 'l1' => $left['label'],
  5663. 'v1' => $left['value'],
  5664. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5665. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5666. ];
  5667. }
  5668. return [
  5669. 'steps' => $steps,
  5670. 'orderSummary' => $orderSummary,
  5671. 'orderSummaryGrid' => $orderSummaryGrid,
  5672. 'inbound_result' => $inboundResult,
  5673. 'inbound_score_time'=> $inboundScoreTime,
  5674. 'detailRows' => $details,
  5675. ];
  5676. }
  5677. /**
  5678. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5679. *
  5680. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5681. */
  5682. protected function prepareProcuremenDetailsView(string $ids): array
  5683. {
  5684. $main = [];
  5685. try {
  5686. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5687. $main = is_array($one) ? $one : [];
  5688. } catch (\Throwable $e) {
  5689. $main = [];
  5690. }
  5691. $details = [];
  5692. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5693. if ($mergeRows === []) {
  5694. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5695. if ($mergeRows === [] && $main !== []) {
  5696. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5697. }
  5698. }
  5699. $detailSidList = [];
  5700. $anchorSid = (int)$ids;
  5701. if ($anchorSid !== 0) {
  5702. $detailSidList[$anchorSid] = true;
  5703. }
  5704. foreach ($mergeRows as $mr) {
  5705. if (!is_array($mr)) {
  5706. continue;
  5707. }
  5708. $sid = $this->extractScydgyRowId($mr);
  5709. if ($sid !== 0) {
  5710. $detailSidList[$sid] = true;
  5711. }
  5712. }
  5713. try {
  5714. if ($detailSidList !== []) {
  5715. $details = Db::table('purchase_order_detail')
  5716. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5717. ->order('id', 'asc')
  5718. ->select();
  5719. }
  5720. } catch (\Throwable $e) {
  5721. $details = [];
  5722. }
  5723. if (!is_array($details)) {
  5724. $details = [];
  5725. }
  5726. foreach ($details as &$r) {
  5727. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5728. $r['id'] = $r['ID'];
  5729. }
  5730. if (isset($r['createtime'])) {
  5731. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5732. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5733. } else {
  5734. $r['createtime_text'] = (string)$r['createtime'];
  5735. }
  5736. } else {
  5737. $r['createtime_text'] = '';
  5738. }
  5739. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5740. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5741. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5742. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5743. if (is_array($r)) {
  5744. $r = $this->maskSupplierContactFields($r);
  5745. }
  5746. }
  5747. unset($r);
  5748. $activeDetails = [];
  5749. foreach ($details as $r) {
  5750. if (is_array($r) && empty($r['is_void'])) {
  5751. $activeDetails[] = $r;
  5752. }
  5753. }
  5754. $operLogs = [];
  5755. try {
  5756. $operSidList = array_keys($detailSidList);
  5757. if ($operSidList === [] && (int)$ids !== 0) {
  5758. $operSidList = [(int)$ids];
  5759. }
  5760. if ($operSidList !== []) {
  5761. $operLogs = Db::table('purchase_order_oper_log')
  5762. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5763. ->order('id', 'asc')
  5764. ->select();
  5765. }
  5766. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5767. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5768. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5769. if ($poId > 0) {
  5770. $operLogs = Db::table('purchase_order_oper_log')
  5771. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5772. ->order('id', 'asc')
  5773. ->select();
  5774. }
  5775. }
  5776. } catch (\Throwable $e) {
  5777. $operLogs = [];
  5778. }
  5779. if (!is_array($operLogs)) {
  5780. $operLogs = [];
  5781. }
  5782. $operLogsRaw = $operLogs;
  5783. $processNameBySid = [];
  5784. foreach ($mergeRows as $mr) {
  5785. if (!is_array($mr)) {
  5786. continue;
  5787. }
  5788. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5789. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5790. if ($psid !== 0 && $gymc !== '') {
  5791. $processNameBySid[$psid] = $gymc;
  5792. }
  5793. }
  5794. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5795. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5796. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5797. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5798. if ($ccydh === '') {
  5799. foreach ($details as $r) {
  5800. if (!is_array($r)) {
  5801. continue;
  5802. }
  5803. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5804. if ($ccydh !== '') {
  5805. break;
  5806. }
  5807. }
  5808. }
  5809. $this->view->assign('ccydh', $ccydh);
  5810. $this->view->assign('steps', $bundle['steps']);
  5811. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5812. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5813. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5814. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5815. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5816. $this->view->assign('processCount', count($mergeRows));
  5817. $this->view->assign('detailRows', $details);
  5818. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5819. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5820. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5821. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5822. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5823. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5824. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5825. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5826. $this->view->assign('operLogs', $operLogs);
  5827. $sg = $quoteView['supplier_groups'] ?? [];
  5828. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  5829. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  5830. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  5831. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  5832. return [
  5833. 'ok' => $main !== [] || $details !== [],
  5834. 'ccydh' => $ccydh,
  5835. ];
  5836. }
  5837. /**
  5838. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  5839. */
  5840. public function details()
  5841. {
  5842. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5843. if (is_array($ids)) {
  5844. $ids = isset($ids[0]) ? $ids[0] : '';
  5845. }
  5846. $ids = trim((string)$ids);
  5847. if ($ids === '') {
  5848. $this->error(__('Invalid parameters'));
  5849. }
  5850. $this->assertManualOrderDetailsViewable((int)$ids);
  5851. $this->prepareProcuremenDetailsView($ids);
  5852. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  5853. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5854. $this->view->engine->layout(false);
  5855. try {
  5856. return $this->view->fetch('procuremen/details_dialog_shell');
  5857. } finally {
  5858. if ($restoreLayout) {
  5859. $this->view->engine->layout($restoreLayout);
  5860. }
  5861. }
  5862. }
  5863. /**
  5864. * 解析合并审核工序行(订单号须一致,且均未协助)
  5865. *
  5866. * @return array<int, array<string, mixed>>
  5867. */
  5868. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  5869. {
  5870. $primary = json_decode($rowJson, true);
  5871. if (!is_array($primary)) {
  5872. $this->error(__('Invalid parameters'));
  5873. }
  5874. $merge = json_decode($mergeRowsJson, true);
  5875. if (!is_array($merge) || $merge === []) {
  5876. $merge = [$primary];
  5877. }
  5878. $seen = [];
  5879. $out = [];
  5880. foreach ($merge as $r) {
  5881. if (!is_array($r)) {
  5882. continue;
  5883. }
  5884. $id = $this->extractScydgyRowId($r);
  5885. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  5886. continue;
  5887. }
  5888. $seen[$id] = true;
  5889. $out[] = $r;
  5890. }
  5891. if ($out === []) {
  5892. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  5893. }
  5894. $ccydh = null;
  5895. foreach ($out as $r) {
  5896. $dh = trim((string)($r['CCYDH'] ?? ''));
  5897. if ($ccydh === null) {
  5898. $ccydh = $dh;
  5899. } elseif ($dh !== $ccydh) {
  5900. $this->error('合并审核要求所选行的订单号一致');
  5901. }
  5902. }
  5903. $ids = [];
  5904. foreach ($out as $r) {
  5905. $id = $this->extractScydgyRowId($r);
  5906. if ($this->isValidScydgyRowId($id)) {
  5907. $ids[$id] = true;
  5908. }
  5909. }
  5910. $poBySid = [];
  5911. $detCntBySid = [];
  5912. if ($ids !== []) {
  5913. $idList = array_keys($ids);
  5914. try {
  5915. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  5916. if (is_array($poList)) {
  5917. foreach ($poList as $po) {
  5918. if (!is_array($po)) {
  5919. continue;
  5920. }
  5921. $sid = (int)($po['scydgy_id'] ?? 0);
  5922. if ($this->isValidScydgyRowId($sid)) {
  5923. $poBySid[$sid] = $po;
  5924. }
  5925. }
  5926. }
  5927. } catch (\Throwable $e) {
  5928. }
  5929. try {
  5930. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  5931. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  5932. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  5933. if (is_array($detRows)) {
  5934. foreach ($detRows as $dr) {
  5935. if (!is_array($dr)) {
  5936. continue;
  5937. }
  5938. $sid = (int)($dr['scydgy_id'] ?? 0);
  5939. if ($this->isValidScydgyRowId($sid)) {
  5940. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  5941. }
  5942. }
  5943. }
  5944. } catch (\Throwable $e) {
  5945. }
  5946. }
  5947. foreach ($out as $r) {
  5948. $id = $this->extractScydgyRowId($r);
  5949. if (!$this->isValidScydgyRowId($id)) {
  5950. continue;
  5951. }
  5952. $po = $poBySid[$id] ?? null;
  5953. if (!is_array($po)) {
  5954. continue;
  5955. }
  5956. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  5957. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5958. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  5959. }
  5960. $detCnt = (int)($detCntBySid[$id] ?? 0);
  5961. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  5962. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5963. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  5964. }
  5965. }
  5966. return $out;
  5967. }
  5968. /**
  5969. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  5970. */
  5971. protected function maskSupplierContactFields(array $item): array
  5972. {
  5973. if (array_key_exists('email', $item)) {
  5974. $item['email'] = mask_email((string)$item['email']);
  5975. }
  5976. if (array_key_exists('phone', $item)) {
  5977. $item['phone'] = mask_phone((string)$item['phone']);
  5978. }
  5979. return $item;
  5980. }
  5981. /**
  5982. * @param array<int, array<string, mixed>> $list
  5983. * @return array<int, array<string, mixed>>
  5984. */
  5985. protected function maskSupplierContactList(array $list): array
  5986. {
  5987. $out = [];
  5988. foreach ($list as $item) {
  5989. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  5990. }
  5991. return $out;
  5992. }
  5993. /**
  5994. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  5995. *
  5996. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  5997. * @return array<string, string>|null
  5998. */
  5999. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  6000. {
  6001. if (!is_array($row)) {
  6002. return null;
  6003. }
  6004. $norm = [];
  6005. foreach ($row as $k => $v) {
  6006. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6007. }
  6008. $row = $norm;
  6009. $st = $row['status'] ?? '';
  6010. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6011. return null;
  6012. }
  6013. $companyName = '';
  6014. foreach (['company_name', 'name'] as $nk) {
  6015. if (!empty($row[$nk])) {
  6016. $companyName = trim((string)$row[$nk]);
  6017. break;
  6018. }
  6019. }
  6020. if ($companyName === '') {
  6021. return null;
  6022. }
  6023. $username = '';
  6024. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6025. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6026. $username = trim((string)$row[$uk]);
  6027. break;
  6028. }
  6029. }
  6030. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6031. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6032. if ($phone === '' && isset($row['account'])) {
  6033. $phone = trim((string)$row['account']);
  6034. }
  6035. if ($phone === '' && isset($row['mobile'])) {
  6036. $phone = trim((string)$row['mobile']);
  6037. }
  6038. if ($requireContactChannels && $email === '' && $phone === '') {
  6039. return null;
  6040. }
  6041. $category = '';
  6042. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6043. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6044. $category = trim((string)$row[$ck]);
  6045. break;
  6046. }
  6047. }
  6048. return [
  6049. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6050. 'name' => $companyName,
  6051. 'company_name' => $companyName,
  6052. 'username' => $username,
  6053. 'email' => $email,
  6054. 'phone' => $phone,
  6055. 'category' => $category,
  6056. 'company_type' => $category,
  6057. ];
  6058. }
  6059. /**
  6060. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6061. */
  6062. protected function resolveCustomerContactById(string $id): ?array
  6063. {
  6064. $id = trim($id);
  6065. if ($id === '' || !ctype_digit($id)) {
  6066. return null;
  6067. }
  6068. try {
  6069. $row = Db::table('customer')->where('id', (int)$id)->find();
  6070. } catch (\Throwable $e) {
  6071. return null;
  6072. }
  6073. return $this->buildCustomerContactPayloadFromRow($row);
  6074. }
  6075. /**
  6076. * 按供应商名称解析联系信息(兼容旧提交数据)
  6077. *
  6078. * @param bool $requireContactChannels true 时须有邮箱或手机
  6079. */
  6080. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6081. {
  6082. $name = trim($name);
  6083. if ($name === '') {
  6084. return null;
  6085. }
  6086. try {
  6087. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6088. $row = Db::table('customer')
  6089. ->where('company_name', $name)
  6090. ->order('id', 'desc')
  6091. ->find();
  6092. } catch (\Throwable $e) {
  6093. return null;
  6094. }
  6095. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6096. }
  6097. /**
  6098. * 规范化下发/确认时勾选的供应商
  6099. *
  6100. * @param array<int, mixed> $companies
  6101. * @return array<int, array<string, string>>
  6102. */
  6103. protected function normalizePickCompanies(array $companies): array
  6104. {
  6105. $out = [];
  6106. foreach ($companies as $c) {
  6107. if (!is_array($c)) {
  6108. continue;
  6109. }
  6110. $resolved = null;
  6111. $cid = trim((string)($c['id'] ?? ''));
  6112. if ($cid !== '') {
  6113. $resolved = $this->resolveCustomerContactById($cid);
  6114. }
  6115. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6116. if ($resolved === null && $name !== '') {
  6117. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6118. }
  6119. if ($resolved === null) {
  6120. continue;
  6121. }
  6122. $out[] = $resolved;
  6123. }
  6124. return $out;
  6125. }
  6126. /**
  6127. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6128. *
  6129. * @param array<int, array<string, mixed>> $pool
  6130. * @return array<int, array<string, mixed>>
  6131. */
  6132. protected function collapseProcuremenPoolByOrder(array $pool): array
  6133. {
  6134. if ($pool === []) {
  6135. return [];
  6136. }
  6137. $groups = [];
  6138. foreach ($pool as $row) {
  6139. if (!is_array($row)) {
  6140. continue;
  6141. }
  6142. $dh = trim((string)($row['CCYDH'] ?? ''));
  6143. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6144. if (!isset($groups[$key])) {
  6145. $groups[$key] = [];
  6146. }
  6147. $groups[$key][] = $row;
  6148. }
  6149. $out = [];
  6150. foreach ($groups as $ccydh => $rows) {
  6151. if ($rows === []) {
  6152. continue;
  6153. }
  6154. usort($rows, function ($a, $b) {
  6155. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6156. });
  6157. $head = $rows[0];
  6158. $gymcList = [];
  6159. foreach ($rows as $r) {
  6160. $g = trim((string)($r['CGYMC'] ?? ''));
  6161. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6162. $gymcList[] = $g;
  6163. }
  6164. }
  6165. $merged = $head;
  6166. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6167. $merged['process_count'] = count($rows);
  6168. $merged['_order_merge_rows'] = $rows;
  6169. $qtyList = [];
  6170. $priceList = [];
  6171. foreach ($rows as $r) {
  6172. if (!is_array($r)) {
  6173. continue;
  6174. }
  6175. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6176. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6177. }
  6178. if (count($rows) > 1) {
  6179. $merged['CGYMC'] = implode('、', $gymcList);
  6180. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6181. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6182. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6183. } else {
  6184. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6185. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6186. }
  6187. // 已选供应商:取合并行中首个非空 pick_company_name
  6188. $pickedName = '';
  6189. foreach ($rows as $r) {
  6190. if (!is_array($r)) {
  6191. continue;
  6192. }
  6193. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6194. if ($pn !== '') {
  6195. $pickedName = $pn;
  6196. break;
  6197. }
  6198. }
  6199. if ($pickedName !== '') {
  6200. $merged['pick_company_name'] = $pickedName;
  6201. $merged['picked_supplier_name'] = $pickedName;
  6202. }
  6203. $mergedPickTime = '';
  6204. foreach ($rows as $r) {
  6205. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6206. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6207. $mergedPickTime = $t;
  6208. }
  6209. }
  6210. if ($mergedPickTime !== '') {
  6211. $merged['pick_time'] = $mergedPickTime;
  6212. }
  6213. $out[] = $merged;
  6214. }
  6215. usort($out, function ($a, $b) {
  6216. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6217. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6218. if ($ta === $tb) {
  6219. $ida = (int)($a['purchase_order_id'] ?? 0);
  6220. $idb = (int)($b['purchase_order_id'] ?? 0);
  6221. if ($ida !== $idb) {
  6222. return $idb <=> $ida;
  6223. }
  6224. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6225. }
  6226. if ($ta === '') {
  6227. return 1;
  6228. }
  6229. if ($tb === '') {
  6230. return -1;
  6231. }
  6232. return strcmp($tb, $ta);
  6233. });
  6234. return $out;
  6235. }
  6236. /**
  6237. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6238. *
  6239. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6240. */
  6241. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6242. {
  6243. $scydgyId = trim($scydgyId);
  6244. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6245. if ($scydgyId === '') {
  6246. return $empty;
  6247. }
  6248. try {
  6249. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6250. } catch (\Throwable $e) {
  6251. $anchor = null;
  6252. }
  6253. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6254. return $empty;
  6255. }
  6256. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6257. if ($ccydh === '') {
  6258. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6259. }
  6260. try {
  6261. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6262. } catch (\Throwable $e) {
  6263. $pos = [$anchor];
  6264. }
  6265. if (!is_array($pos) || $pos === []) {
  6266. $pos = [$anchor];
  6267. }
  6268. return [
  6269. 'ccydh' => $ccydh,
  6270. 'pos' => $pos,
  6271. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6272. ];
  6273. }
  6274. /**
  6275. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6276. */
  6277. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6278. {
  6279. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6280. return false;
  6281. }
  6282. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6283. return false;
  6284. }
  6285. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6286. return true;
  6287. }
  6288. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6289. $sid = (int)($po['scydgy_id'] ?? 0);
  6290. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6291. }
  6292. return false;
  6293. }
  6294. /**
  6295. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6296. *
  6297. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6298. */
  6299. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6300. {
  6301. $scydgyId = trim($scydgyId);
  6302. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6303. if ($scydgyId === '') {
  6304. return $empty;
  6305. }
  6306. try {
  6307. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6308. } catch (\Throwable $e) {
  6309. $anchor = null;
  6310. }
  6311. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6312. return $empty;
  6313. }
  6314. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6315. if ($ccydh === '') {
  6316. return [
  6317. 'ccydh' => '',
  6318. 'pos' => [$anchor],
  6319. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6320. ];
  6321. }
  6322. try {
  6323. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6324. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6325. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6326. } catch (\Throwable $e) {
  6327. $pos = [$anchor];
  6328. }
  6329. if (!is_array($pos) || $pos === []) {
  6330. $pos = [$anchor];
  6331. }
  6332. $pos = array_values(array_filter($pos, function ($po) {
  6333. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6334. }));
  6335. if ($pos === []) {
  6336. $pos = [$anchor];
  6337. }
  6338. return [
  6339. 'ccydh' => $ccydh,
  6340. 'pos' => $pos,
  6341. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6342. ];
  6343. }
  6344. /**
  6345. * @param array<int, array<string, mixed>> $purchaseOrders
  6346. * @return array<int, array<string, mixed>>
  6347. */
  6348. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6349. {
  6350. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6351. $byId = [];
  6352. foreach ($pool as $r) {
  6353. if (!is_array($r)) {
  6354. continue;
  6355. }
  6356. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6357. if ($this->isValidScydgyRowId($sid)) {
  6358. $byId[$sid] = $r;
  6359. }
  6360. }
  6361. $out = [];
  6362. foreach ($purchaseOrders as $po) {
  6363. if (!is_array($po)) {
  6364. continue;
  6365. }
  6366. $sid = (int)($po['scydgy_id'] ?? 0);
  6367. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6368. $out[] = $byId[$sid];
  6369. }
  6370. }
  6371. return $out;
  6372. }
  6373. /**
  6374. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6375. *
  6376. * @return array<int, array<string, mixed>>
  6377. */
  6378. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6379. {
  6380. $scydgyId = trim($scydgyId);
  6381. if ($scydgyId === '') {
  6382. return [];
  6383. }
  6384. try {
  6385. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6386. } catch (\Throwable $e) {
  6387. $anchor = null;
  6388. }
  6389. if (!is_array($anchor)) {
  6390. return [];
  6391. }
  6392. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6393. return [];
  6394. }
  6395. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6396. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6397. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6398. try {
  6399. $q = Db::table('purchase_order');
  6400. if ($ccydh !== '') {
  6401. $q->where('CCYDH', $ccydh);
  6402. } else {
  6403. $q->where('scydgy_id', $scydgyId);
  6404. }
  6405. if ($isValidPick) {
  6406. $q->where('pick_time', $pickTime);
  6407. }
  6408. $pos = $q->order('scydgy_id', 'asc')->select();
  6409. } catch (\Throwable $e) {
  6410. $pos = [$anchor];
  6411. }
  6412. if (!is_array($pos) || $pos === []) {
  6413. $pos = [$anchor];
  6414. }
  6415. $pos = array_values(array_filter($pos, function ($po) {
  6416. if (!is_array($po)) {
  6417. return false;
  6418. }
  6419. $mr = $po['mod_rq'] ?? null;
  6420. if ($mr === null || $mr === '') {
  6421. return true;
  6422. }
  6423. $mrs = trim((string)$mr);
  6424. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6425. }));
  6426. if ($pos === []) {
  6427. $pos = [$anchor];
  6428. }
  6429. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6430. if ($rows === []) {
  6431. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6432. }
  6433. return $rows;
  6434. }
  6435. /**
  6436. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6437. *
  6438. * @param array<int, array<string, mixed>> $mergeRows
  6439. * @return array<int, array<string, mixed>>
  6440. */
  6441. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6442. {
  6443. $list = array_values($mergeRows);
  6444. $n = count($list);
  6445. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6446. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6447. $mergeSame = $n > 1 && $orderKey0 !== '';
  6448. if ($mergeSame) {
  6449. foreach ($list as $rr) {
  6450. if (!is_array($rr)) {
  6451. $mergeSame = false;
  6452. break;
  6453. }
  6454. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6455. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6456. $mergeSame = false;
  6457. break;
  6458. }
  6459. }
  6460. }
  6461. $out = [];
  6462. foreach ($list as $idx => $r) {
  6463. if (!is_array($r)) {
  6464. continue;
  6465. }
  6466. $qty = $this->resolveProcuremenThisQuantity($r);
  6467. $price = $this->resolveProcuremenCeilingPrice($r);
  6468. $sid = $this->extractScydgyRowId($r);
  6469. $out[] = [
  6470. 'seq' => $idx + 1,
  6471. 'scydgy_id' => $sid,
  6472. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6473. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6474. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6475. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6476. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6477. 'NGZL' => $r['NGZL'] ?? '',
  6478. 'This_quantity' => $qty,
  6479. 'ceilingPrice' => $price,
  6480. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6481. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6482. 'show_order_cells' => !$mergeSame || $idx === 0,
  6483. 'order_rowspan' => $mergeSame ? $n : 1,
  6484. ];
  6485. }
  6486. return $out;
  6487. }
  6488. /**
  6489. * 解析金额/数量(去千分位等非数字字符)
  6490. */
  6491. protected function parseProcuremenMoneyNumber($value): ?float
  6492. {
  6493. if ($value === null || $value === '') {
  6494. return null;
  6495. }
  6496. if (is_numeric($value)) {
  6497. return (float)$value;
  6498. }
  6499. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6500. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6501. }
  6502. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6503. {
  6504. if ($amount === null) {
  6505. return '';
  6506. }
  6507. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6508. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6509. return $s === '' ? '0' : $s;
  6510. }
  6511. /**
  6512. * 列表/详情展示:工作量为 0 时显示空
  6513. */
  6514. protected function formatProcuremenWorkloadDisplay($value): string
  6515. {
  6516. if ($value === null || $value === '') {
  6517. return '';
  6518. }
  6519. $s = trim((string)$value);
  6520. if ($s === '') {
  6521. return '';
  6522. }
  6523. if (is_numeric($s) && (float)$s == 0) {
  6524. return '';
  6525. }
  6526. return $s;
  6527. }
  6528. /**
  6529. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6530. */
  6531. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6532. {
  6533. foreach ($details as $d) {
  6534. if (!is_array($d)) {
  6535. continue;
  6536. }
  6537. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6538. $cn = trim((string)($d['company_name'] ?? ''));
  6539. if ($cn !== '') {
  6540. return $cn;
  6541. }
  6542. }
  6543. }
  6544. return trim((string)($main['pick_company_name'] ?? ''));
  6545. }
  6546. /**
  6547. * 详情报价小计:单价 × 本工序本次数量
  6548. */
  6549. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6550. {
  6551. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6552. if ($unit === null) {
  6553. return null;
  6554. }
  6555. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6556. if ($qty === null || $qty <= 0) {
  6557. return null;
  6558. }
  6559. return $unit * $qty;
  6560. }
  6561. /**
  6562. * 详情页:工序小计 + 供应商分组报价与总计
  6563. *
  6564. * @param array<int, array<string, mixed>> $mergeRows
  6565. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6566. * @return array{
  6567. * process_rows: array,
  6568. * supplier_groups: array,
  6569. * order_total_text: string,
  6570. * order_total_has: bool,
  6571. * selected_company: string
  6572. * }
  6573. */
  6574. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6575. {
  6576. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6577. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6578. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6579. || ((int)($main['manual_pick'] ?? 0) === 1);
  6580. $qtyBySid = [];
  6581. $gymcBySid = [];
  6582. $orderedSids = [];
  6583. foreach ($mergeRows as $mr) {
  6584. if (!is_array($mr)) {
  6585. continue;
  6586. }
  6587. $sid = $this->extractScydgyRowId($mr);
  6588. if ($this->isValidScydgyRowId($sid)) {
  6589. $orderedSids[] = $sid;
  6590. }
  6591. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6592. if ($qty === '') {
  6593. $qty = trim((string)($mr['NGZL'] ?? ''));
  6594. }
  6595. $qtyBySid[$sid] = $qty;
  6596. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6597. }
  6598. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6599. $detailByCompanySid = [];
  6600. foreach ($details as $d) {
  6601. if (!is_array($d)) {
  6602. continue;
  6603. }
  6604. $cn = trim((string)($d['company_name'] ?? ''));
  6605. $sid = (int)($d['scydgy_id'] ?? 0);
  6606. if ($cn === '' || $sid === 0) {
  6607. continue;
  6608. }
  6609. if (!isset($detailByCompanySid[$cn])) {
  6610. $detailByCompanySid[$cn] = [];
  6611. }
  6612. $detailByCompanySid[$cn][$sid] = $d;
  6613. }
  6614. $supplierGroups = [];
  6615. foreach ($detailByCompanySid as $cn => $bySid) {
  6616. $lines = [];
  6617. $groupTotal = 0.0;
  6618. $groupHas = false;
  6619. $groupVoid = true;
  6620. $usedSids = [];
  6621. $appendLine = function (int $sid, array $d) use (
  6622. &$lines,
  6623. &$groupTotal,
  6624. &$groupHas,
  6625. &$groupVoid,
  6626. $qtyBySid,
  6627. $gymcBySid,
  6628. $quoteVisible
  6629. ) {
  6630. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6631. if (!$isVoid) {
  6632. $groupVoid = false;
  6633. }
  6634. $qtyStr = $qtyBySid[$sid] ?? '';
  6635. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6636. $am = trim((string)($d['amount'] ?? ''));
  6637. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6638. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6639. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6640. $sub = null;
  6641. if (!$isVoid && $amountNum !== null) {
  6642. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6643. }
  6644. $ct = $this->resolveDetailSupplierOperTime($d);
  6645. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6646. $leadFilled = ($leadDays !== null);
  6647. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6648. $line = [
  6649. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6650. 'amount' => $am,
  6651. 'unit_price_text' => $amountFilled
  6652. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6653. : '未填写',
  6654. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6655. 'delivery_ymd' => $deliveryYmd,
  6656. 'amount_filled' => $amountFilled,
  6657. 'delivery_filled' => $deliveryFilled,
  6658. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6659. 'lead_days' => $leadFilled ? $leadDays : '',
  6660. 'lead_days_filled'=> $leadFilled,
  6661. 'lead_days_show' => $leadText,
  6662. 'lead_days_text' => $leadText,
  6663. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6664. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6665. 'is_void' => $isVoid,
  6666. 'oper_time_text' => $ct,
  6667. ];
  6668. if (!$quoteVisible && !$isVoid) {
  6669. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6670. } elseif ($sub !== null) {
  6671. $groupTotal += $sub;
  6672. $groupHas = true;
  6673. }
  6674. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6675. };
  6676. foreach ($orderedSids as $sid) {
  6677. if (!isset($bySid[$sid])) {
  6678. continue;
  6679. }
  6680. $usedSids[$sid] = true;
  6681. $appendLine($sid, $bySid[$sid]);
  6682. }
  6683. foreach ($bySid as $sid => $d) {
  6684. if (isset($usedSids[$sid])) {
  6685. continue;
  6686. }
  6687. $appendLine((int)$sid, $d);
  6688. }
  6689. $firstDetail = null;
  6690. foreach ($bySid as $d) {
  6691. if (is_array($d)) {
  6692. $firstDetail = $d;
  6693. break;
  6694. }
  6695. }
  6696. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6697. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6698. if ($username === '' && $ph !== '') {
  6699. $username = $this->resolveCustomerContactName($ph, $cn);
  6700. }
  6701. $remark = '';
  6702. foreach ($bySid as $d) {
  6703. if (!is_array($d)) {
  6704. continue;
  6705. }
  6706. $rm = '';
  6707. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6708. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6709. $rm = trim((string)$d[$rk]);
  6710. break;
  6711. }
  6712. }
  6713. if ($rm !== '') {
  6714. $remark = $rm;
  6715. break;
  6716. }
  6717. }
  6718. $lineCount = count($lines);
  6719. $hasRemark = $lineCount > 0;
  6720. $supplierGroup = [
  6721. 'company_name' => $cn,
  6722. 'username' => $username,
  6723. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6724. 'phone' => $ph,
  6725. 'remark' => $remark,
  6726. 'has_remark' => $hasRemark,
  6727. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6728. 'is_void' => $groupVoid,
  6729. 'lines' => $lines,
  6730. 'line_count' => $lineCount,
  6731. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6732. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6733. 'has_total' => $lineCount > 0,
  6734. ];
  6735. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6736. $supplierGroups[] = $supplierGroup;
  6737. }
  6738. usort($supplierGroups, function ($a, $b) {
  6739. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6740. return ($a['is_void'] ?? false) ? 1 : -1;
  6741. }
  6742. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6743. return ($a['is_selected'] ?? false) ? -1 : 1;
  6744. }
  6745. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6746. });
  6747. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6748. return [
  6749. 'process_rows' => $processRows,
  6750. 'supplier_groups' => $supplierGroups,
  6751. 'order_total_text' => '',
  6752. 'order_total_has' => false,
  6753. 'selected_company' => $selectedCompany,
  6754. ];
  6755. }
  6756. /**
  6757. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  6758. */
  6759. protected function buildProcessLinesPlain(array $mergeRows): string
  6760. {
  6761. $lines = [];
  6762. $i = 1;
  6763. foreach ($mergeRows as $r) {
  6764. if (!is_array($r)) {
  6765. continue;
  6766. }
  6767. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6768. $dw = trim((string)($r['CDW'] ?? ''));
  6769. $gzl = trim((string)($r['NGZL'] ?? ''));
  6770. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6771. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  6772. if ($dw !== '') {
  6773. $parts[] = '单位:' . $dw;
  6774. }
  6775. if ($gzl !== '') {
  6776. $parts[] = '工作量:' . $gzl;
  6777. }
  6778. if ($qty !== '') {
  6779. $parts[] = '本次数量:' . $qty;
  6780. }
  6781. $lines[] = implode(' ', $parts);
  6782. $i++;
  6783. }
  6784. return implode("\n", $lines);
  6785. }
  6786. /**
  6787. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  6788. *
  6789. * @return array<string, string>
  6790. */
  6791. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  6792. {
  6793. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  6794. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  6795. }
  6796. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  6797. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  6798. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6799. $cyjmc = '';
  6800. foreach ($mergeRows as $mr) {
  6801. if (!is_array($mr)) {
  6802. continue;
  6803. }
  6804. if ($ccydh === '') {
  6805. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  6806. }
  6807. if ($cyjmc === '') {
  6808. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  6809. }
  6810. }
  6811. if ($pos !== []) {
  6812. $firstPo = $pos[0];
  6813. if (is_array($firstPo)) {
  6814. if ($ccydh === '') {
  6815. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  6816. }
  6817. if ($cyjmc === '') {
  6818. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  6819. }
  6820. }
  6821. }
  6822. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  6823. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  6824. if (is_array($any)) {
  6825. if ($ccydh === '') {
  6826. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  6827. }
  6828. if ($cyjmc === '') {
  6829. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  6830. }
  6831. }
  6832. }
  6833. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  6834. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  6835. $cgymc = '';
  6836. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  6837. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  6838. }
  6839. return [
  6840. 'ccydh' => $ccydh,
  6841. 'cyjmc' => $cyjmc,
  6842. 'cgymc' => $cgymc,
  6843. 'process_lines' => $processLines,
  6844. 'process_lines_html' => '',
  6845. ];
  6846. }
  6847. /**
  6848. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  6849. */
  6850. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  6851. {
  6852. $lines = [];
  6853. if ($ccydh !== '') {
  6854. $lines[] = '订单号:' . $ccydh;
  6855. }
  6856. if ($cyjmc !== '') {
  6857. $lines[] = '印件名称:' . $cyjmc;
  6858. }
  6859. if ($processPlain !== '') {
  6860. $lines[] = $processPlain;
  6861. }
  6862. return implode("\n", $lines);
  6863. }
  6864. /**
  6865. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  6866. *
  6867. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6868. */
  6869. protected function buildPlatformLinksPlain(array $detailLinks): string
  6870. {
  6871. $lines = [];
  6872. $i = 1;
  6873. foreach ($detailLinks as $lk) {
  6874. if (!is_array($lk)) {
  6875. continue;
  6876. }
  6877. $url = trim((string)($lk['url'] ?? ''));
  6878. if ($url === '') {
  6879. continue;
  6880. }
  6881. $label = trim((string)($lk['cgymc'] ?? ''));
  6882. if ($label === '') {
  6883. $label = '工序' . $i;
  6884. }
  6885. $lines[] = $label . ':' . $url;
  6886. $i++;
  6887. }
  6888. return implode("\n", $lines);
  6889. }
  6890. /**
  6891. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  6892. *
  6893. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6894. */
  6895. protected function buildPlatformLinksHtml(array $detailLinks): string
  6896. {
  6897. $parts = [];
  6898. $i = 1;
  6899. foreach ($detailLinks as $lk) {
  6900. if (!is_array($lk)) {
  6901. continue;
  6902. }
  6903. $url = trim((string)($lk['url'] ?? ''));
  6904. if ($url === '') {
  6905. continue;
  6906. }
  6907. $label = trim((string)($lk['cgymc'] ?? ''));
  6908. if ($label === '') {
  6909. $label = '工序' . $i;
  6910. }
  6911. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  6912. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  6913. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  6914. $i++;
  6915. }
  6916. return implode("<br>\n", $parts);
  6917. }
  6918. /**
  6919. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  6920. *
  6921. * @return array<string, mixed>
  6922. */
  6923. protected function loadMailerConfig(): array
  6924. {
  6925. try {
  6926. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  6927. } catch (\Throwable $e) {
  6928. $cfg = [];
  6929. }
  6930. return is_array($cfg) ? $cfg : [];
  6931. }
  6932. protected function loadNotifyTemplateRow(string $scene): ?array
  6933. {
  6934. try {
  6935. $row = Db::table('purchase_sms_template')
  6936. ->where('scene', $scene)
  6937. ->where(function ($q) {
  6938. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  6939. })
  6940. ->order('id', 'asc')
  6941. ->find();
  6942. } catch (\Throwable $e) {
  6943. return null;
  6944. }
  6945. if (!is_array($row) || $row === []) {
  6946. return null;
  6947. }
  6948. return [
  6949. 'title' => trim((string)($row['title'] ?? '')),
  6950. 'content' => trim((string)($row['content'] ?? '')),
  6951. ];
  6952. }
  6953. /**
  6954. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  6955. */
  6956. protected function buildProcessLinesHtml(array $mergeRows): string
  6957. {
  6958. if (count($mergeRows) <= 1) {
  6959. $r = $mergeRows[0] ?? [];
  6960. if (!is_array($r)) {
  6961. return '';
  6962. }
  6963. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6964. $dw = trim((string)($r['CDW'] ?? ''));
  6965. $gzl = trim((string)($r['NGZL'] ?? ''));
  6966. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6967. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  6968. if ($dw !== '') {
  6969. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  6970. }
  6971. if ($gzl !== '') {
  6972. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  6973. }
  6974. if ($qty !== '') {
  6975. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  6976. }
  6977. return $html;
  6978. }
  6979. $rows = '';
  6980. $i = 1;
  6981. foreach ($mergeRows as $r) {
  6982. if (!is_array($r)) {
  6983. continue;
  6984. }
  6985. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  6986. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  6987. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  6988. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  6989. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  6990. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  6991. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  6992. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  6993. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  6994. $i++;
  6995. }
  6996. if ($rows === '') {
  6997. return '';
  6998. }
  6999. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  7000. . '<thead><tr style="background:#f5f5f5;">'
  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. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  7005. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  7006. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7007. }
  7008. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7009. {
  7010. $sysRq = trim($sysRq);
  7011. if ($sysRq === '') {
  7012. if ($required) {
  7013. $this->error('请选择招标截止日期');
  7014. }
  7015. return '';
  7016. }
  7017. $ts = strtotime($sysRq);
  7018. if ($ts === false || $ts <= 0) {
  7019. $this->error('招标截止日期格式无效');
  7020. }
  7021. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7022. if (!$allowPast) {
  7023. $ymd = date('Y-m-d', $ts);
  7024. if ($ymd < date('Y-m-d')) {
  7025. $this->error('招标截止日期不能早于今天');
  7026. }
  7027. if ($ts <= time()) {
  7028. $this->error('招标截止时间不能早于当前时间');
  7029. }
  7030. }
  7031. return date('Y-m-d H:i:s', $ts);
  7032. }
  7033. /**
  7034. * 确保 purchase_order.czlyq(类型)存在
  7035. */
  7036. protected function ensurePurchaseOrderCzlyqColumn(): void
  7037. {
  7038. static $done = false;
  7039. if ($done) {
  7040. return;
  7041. }
  7042. $done = true;
  7043. try {
  7044. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7045. if (empty($cols)) {
  7046. Db::execute(
  7047. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7048. );
  7049. }
  7050. } catch (\Throwable $e) {
  7051. // ignore
  7052. }
  7053. }
  7054. /**
  7055. * 确保 purchase_order.delivery_deadline 存在
  7056. */
  7057. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7058. {
  7059. static $done = false;
  7060. if ($done) {
  7061. return;
  7062. }
  7063. $done = true;
  7064. try {
  7065. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7066. if (empty($cols)) {
  7067. Db::execute(
  7068. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7069. );
  7070. }
  7071. } catch (\Throwable $e) {
  7072. // ignore
  7073. }
  7074. }
  7075. /**
  7076. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7077. */
  7078. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7079. {
  7080. static $done = false;
  7081. if ($done) {
  7082. return;
  7083. }
  7084. $done = true;
  7085. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7086. $adds = [
  7087. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7088. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7089. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7090. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7091. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7092. ];
  7093. $changed = false;
  7094. foreach ($adds as $col => $ddl) {
  7095. try {
  7096. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7097. if (!is_array($cols) || $cols === []) {
  7098. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7099. $changed = true;
  7100. }
  7101. } catch (\Throwable $e) {
  7102. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7103. }
  7104. }
  7105. if ($changed) {
  7106. $this->clearPurchaseOrderTableFieldsCache();
  7107. }
  7108. }
  7109. /**
  7110. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7111. */
  7112. protected function clearPurchaseOrderTableFieldsCache(): void
  7113. {
  7114. try {
  7115. $db = (string)Config::get('database.database');
  7116. $key = $db . '.purchase_order';
  7117. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7118. $ref->setAccessible(true);
  7119. $info = $ref->getValue();
  7120. if (is_array($info) && isset($info[$key])) {
  7121. unset($info[$key]);
  7122. $ref->setValue(null, $info);
  7123. }
  7124. } catch (\Throwable $e) {
  7125. }
  7126. try {
  7127. $db = (string)Config::get('database.database');
  7128. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7129. if (is_file($schemaFile)) {
  7130. @unlink($schemaFile);
  7131. }
  7132. } catch (\Throwable $e) {
  7133. }
  7134. }
  7135. /**
  7136. * @return array<string, bool>
  7137. */
  7138. protected function loadPurchaseOrderColumnSet(): array
  7139. {
  7140. static $set = null;
  7141. if (is_array($set)) {
  7142. return $set;
  7143. }
  7144. $set = [];
  7145. try {
  7146. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7147. } catch (\Throwable $e) {
  7148. return $set;
  7149. }
  7150. if (!is_array($cols)) {
  7151. return $set;
  7152. }
  7153. foreach ($cols as $c) {
  7154. if (!is_array($c)) {
  7155. continue;
  7156. }
  7157. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7158. if ($f !== '') {
  7159. $set[$f] = true;
  7160. }
  7161. }
  7162. return $set;
  7163. }
  7164. /**
  7165. * 解析交货截止日期(仅年月日)
  7166. */
  7167. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7168. {
  7169. $raw = trim($raw);
  7170. if ($raw === '') {
  7171. if ($required) {
  7172. $this->error('请选择交货截止日期');
  7173. }
  7174. return '';
  7175. }
  7176. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7177. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7178. } else {
  7179. $ts = strtotime(str_replace('/', '-', $raw));
  7180. if ($ts === false || $ts <= 0) {
  7181. $this->error('交货截止日期格式无效');
  7182. }
  7183. $ymd = date('Y-m-d', $ts);
  7184. }
  7185. if ($ymd < date('Y-m-d')) {
  7186. $this->error('交货截止日期不能早于今天');
  7187. }
  7188. return $ymd;
  7189. }
  7190. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7191. {
  7192. $s = trim((string)$value);
  7193. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7194. return '';
  7195. }
  7196. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7197. return $m[1];
  7198. }
  7199. $ts = strtotime(str_replace('/', '-', $s));
  7200. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7201. }
  7202. /**
  7203. * @param array{pos?:array} $bundle
  7204. */
  7205. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7206. {
  7207. foreach ($bundle['pos'] ?? [] as $po) {
  7208. if (!is_array($po)) {
  7209. continue;
  7210. }
  7211. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7212. if ($d !== '') {
  7213. return $d;
  7214. }
  7215. }
  7216. return '';
  7217. }
  7218. protected function formatProcuremenSysRqForInput($sysRq): string
  7219. {
  7220. $sr = trim((string)$sysRq);
  7221. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7222. return '';
  7223. }
  7224. $ts = strtotime($sr);
  7225. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7226. }
  7227. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7228. {
  7229. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7230. if ($sr === '') {
  7231. return '—';
  7232. }
  7233. $ts = strtotime($sr);
  7234. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7235. }
  7236. /**
  7237. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7238. *
  7239. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7240. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7241. */
  7242. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7243. {
  7244. return $bundle;
  7245. }
  7246. /**
  7247. * 写入/更新 purchase_order(单道工序行)
  7248. *
  7249. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7250. */
  7251. protected function upsertPurchaseOrderFromRow(
  7252. array $row,
  7253. string $sysRqDb,
  7254. $wflowStatus = null,
  7255. ?string $pickTime = null,
  7256. ?array $exists = null,
  7257. ?string $deliveryDeadline = null,
  7258. $scoreRuleId = null
  7259. ): void {
  7260. $ids = $this->extractScydgyRowId($row);
  7261. if (!$this->isValidScydgyRowId($ids)) {
  7262. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7263. }
  7264. if ($exists === null) {
  7265. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7266. }
  7267. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7268. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7269. $this->ensurePurchaseOrderCzlyqColumn();
  7270. $data = [
  7271. 'scydgy_id' => $ids,
  7272. 'CCYDH' => $row['CCYDH'] ?? null,
  7273. 'CYJMC' => $row['CYJMC'] ?? null,
  7274. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7275. 'CDXMC' => $row['CDXMC'] ?? null,
  7276. 'CGYBH' => $row['CGYBH'] ?? null,
  7277. 'CGYMC' => $row['CGYMC'] ?? null,
  7278. 'CDW' => $row['CDW'] ?? null,
  7279. 'czlyq' => $row['czlyq'] ?? null,
  7280. 'NGZL' => $row['NGZL'] ?? null,
  7281. 'CDF' => $row['CDF'] ?? null,
  7282. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7283. 'MBZ' => $row['MBZ'] ?? null,
  7284. 'bwjg' => $row['bwjg'] ?? null,
  7285. 'iStatus' => $row['iStatus'] ?? null,
  7286. 'dStamp' => $row['dStamp'] ?? null,
  7287. 'dputrecord' => $row['dputrecord'] ?? null,
  7288. 'cywyxm' => $row['cywyxm'] ?? null,
  7289. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7290. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7291. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7292. 'sys_rq' => $sysRqDb,
  7293. ];
  7294. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7295. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7296. if ($qtyUp === '') {
  7297. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7298. 'This_quantity' => '',
  7299. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7300. ]);
  7301. if ($qtyFallback !== '') {
  7302. $data['This_quantity'] = $qtyFallback;
  7303. }
  7304. }
  7305. if ($deliveryDeadline !== null) {
  7306. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7307. }
  7308. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7309. $scoreRule = null;
  7310. if (is_array($scoreRuleId)) {
  7311. $scoreRule = $scoreRuleId;
  7312. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7313. } else {
  7314. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7315. }
  7316. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7317. $poCols = $this->loadPurchaseOrderColumnSet();
  7318. if (!empty($poCols['score_rule_id'])) {
  7319. $data['score_rule_id'] = $scoreRuleId;
  7320. if (is_array($scoreRule)) {
  7321. if (!empty($poCols['score_rule_name'])) {
  7322. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7323. }
  7324. if (!empty($poCols['score_quality_weight'])) {
  7325. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7326. }
  7327. if (!empty($poCols['score_price_weight'])) {
  7328. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7329. }
  7330. if (!empty($poCols['score_lead_weight'])) {
  7331. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7332. }
  7333. }
  7334. }
  7335. }
  7336. if ($wflowStatus !== null && $wflowStatus !== '') {
  7337. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7338. }
  7339. if ($pickTime !== null && $pickTime !== '') {
  7340. $data['pick_time'] = $pickTime;
  7341. $data['pick_company_name'] = '';
  7342. }
  7343. if ($exists) {
  7344. $upd = $data;
  7345. unset($upd['scydgy_id']);
  7346. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7347. } else {
  7348. $data['createtime'] = date('Y-m-d H:i:s');
  7349. Db::table('purchase_order')->insert($data);
  7350. }
  7351. }
  7352. /**
  7353. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7354. *
  7355. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7356. */
  7357. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7358. {
  7359. $toDb = function ($value) {
  7360. if ($value === null) {
  7361. return null;
  7362. }
  7363. if (is_scalar($value)) {
  7364. return $value;
  7365. }
  7366. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7367. };
  7368. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7369. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7370. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7371. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7372. if ($username === '') {
  7373. $username = $this->resolveCustomerContactName($phone, $companyName);
  7374. }
  7375. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7376. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7377. }
  7378. if ($requirePhone && $phone === '') {
  7379. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7380. }
  7381. $detailLinks = [];
  7382. foreach ($mergeRows as $row) {
  7383. if (!is_array($row)) {
  7384. continue;
  7385. }
  7386. $sid = $this->extractScydgyRowId($row);
  7387. $detailId = 0;
  7388. if ($skipExisting) {
  7389. try {
  7390. $existsQuery = Db::table('purchase_order_detail')
  7391. ->where('scydgy_id', $sid)
  7392. ->where('company_name', $companyName);
  7393. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7394. $exists = $existsQuery->find();
  7395. } catch (\Throwable $e) {
  7396. $exists = null;
  7397. }
  7398. if (is_array($exists)) {
  7399. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7400. }
  7401. }
  7402. if ($detailId <= 0) {
  7403. $one = [
  7404. 'scydgy_id' => $toDb($sid),
  7405. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7406. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7407. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7408. 'username' => $username !== '' ? $username : null,
  7409. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7410. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7411. 'createtime' => date('Y-m-d H:i:s'),
  7412. 'status' => ProcuremenStatus::POD_UNPICKED,
  7413. 'status_name' => '未提交',
  7414. ];
  7415. Db::table('purchase_order_detail')->insert($one);
  7416. $detailId = (int)Db::getLastInsID();
  7417. }
  7418. $mprocUrl = '';
  7419. if ($buildMobileLinks && $detailId > 0) {
  7420. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  7421. }
  7422. $detailLinks[] = [
  7423. 'detail_id' => $detailId,
  7424. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7425. 'url' => $mprocUrl,
  7426. ];
  7427. }
  7428. $this->invalidatePickHiddenScydgyCache();
  7429. return $detailLinks;
  7430. }
  7431. /**
  7432. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7433. * @return array<string, mixed>
  7434. */
  7435. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  7436. {
  7437. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7438. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7439. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7440. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7441. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7442. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7443. $isMerge = !empty($ctx['is_merge']);
  7444. $contactName = trim((string)($c['username'] ?? ''));
  7445. if ($contactName === '') {
  7446. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7447. }
  7448. $notifyVars = [
  7449. 'company_name' => $companyName,
  7450. 'contact_name' => $contactName,
  7451. 'phone' => $phone,
  7452. 'email' => $toEmail,
  7453. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7454. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7455. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7456. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7457. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7458. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7459. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7460. 'platform_url' => $platformUrl,
  7461. 'platform_links' => $platformLinksPlain,
  7462. 'platform_links_html' => $platformLinksHtml,
  7463. ];
  7464. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7465. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7466. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  7467. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7468. return [
  7469. 'company_name' => $companyName,
  7470. 'phone' => $phone,
  7471. 'email' => $toEmail,
  7472. 'sms_content' => $smsContent,
  7473. 'mail_plain' => $mailPlain,
  7474. 'mail_body' => $mailBody,
  7475. 'notify_vars' => $notifyVars,
  7476. 'detail_links' => $detailLinks,
  7477. ];
  7478. }
  7479. /**
  7480. * @param array<string, mixed> $chosen
  7481. * @param array<int, array<string, mixed>> $mergeRows
  7482. * @param array{ccydh:string, pos:array} $bundle
  7483. */
  7484. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  7485. {
  7486. if (!$sendSms && !$sendEmail) {
  7487. return;
  7488. }
  7489. $companyName = trim((string)($chosen['name'] ?? ''));
  7490. $phone = trim((string)($chosen['phone'] ?? ''));
  7491. $toEmail = trim((string)($chosen['email'] ?? ''));
  7492. if ($companyName === '') {
  7493. throw new \Exception('供应商名称无效');
  7494. }
  7495. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7496. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7497. }
  7498. if ($sendSms && $phone === '') {
  7499. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7500. }
  7501. $sids = [];
  7502. foreach ($mergeRows as $mr) {
  7503. if (!is_array($mr)) {
  7504. continue;
  7505. }
  7506. $sid = $this->extractScydgyRowId($mr);
  7507. if ($this->isValidScydgyRowId($sid)) {
  7508. $sids[$sid] = true;
  7509. }
  7510. }
  7511. if ($sids === []) {
  7512. throw new \Exception('未找到工序行,无法发送通知');
  7513. }
  7514. $sysRqNotify = '';
  7515. $pos = $bundle['pos'] ?? [];
  7516. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7517. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7518. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7519. $ts = strtotime($sr);
  7520. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7521. }
  7522. }
  7523. try {
  7524. $detailsQuery = Db::table('purchase_order_detail')
  7525. ->where('scydgy_id', 'in', array_keys($sids))
  7526. ->where('company_name', $companyName);
  7527. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7528. $details = $detailsQuery->order('id', 'asc')->select();
  7529. } catch (\Throwable $e) {
  7530. $details = [];
  7531. }
  7532. if (!is_array($details) || $details === []) {
  7533. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7534. try {
  7535. $detailsQuery = Db::table('purchase_order_detail')
  7536. ->where('scydgy_id', 'in', array_keys($sids))
  7537. ->where('company_name', $companyName);
  7538. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7539. $details = $detailsQuery->order('id', 'asc')->select();
  7540. } catch (\Throwable $e) {
  7541. $details = [];
  7542. }
  7543. }
  7544. if (!is_array($details) || $details === []) {
  7545. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7546. }
  7547. $detailLinks = [];
  7548. foreach ($details as $d) {
  7549. if (!is_array($d)) {
  7550. continue;
  7551. }
  7552. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7553. if ($detailId <= 0) {
  7554. continue;
  7555. }
  7556. $sid = (int)($d['scydgy_id'] ?? 0);
  7557. $gymc = '';
  7558. foreach ($mergeRows as $mr) {
  7559. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7560. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7561. break;
  7562. }
  7563. }
  7564. $detailLinks[] = [
  7565. 'detail_id' => $detailId,
  7566. 'cgymc' => $gymc,
  7567. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  7568. ];
  7569. }
  7570. if ($detailLinks === []) {
  7571. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7572. }
  7573. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7574. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7575. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  7576. $notifyBundle['email_log_scene'] = $emailLogScene;
  7577. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7578. $poIdLog = 0;
  7579. $pos = $bundle['pos'] ?? [];
  7580. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7581. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7582. }
  7583. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7584. if ($sendEmail) {
  7585. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  7586. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7587. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  7588. }
  7589. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  7590. $mailConfig = $this->loadMailerConfig();
  7591. if (!$this->isProcuremenNotifyDryRun()) {
  7592. if (empty($mailConfig['host'])) {
  7593. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7594. }
  7595. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7596. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7597. }
  7598. }
  7599. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7600. }
  7601. if ($sendSms) {
  7602. $this->issueSendSupplierSms($notifyBundle);
  7603. }
  7604. }
  7605. /**
  7606. * @param array<int, array<string, mixed>> $quoteGroups
  7607. * @return array<int, array<string, mixed>>
  7608. */
  7609. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7610. {
  7611. $names = [];
  7612. if (is_string($companiesJson) && $companiesJson !== '') {
  7613. $decoded = json_decode($companiesJson, true);
  7614. if (is_array($decoded)) {
  7615. foreach ($decoded as $nm) {
  7616. $nm = trim((string)$nm);
  7617. if ($nm !== '') {
  7618. $names[] = $nm;
  7619. }
  7620. }
  7621. }
  7622. }
  7623. $names = array_values(array_unique($names));
  7624. if ($names === [] && $selectedCompany !== '') {
  7625. $names = [$selectedCompany];
  7626. }
  7627. if ($names === []) {
  7628. return $quoteGroups;
  7629. }
  7630. $targets = [];
  7631. foreach ($quoteGroups as $g) {
  7632. if (!is_array($g)) {
  7633. continue;
  7634. }
  7635. $cn = trim((string)($g['name'] ?? ''));
  7636. if ($cn !== '' && in_array($cn, $names, true)) {
  7637. $targets[] = $g;
  7638. }
  7639. }
  7640. return $targets;
  7641. }
  7642. /**
  7643. * @return array{pos:array, merge_rows:array, bundle:array}
  7644. */
  7645. protected function loadAuditResendBundle(string $scydgyId): array
  7646. {
  7647. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7648. $pos = $bundle['pos'];
  7649. $mergeRows = $bundle['merge_rows'];
  7650. if ($pos === [] || $mergeRows === []) {
  7651. $this->error('该订单不在待确认供应商状态');
  7652. }
  7653. $sysRqDb = '';
  7654. if (isset($pos[0]) && is_array($pos[0])) {
  7655. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7656. }
  7657. foreach ($pos as $i => $poRow) {
  7658. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7659. $pos[$i]['sys_rq'] = $sysRqDb;
  7660. }
  7661. }
  7662. $bundle['pos'] = $pos;
  7663. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7664. }
  7665. /**
  7666. * @param array<int, array<string, mixed>> $targets
  7667. */
  7668. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7669. {
  7670. if ($targets === []) {
  7671. $this->error('未找到可通知的供应商');
  7672. }
  7673. $notifyErrors = [];
  7674. try {
  7675. $this->notifyDryRunPreview = [];
  7676. foreach ($targets as $g) {
  7677. if (!is_array($g)) {
  7678. continue;
  7679. }
  7680. $cname = trim((string)($g['name'] ?? ''));
  7681. if ($cname === '') {
  7682. continue;
  7683. }
  7684. $chosen = [
  7685. 'name' => $cname,
  7686. 'company_name' => $cname,
  7687. 'email' => trim((string)($g['email'] ?? '')),
  7688. 'phone' => trim((string)($g['phone'] ?? '')),
  7689. 'username' => trim((string)($g['username'] ?? '')),
  7690. ];
  7691. try {
  7692. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7693. } catch (\Throwable $e) {
  7694. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7695. }
  7696. }
  7697. } catch (\Throwable $e) {
  7698. $this->error('通知发送失败:' . $e->getMessage());
  7699. }
  7700. if ($notifyErrors !== []) {
  7701. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7702. }
  7703. if ($this->isProcuremenNotifyDryRun()) {
  7704. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7705. 'notify_dry_run' => true,
  7706. 'notify_preview' => $this->notifyDryRunPreview,
  7707. ]);
  7708. }
  7709. $nameLabels = [];
  7710. foreach ($targets as $g) {
  7711. if (!is_array($g)) {
  7712. continue;
  7713. }
  7714. $n = trim((string)($g['name'] ?? ''));
  7715. if ($n !== '') {
  7716. $nameLabels[] = $n;
  7717. }
  7718. }
  7719. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7720. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7721. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7722. $seenLogSid = [];
  7723. foreach ($bundle['pos'] ?? [] as $poRow) {
  7724. if (!is_array($poRow)) {
  7725. continue;
  7726. }
  7727. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7728. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7729. continue;
  7730. }
  7731. $seenLogSid[$sid] = true;
  7732. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7733. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7734. }
  7735. if ($seenLogSid === []) {
  7736. foreach ($mergeRows as $mr) {
  7737. if (!is_array($mr)) {
  7738. continue;
  7739. }
  7740. $sid = $this->extractScydgyRowId($mr);
  7741. if ($this->isValidScydgyRowId($sid)) {
  7742. $this->addOrderLog($sid, $logAction, $logMsg, null);
  7743. break;
  7744. }
  7745. }
  7746. }
  7747. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  7748. }
  7749. /**
  7750. * 协助下发 — 发送短信(一家供应商)
  7751. *
  7752. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  7753. */
  7754. protected function issueSendSupplierSms(array $bundle): void
  7755. {
  7756. $companyName = (string)($bundle['company_name'] ?? '');
  7757. $phone = (string)($bundle['phone'] ?? '');
  7758. $smsContent = (string)($bundle['sms_content'] ?? '');
  7759. $this->logIssueNotifyDebug('短信', [
  7760. 'company' => $companyName,
  7761. 'phone' => $phone,
  7762. 'sms_content' => $smsContent,
  7763. ]);
  7764. if ($this->isProcuremenNotifyDryRun()) {
  7765. $this->recordNotifyDryRunPreview([
  7766. 'scene' => 'issue_sms',
  7767. 'company_name' => $companyName,
  7768. 'phone' => $phone,
  7769. 'sms_content' => $smsContent,
  7770. ]);
  7771. return;
  7772. }
  7773. $this->smsbao($phone, $smsContent);
  7774. }
  7775. /**
  7776. * 协助下发 — 发送邮件(一家供应商)
  7777. *
  7778. * @param array<string, mixed> $bundle
  7779. * @param array<string, mixed> $mailConfig
  7780. */
  7781. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  7782. {
  7783. $companyName = (string)($bundle['company_name'] ?? '');
  7784. $toEmail = (string)($bundle['email'] ?? '');
  7785. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  7786. $mailBody = (string)($bundle['mail_body'] ?? '');
  7787. $this->logIssueNotifyDebug('邮件', [
  7788. 'company' => $companyName,
  7789. 'email' => $toEmail,
  7790. 'mail_subject' => $mailSubject,
  7791. 'mail_body' => $mailPlain,
  7792. ]);
  7793. if ($this->isProcuremenNotifyDryRun()) {
  7794. $this->recordNotifyDryRunPreview([
  7795. 'scene' => 'issue_email',
  7796. 'company_name' => $companyName,
  7797. 'email' => $toEmail,
  7798. 'mail_subject' => $mailSubject,
  7799. 'mail_body' => $mailPlain,
  7800. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  7801. 'notify_vars' => $bundle['notify_vars'] ?? [],
  7802. 'detail_links' => $bundle['detail_links'] ?? [],
  7803. ]);
  7804. return;
  7805. }
  7806. $mail = new PHPMailer(true);
  7807. $mail->isSMTP();
  7808. $mail->Host = $mailConfig['host'];
  7809. $mail->SMTPAuth = true;
  7810. $mail->Username = $mailConfig['addr'];
  7811. $mail->Password = $mailConfig['pass'];
  7812. $mail->SMTPSecure = $mailConfig['security'];
  7813. $mail->Port = $mailConfig['port'];
  7814. $mail->CharSet = $mailConfig['charset'];
  7815. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  7816. $mail->addAddress($toEmail, $companyName);
  7817. $mail->isHTML(true);
  7818. $mail->Subject = $mailSubject;
  7819. $mail->Body = $mailBody;
  7820. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  7821. $sendOk = true;
  7822. $failReason = '';
  7823. try {
  7824. $mail->send();
  7825. } catch (\Throwable $e) {
  7826. $sendOk = false;
  7827. $failReason = $e->getMessage();
  7828. $this->persistEmailSendLog([
  7829. 'from_email' => $fromEmail,
  7830. 'to_email' => $toEmail,
  7831. 'send_time' => date('Y-m-d H:i:s'),
  7832. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7833. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7834. 'company_name' => $companyName,
  7835. 'mail_subject' => $mailSubject,
  7836. 'status' => 0,
  7837. 'fail_reason' => $failReason,
  7838. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7839. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7840. ]);
  7841. throw $e;
  7842. }
  7843. $this->persistEmailSendLog([
  7844. 'from_email' => $fromEmail,
  7845. 'to_email' => $toEmail,
  7846. 'send_time' => date('Y-m-d H:i:s'),
  7847. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7848. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7849. 'company_name' => $companyName,
  7850. 'mail_subject' => $mailSubject,
  7851. 'status' => 1,
  7852. 'fail_reason' => '',
  7853. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7854. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7855. ]);
  7856. }
  7857. /**
  7858. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  7859. *
  7860. * @param array<int, array<string, mixed>> $mergeRows
  7861. * @return array<string, mixed>
  7862. */
  7863. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  7864. {
  7865. $head = $mergeRows[0] ?? [];
  7866. $isMerge = count($mergeRows) > 1;
  7867. return [
  7868. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  7869. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  7870. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  7871. 'is_merge' => $isMerge,
  7872. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  7873. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  7874. 'deadline' => $sysRqNotify,
  7875. ];
  7876. }
  7877. /**
  7878. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  7879. *
  7880. * @param array<string, mixed> $data
  7881. */
  7882. protected function logIssueNotifyDebug(string $type, array $data): void
  7883. {
  7884. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  7885. return;
  7886. }
  7887. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  7888. }
  7889. protected function ensurePurchaseEmailSendLogTableOnce(): void
  7890. {
  7891. try {
  7892. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  7893. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7894. return;
  7895. } catch (\Throwable $e) {
  7896. }
  7897. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  7898. if (is_file($sqlFile)) {
  7899. $sql = file_get_contents($sqlFile);
  7900. if (is_string($sql) && $sql !== '') {
  7901. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  7902. $stmt = trim($stmt);
  7903. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  7904. continue;
  7905. }
  7906. try {
  7907. Db::execute($stmt);
  7908. } catch (\Throwable $ignore) {
  7909. }
  7910. }
  7911. }
  7912. }
  7913. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7914. }
  7915. /**
  7916. * @param array<string, mixed> $row
  7917. */
  7918. protected function persistEmailSendLog(array $row): void
  7919. {
  7920. try {
  7921. $this->ensurePurchaseEmailSendLogTableOnce();
  7922. } catch (\Throwable $e) {
  7923. return;
  7924. }
  7925. list($adminId, $adminName) = $this->GetUseName();
  7926. $cut = function ($s, $max) {
  7927. $s = (string)$s;
  7928. if (function_exists('mb_substr')) {
  7929. return mb_substr($s, 0, $max, 'UTF-8');
  7930. }
  7931. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  7932. };
  7933. $data = [
  7934. 'from_email' => $cut($row['from_email'] ?? '', 128),
  7935. 'to_email' => $cut($row['to_email'] ?? '', 128),
  7936. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  7937. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  7938. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  7939. 'company_name' => $cut($row['company_name'] ?? '', 128),
  7940. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  7941. 'status' => !empty($row['status']) ? 1 : 0,
  7942. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  7943. 'admin_id' => (int)$adminId,
  7944. 'admin_name' => $cut($adminName, 64),
  7945. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  7946. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  7947. 'createtime' => date('Y-m-d H:i:s'),
  7948. ];
  7949. try {
  7950. Db::table('purchase_email_send_log')->insert($data);
  7951. } catch (\Throwable $e) {
  7952. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  7953. }
  7954. }
  7955. protected function formatEmailLogSceneText(string $scene): string
  7956. {
  7957. $map = [
  7958. 'pick_issue' => '初选下发',
  7959. 'audit_resend' => '确认页重发',
  7960. 'rfq_salesman' => '询价通知业务员',
  7961. 'rfq_supplier' => '供应商询价通知',
  7962. ];
  7963. return $map[$scene] ?? $scene;
  7964. }
  7965. /**
  7966. * 邮件发送日志列表
  7967. */
  7968. public function emailLog()
  7969. {
  7970. $this->relationSearch = false;
  7971. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  7972. $this->request->filter(['strip_tags', 'trim']);
  7973. $bakModel = $this->model;
  7974. $this->model = new \app\admin\model\Purchaseemailsendlog;
  7975. if ($this->request->isAjax()) {
  7976. $this->ensurePurchaseEmailSendLogTableOnce();
  7977. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  7978. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  7979. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  7980. $list = $this->model
  7981. ->where($where)
  7982. ->order($sortField, $orderDir)
  7983. ->paginate($limit);
  7984. $rows = [];
  7985. foreach ($list->items() as $item) {
  7986. $row = is_array($item) ? $item : $item->toArray();
  7987. $scene = trim((string)($row['scene'] ?? ''));
  7988. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  7989. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  7990. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  7991. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  7992. $rows[] = $row;
  7993. }
  7994. $this->model = $bakModel;
  7995. return json(['total' => $list->total(), 'rows' => $rows]);
  7996. }
  7997. $this->model = $bakModel;
  7998. return $this->view->fetch('procuremen/emaillog');
  7999. }
  8000. /**
  8001. * 协助下发弹窗(选多家供应商并通知)
  8002. */
  8003. public function pickReview()
  8004. {
  8005. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  8006. $this->error(__('You have no permission'));
  8007. }
  8008. if ($this->request->isPost()) {
  8009. $this->error('请使用弹窗内「确认下发」提交');
  8010. }
  8011. $this->view->assign('pickMode', 1);
  8012. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8013. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8014. }
  8015. /**
  8016. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8017. */
  8018. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  8019. {
  8020. static $done = false;
  8021. if ($done) {
  8022. return;
  8023. }
  8024. $done = true;
  8025. try {
  8026. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  8027. if (empty($cols)) {
  8028. Db::execute(
  8029. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8030. );
  8031. } else {
  8032. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8033. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8034. Db::execute(
  8035. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8036. );
  8037. }
  8038. }
  8039. } catch (\Throwable $e) {
  8040. // ignore
  8041. }
  8042. }
  8043. /**
  8044. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8045. */
  8046. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8047. {
  8048. static $done = false;
  8049. if ($done) {
  8050. return;
  8051. }
  8052. $done = true;
  8053. try {
  8054. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8055. if (empty($cols)) {
  8056. Db::execute(
  8057. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8058. );
  8059. }
  8060. } catch (\Throwable $e) {
  8061. // ignore
  8062. }
  8063. try {
  8064. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8065. if (empty($cols2)) {
  8066. Db::execute(
  8067. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8068. );
  8069. }
  8070. } catch (\Throwable $e) {
  8071. // ignore
  8072. }
  8073. }
  8074. /**
  8075. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  8076. */
  8077. protected function ensureRfqSupplierEmailTemplate(): void
  8078. {
  8079. static $done = false;
  8080. if ($done) {
  8081. return;
  8082. }
  8083. $done = true;
  8084. $content = "您好,{company_name}:\n\n"
  8085. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  8086. . "需求编号:{ccydh}\n"
  8087. . "印件名称:{cyjmc}\n"
  8088. . "{process_lines}\n\n"
  8089. . "请在 {deadline} 前完成回复。\n\n"
  8090. . "平台链接:{platform_url}\n";
  8091. try {
  8092. $row = Db::table('purchase_sms_template')
  8093. ->where('scene', 'rfq_supplier_email')
  8094. ->find();
  8095. } catch (\Throwable $e) {
  8096. return;
  8097. }
  8098. $now = date('Y-m-d H:i:s');
  8099. if (is_array($row) && $row !== []) {
  8100. return;
  8101. }
  8102. try {
  8103. $data = [
  8104. 'scene' => 'rfq_supplier_email',
  8105. 'title' => '供应商询价通知',
  8106. 'content' => $content,
  8107. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  8108. 'status' => 1,
  8109. ];
  8110. try {
  8111. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8112. } catch (\Throwable $e) {
  8113. $cols = [];
  8114. }
  8115. $colNames = [];
  8116. foreach ($cols as $c) {
  8117. if (!is_array($c)) {
  8118. continue;
  8119. }
  8120. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8121. if ($n !== '') {
  8122. $colNames[$n] = true;
  8123. }
  8124. }
  8125. if (isset($colNames['updatetime'])) {
  8126. $data['updatetime'] = $now;
  8127. }
  8128. if (isset($colNames['createtime'])) {
  8129. $data['createtime'] = $now;
  8130. }
  8131. Db::table('purchase_sms_template')->insert($data);
  8132. } catch (\Throwable $e) {
  8133. // ignore
  8134. }
  8135. }
  8136. /**
  8137. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8138. */
  8139. protected function ensureRfqSalesmanEmailTemplate(): void
  8140. {
  8141. static $done = false;
  8142. if ($done) {
  8143. return;
  8144. }
  8145. $done = true;
  8146. $content = "您好,{contact_name}:\n\n"
  8147. . "有新的协助采购询价需求,请知悉。\n"
  8148. . "印件名称:{cyjmc}\n"
  8149. . "工序名称:{cgymc}\n"
  8150. . "本次数量:{this_quantity}\n"
  8151. . "供应商:{supplier_name}\n"
  8152. . "需求发起人:{cywyxm}\n";
  8153. try {
  8154. $row = Db::table('purchase_sms_template')
  8155. ->where('scene', 'rfq_salesman_email')
  8156. ->find();
  8157. } catch (\Throwable $e) {
  8158. return;
  8159. }
  8160. $now = date('Y-m-d H:i:s');
  8161. if (is_array($row) && $row !== []) {
  8162. $old = (string)($row['content'] ?? '');
  8163. $needMigrate = (strpos($old, '需求编号:{ccydh}') !== false)
  8164. || (strpos($old, '{supplier_name}') === false && strpos($old, '供应商:') === false);
  8165. if ($needMigrate) {
  8166. $data = ['content' => $content];
  8167. try {
  8168. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8169. if (!empty($cols)) {
  8170. $data['updatetime'] = $now;
  8171. }
  8172. } catch (\Throwable $e) {
  8173. }
  8174. try {
  8175. Db::table('purchase_sms_template')
  8176. ->where('id', (int)($row['id'] ?? 0))
  8177. ->update($data);
  8178. } catch (\Throwable $e) {
  8179. }
  8180. }
  8181. return;
  8182. }
  8183. try {
  8184. $data = [
  8185. 'scene' => 'rfq_salesman_email',
  8186. 'title' => '询价邮箱通知',
  8187. 'content' => $content,
  8188. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8189. 'status' => 1,
  8190. ];
  8191. try {
  8192. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8193. } catch (\Throwable $e) {
  8194. $cols = [];
  8195. }
  8196. $colNames = [];
  8197. foreach ($cols as $c) {
  8198. if (!is_array($c)) {
  8199. continue;
  8200. }
  8201. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8202. if ($n !== '') {
  8203. $colNames[$n] = true;
  8204. }
  8205. }
  8206. if (isset($colNames['updatetime'])) {
  8207. $data['updatetime'] = $now;
  8208. }
  8209. if (isset($colNames['createtime'])) {
  8210. $data['createtime'] = $now;
  8211. }
  8212. Db::table('purchase_sms_template')->insert($data);
  8213. } catch (\Throwable $e) {
  8214. // ignore
  8215. }
  8216. }
  8217. /**
  8218. * 询价多选字段:数组或字符串统一为顿号拼接
  8219. *
  8220. * @param mixed $raw
  8221. */
  8222. protected function joinRfqMultiSelectValues($raw): string
  8223. {
  8224. $parts = [];
  8225. if (is_array($raw)) {
  8226. foreach ($raw as $item) {
  8227. if (is_array($item)) {
  8228. continue;
  8229. }
  8230. $v = trim((string)$item);
  8231. if ($v !== '') {
  8232. $parts[] = $v;
  8233. }
  8234. }
  8235. } else {
  8236. $s = trim((string)$raw);
  8237. if ($s !== '') {
  8238. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8239. $v = trim((string)$piece);
  8240. if ($v !== '') {
  8241. $parts[] = $v;
  8242. }
  8243. }
  8244. }
  8245. }
  8246. $parts = array_values(array_unique($parts));
  8247. return implode('、', $parts);
  8248. }
  8249. /**
  8250. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8251. *
  8252. * @return string[]
  8253. */
  8254. protected function loadRfqSupplierNameOptions(): array
  8255. {
  8256. $out = [];
  8257. try {
  8258. $rows = Db::table('customer')
  8259. ->where(function ($q) {
  8260. $q->where('status', 1)
  8261. ->whereOr('status', '1')
  8262. ->whereOr('status', '')
  8263. ->whereNull('status');
  8264. })
  8265. ->order('id', 'desc')
  8266. ->column('company_name');
  8267. } catch (\Throwable $e) {
  8268. return [];
  8269. }
  8270. if (!is_array($rows)) {
  8271. return [];
  8272. }
  8273. foreach ($rows as $name) {
  8274. $name = trim((string)$name);
  8275. if ($name === '' || isset($out[$name])) {
  8276. continue;
  8277. }
  8278. $out[$name] = $name;
  8279. }
  8280. return array_values($out);
  8281. }
  8282. /**
  8283. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8284. */
  8285. protected function rfqNotifySalesmanAuthGroupId(): int
  8286. {
  8287. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8288. if ($id > 0) {
  8289. return $id;
  8290. }
  8291. try {
  8292. $found = Db::name('auth_group')
  8293. ->where('name', '业务员')
  8294. ->where('status', 'normal')
  8295. ->order('id', 'asc')
  8296. ->value('id');
  8297. $id = (int)$found;
  8298. } catch (\Throwable $e) {
  8299. $id = 0;
  8300. }
  8301. return $id > 0 ? $id : 12;
  8302. }
  8303. /**
  8304. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8305. *
  8306. * @return string[]
  8307. */
  8308. protected function loadRfqSalesmanNameOptions(): array
  8309. {
  8310. $out = [];
  8311. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8312. $name = trim((string)($row['name'] ?? ''));
  8313. if ($name !== '') {
  8314. $out[] = $name;
  8315. }
  8316. }
  8317. return $out;
  8318. }
  8319. /**
  8320. * 业务员角色组下管理员:姓名、邮箱、手机
  8321. *
  8322. * @return array<int, array{name:string,email:string,mobile:string}>
  8323. */
  8324. protected function loadRfqSalesmanContactOptions(): array
  8325. {
  8326. $out = [];
  8327. $seen = [];
  8328. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8329. if ($groupId <= 0) {
  8330. return [];
  8331. }
  8332. try {
  8333. $adminIds = Db::name('auth_group_access')
  8334. ->where('group_id', $groupId)
  8335. ->column('uid');
  8336. } catch (\Throwable $e) {
  8337. return [];
  8338. }
  8339. $adminIds = is_array($adminIds)
  8340. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8341. : [];
  8342. if ($adminIds === []) {
  8343. return [];
  8344. }
  8345. try {
  8346. $rows = Db::name('admin')
  8347. ->where('status', 'normal')
  8348. ->where('id', 'in', $adminIds)
  8349. ->order('id', 'asc')
  8350. ->field('id,nickname,username,email,mobile')
  8351. ->select();
  8352. } catch (\Throwable $e) {
  8353. return [];
  8354. }
  8355. if (!is_array($rows)) {
  8356. return [];
  8357. }
  8358. foreach ($rows as $row) {
  8359. if (!is_array($row)) {
  8360. continue;
  8361. }
  8362. $name = trim((string)($row['nickname'] ?? ''));
  8363. if ($name === '') {
  8364. $name = trim((string)($row['username'] ?? ''));
  8365. }
  8366. if ($name === '' || isset($seen[$name])) {
  8367. continue;
  8368. }
  8369. $seen[$name] = true;
  8370. $out[] = [
  8371. 'name' => $name,
  8372. 'email' => trim((string)($row['email'] ?? '')),
  8373. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8374. ];
  8375. }
  8376. return $out;
  8377. }
  8378. /**
  8379. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8380. *
  8381. * @return string[]
  8382. */
  8383. protected function loadRfqDeptNameOptions(): array
  8384. {
  8385. $out = [];
  8386. // ERP 承揽部门(主来源)
  8387. try {
  8388. $vals = Db::table('mcyd')
  8389. ->where('CCLBMMC', '<>', '')
  8390. ->whereNotNull('CCLBMMC')
  8391. ->distinct(true)
  8392. ->limit(300)
  8393. ->column('CCLBMMC');
  8394. } catch (\Throwable $e) {
  8395. $vals = [];
  8396. }
  8397. if (is_array($vals)) {
  8398. foreach ($vals as $v) {
  8399. $v = trim((string)$v);
  8400. if ($v === '' || isset($out[$v])) {
  8401. continue;
  8402. }
  8403. $out[$v] = $v;
  8404. }
  8405. }
  8406. // 手工询价历史部门补全
  8407. try {
  8408. $poVals = Db::table('purchase_order')
  8409. ->where('CCLBMMC', '<>', '')
  8410. ->whereNotNull('CCLBMMC')
  8411. ->distinct(true)
  8412. ->limit(200)
  8413. ->column('CCLBMMC');
  8414. } catch (\Throwable $e) {
  8415. $poVals = [];
  8416. }
  8417. if (is_array($poVals)) {
  8418. foreach ($poVals as $v) {
  8419. $v = trim((string)$v);
  8420. if ($v === '' || isset($out[$v])) {
  8421. continue;
  8422. }
  8423. $out[$v] = $v;
  8424. }
  8425. }
  8426. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8427. if (!isset($out[$preset])) {
  8428. $out[$preset] = $preset;
  8429. }
  8430. }
  8431. $list = array_values($out);
  8432. // 常用部门靠前
  8433. usort($list, static function ($a, $b) {
  8434. $weight = [
  8435. '营销中心' => 1,
  8436. '业务部' => 2,
  8437. '市场部' => 3,
  8438. '外贸部' => 4,
  8439. '新华技术业务部' => 5,
  8440. ];
  8441. $wa = $weight[$a] ?? 100;
  8442. $wb = $weight[$b] ?? 100;
  8443. if ($wa !== $wb) {
  8444. return $wa <=> $wb;
  8445. }
  8446. return strcmp((string)$a, (string)$b);
  8447. });
  8448. return $list;
  8449. }
  8450. /**
  8451. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8452. */
  8453. public function add()
  8454. {
  8455. if ($this->request->isPost()) {
  8456. $params = $this->request->post('row/a');
  8457. if (!is_array($params)) {
  8458. $this->error(__('Parameter %s can not be empty', ''));
  8459. }
  8460. [, $adminName] = $this->GetUseName();
  8461. $params['cywyxm'] = $adminName;
  8462. try {
  8463. $sid = $this->saveManualPickOrder($params);
  8464. } catch (\InvalidArgumentException $e) {
  8465. $this->error($e->getMessage());
  8466. } catch (\Throwable $e) {
  8467. $this->error($e->getMessage());
  8468. }
  8469. $this->success('新增成功', '', [
  8470. 'scydgy_id' => $sid,
  8471. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8472. ]);
  8473. }
  8474. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8475. [, $adminName] = $this->GetUseName();
  8476. $this->view->assign('adminNickname', $adminName);
  8477. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8478. $this->view->assign('defaultCclbmmc', '营销中心');
  8479. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8480. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8481. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8482. return $this->view->fetch();
  8483. }
  8484. /**
  8485. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  8486. */
  8487. public function rfqlist()
  8488. {
  8489. $this->relationSearch = false;
  8490. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8491. $this->request->filter(['strip_tags', 'trim']);
  8492. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8493. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8494. $this->ensureRfqSalesmanEmailTemplate();
  8495. $this->ensureRfqSupplierEmailTemplate();
  8496. if ($this->request->isAjax()) {
  8497. try {
  8498. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8499. $limit = max(10, min(500, (int)$limit));
  8500. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8501. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8502. $filterYm = date('Y-m');
  8503. }
  8504. $applyFilters = function ($query) use ($where, $filterYm) {
  8505. $query->where('scydgy_id', '<', 0);
  8506. $this->applyPurchaseOrderNotDeletedWhere($query);
  8507. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  8508. $this->applyRfqListMonthFilter($query, $filterYm);
  8509. if (!empty($where)) {
  8510. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  8511. $safeWhere = [];
  8512. $skipFields = [
  8513. 'supplier_name' => true,
  8514. 'progress_text' => true,
  8515. 'createtime_text' => true,
  8516. 'notify_time_text' => true,
  8517. 'can_notify_salesman' => true,
  8518. 'has_issued' => true,
  8519. 'has_quoted' => true,
  8520. ];
  8521. foreach ((array)$where as $cond) {
  8522. if (!is_array($cond) || !isset($cond[0])) {
  8523. continue;
  8524. }
  8525. $field = (string)$cond[0];
  8526. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  8527. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  8528. if (isset($skipFields[$fieldBase])) {
  8529. continue;
  8530. }
  8531. if ($fieldBase === 'supplier_name') {
  8532. continue;
  8533. }
  8534. $safeWhere[] = $cond;
  8535. }
  8536. if ($safeWhere !== []) {
  8537. $query->where($safeWhere);
  8538. }
  8539. }
  8540. };
  8541. $countQuery = Db::table('purchase_order');
  8542. $applyFilters($countQuery);
  8543. $total = (int)$countQuery->count();
  8544. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8545. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8546. $listQuery = Db::table('purchase_order');
  8547. $applyFilters($listQuery);
  8548. $rows = $listQuery
  8549. ->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')
  8550. ->order($sortField, $orderDir)
  8551. ->limit($offset, $limit)
  8552. ->select();
  8553. if (!is_array($rows)) {
  8554. $rows = [];
  8555. }
  8556. $sidList = [];
  8557. foreach ($rows as $r) {
  8558. if (!is_array($r)) {
  8559. continue;
  8560. }
  8561. $sid = (int)($r['scydgy_id'] ?? 0);
  8562. if ($sid < 0) {
  8563. $sidList[$sid] = true;
  8564. }
  8565. }
  8566. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  8567. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  8568. $out = [];
  8569. foreach ($rows as $r) {
  8570. if (!is_array($r)) {
  8571. continue;
  8572. }
  8573. $sid = (int)($r['scydgy_id'] ?? 0);
  8574. if ($sid >= 0) {
  8575. continue;
  8576. }
  8577. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8578. if ($createdText === '') {
  8579. $createdText = trim((string)($r['dStamp'] ?? ''));
  8580. }
  8581. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  8582. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  8583. if ($supplier === '') {
  8584. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  8585. }
  8586. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  8587. || isset($issuedSidSet[$sid]);
  8588. $hasQuoted = isset($quotedSidSet[$sid]);
  8589. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  8590. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  8591. $out[] = [
  8592. 'id' => (int)($r['id'] ?? 0),
  8593. 'scydgy_id' => $sid,
  8594. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  8595. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  8596. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  8597. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  8598. 'CDW' => trim((string)($r['CDW'] ?? '')),
  8599. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  8600. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  8601. 'CDF' => trim((string)($r['CDF'] ?? '')),
  8602. 'supplier_name' => $supplier,
  8603. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  8604. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  8605. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  8606. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  8607. 'notify_time_text' => $notifyTimeText,
  8608. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  8609. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  8610. 'has_issued' => $hasIssued ? 1 : 0,
  8611. 'has_quoted' => $hasQuoted ? 1 : 0,
  8612. 'can_notify_salesman' => $canNotifySalesman,
  8613. 'createtime' => $r['createtime'] ?? null,
  8614. 'createtime_text' => $createdText,
  8615. ];
  8616. }
  8617. return json(['total' => $total, 'rows' => $out]);
  8618. } catch (\Throwable $e) {
  8619. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  8620. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  8621. }
  8622. }
  8623. $sidebar = $this->loadRfqSidebarYearMonths();
  8624. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  8625. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  8626. [, $adminName] = $this->GetUseName();
  8627. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  8628. $this->view->assign('adminNickname', $adminName);
  8629. $this->view->assign('defaultYm', $defaultYm);
  8630. $this->view->assign('sidebarYearMonths', $sidebar);
  8631. return $this->view->fetch('procuremen/rfqlist');
  8632. }
  8633. /**
  8634. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  8635. *
  8636. * @param array<int, array{year:string, months:array}> $sidebar
  8637. */
  8638. protected function resolveRfqListDefaultYm(array $sidebar): string
  8639. {
  8640. $current = date('Y-m');
  8641. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  8642. if (in_array($current, $yms, true)) {
  8643. return $current;
  8644. }
  8645. if ($yms !== []) {
  8646. rsort($yms, SORT_STRING);
  8647. return (string)$yms[0];
  8648. }
  8649. return $current;
  8650. }
  8651. /**
  8652. * 手工询价列表左侧月份(按 createtime / dStamp)
  8653. *
  8654. * @return array<int, array{year:string, months:array}>
  8655. */
  8656. protected function loadRfqSidebarYearMonths(): array
  8657. {
  8658. $ymSet = [];
  8659. try {
  8660. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  8661. $this->applyPurchaseOrderNotDeletedWhere($q);
  8662. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  8663. } catch (\Throwable $e) {
  8664. $rows = [];
  8665. }
  8666. if (!is_array($rows)) {
  8667. $rows = [];
  8668. }
  8669. foreach ($rows as $r) {
  8670. if (!is_array($r)) {
  8671. continue;
  8672. }
  8673. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8674. if ($t === '') {
  8675. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  8676. }
  8677. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  8678. $ymSet[$m[1] . '-' . $m[2]] = true;
  8679. }
  8680. }
  8681. return $this->buildYearMonthSidebar(array_keys($ymSet));
  8682. }
  8683. /**
  8684. * 手工询价可见范围(用于详情/操作校验):
  8685. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  8686. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  8687. */
  8688. protected function applyManualRfqViewerWhere($query): void
  8689. {
  8690. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  8691. return;
  8692. }
  8693. [, $adminName] = $this->GetUseName();
  8694. $adminName = trim((string)$adminName);
  8695. if ($adminName === '') {
  8696. $query->whereRaw('1 = 0');
  8697. return;
  8698. }
  8699. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  8700. $query->where(function ($q) use ($adminName) {
  8701. $q->where('cywyxm', $adminName)
  8702. ->whereOr('notify_salesman', $adminName)
  8703. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  8704. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  8705. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  8706. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  8707. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  8708. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  8709. });
  8710. }
  8711. /**
  8712. * 当前用户是否可查看/操作该手工询价单
  8713. */
  8714. protected function canViewManualRfqOrder(array $po): bool
  8715. {
  8716. if ($this->auth->isSuperAdmin()) {
  8717. return true;
  8718. }
  8719. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  8720. if ($this->hasProcuremenPerm(['rfqlist'])) {
  8721. return true;
  8722. }
  8723. [, $adminName] = $this->GetUseName();
  8724. $adminName = trim((string)$adminName);
  8725. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  8726. return true;
  8727. }
  8728. if ($adminName !== '') {
  8729. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8730. if ($n === $adminName) {
  8731. return true;
  8732. }
  8733. }
  8734. }
  8735. return false;
  8736. }
  8737. /**
  8738. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  8739. */
  8740. protected function applyRfqListMonthFilter($query, string $ym): void
  8741. {
  8742. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8743. $ym = date('Y-m');
  8744. }
  8745. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  8746. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  8747. $query->whereRaw(
  8748. "("
  8749. . "CASE "
  8750. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  8751. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  8752. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  8753. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  8754. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  8755. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  8756. . "END"
  8757. . ") LIKE '{$ymEsc}-%'"
  8758. );
  8759. }
  8760. /**
  8761. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  8762. */
  8763. public function rfqlistDetails()
  8764. {
  8765. return $this->details();
  8766. }
  8767. /**
  8768. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  8769. */
  8770. public function rfqnotifysalesmen()
  8771. {
  8772. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  8773. $this->error(__('You have no permission'));
  8774. }
  8775. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8776. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8777. $sid = (int)$this->request->param('scydgy_id', 0);
  8778. if ($sid >= 0) {
  8779. $this->error('仅支持手工新增询价单');
  8780. }
  8781. $po = $this->loadManualRfqOrderForNotify($sid);
  8782. $selectedMap = [];
  8783. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8784. $selectedMap[$n] = true;
  8785. }
  8786. $list = [];
  8787. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8788. $name = trim((string)($row['name'] ?? ''));
  8789. if ($name === '') {
  8790. continue;
  8791. }
  8792. $email = trim((string)($row['email'] ?? ''));
  8793. $mobile = trim((string)($row['mobile'] ?? ''));
  8794. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8795. $list[] = [
  8796. 'name' => $name,
  8797. 'email' => $email,
  8798. 'mobile' => $mobile,
  8799. 'can_select' => $hasEmail ? 1 : 0,
  8800. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  8801. ];
  8802. }
  8803. $canNotify = $this->canRfqNotifySalesman($po);
  8804. $this->success('', null, [
  8805. 'scydgy_id' => $sid,
  8806. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  8807. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  8808. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  8809. 'can_notify_salesman' => $canNotify ? 1 : 0,
  8810. 'list' => $list,
  8811. ]);
  8812. }
  8813. /**
  8814. * 查询询价 — 补加通知业务员可选名单
  8815. */
  8816. public function rfqsalesmanoptions()
  8817. {
  8818. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  8819. $this->error(__('You have no permission'));
  8820. }
  8821. $out = [];
  8822. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8823. $email = trim((string)($row['email'] ?? ''));
  8824. $mobile = trim((string)($row['mobile'] ?? ''));
  8825. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8826. $out[] = [
  8827. 'name' => (string)($row['name'] ?? ''),
  8828. 'email' => $email,
  8829. 'mobile' => $mobile,
  8830. 'can_select' => $hasEmail ? 1 : 0,
  8831. ];
  8832. }
  8833. $this->success('', null, ['list' => $out]);
  8834. }
  8835. /**
  8836. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  8837. */
  8838. public function rfqappendsalesmen()
  8839. {
  8840. if (!$this->request->isPost()) {
  8841. $this->error(__('Invalid parameters'));
  8842. }
  8843. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  8844. $this->error(__('You have no permission'));
  8845. }
  8846. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8847. $sid = (int)$this->request->post('scydgy_id', 0);
  8848. if ($sid >= 0) {
  8849. $this->error('仅支持手工新增询价单');
  8850. }
  8851. $po = $this->loadManualRfqOrderForNotify($sid);
  8852. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  8853. $this->error('订单已完结,无法添加业务员');
  8854. }
  8855. $raw = $this->request->post('salesmen/a', []);
  8856. if (!is_array($raw) || $raw === []) {
  8857. $salesmenJson = $this->request->post('salesmen_json', '');
  8858. if (is_string($salesmenJson) && $salesmenJson !== '') {
  8859. $decoded = json_decode($salesmenJson, true);
  8860. $raw = is_array($decoded) ? $decoded : [];
  8861. }
  8862. }
  8863. $addNames = [];
  8864. foreach ((array)$raw as $item) {
  8865. if (is_array($item)) {
  8866. $n = trim((string)($item['name'] ?? ''));
  8867. } else {
  8868. $n = trim((string)$item);
  8869. }
  8870. if ($n !== '') {
  8871. $addNames[] = $n;
  8872. }
  8873. }
  8874. $addNames = array_values(array_unique($addNames));
  8875. if ($addNames === []) {
  8876. $this->error('请选择要添加的业务员');
  8877. }
  8878. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  8879. $allowedMap = [];
  8880. foreach ($allowedOptions as $opt) {
  8881. $n = trim((string)($opt['name'] ?? ''));
  8882. if ($n === '') {
  8883. continue;
  8884. }
  8885. $email = trim((string)($opt['email'] ?? ''));
  8886. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  8887. }
  8888. foreach ($addNames as $n) {
  8889. if (!array_key_exists($n, $allowedMap)) {
  8890. $this->error('业务员不在可选名单中:' . $n);
  8891. }
  8892. if (!$allowedMap[$n]) {
  8893. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  8894. }
  8895. }
  8896. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  8897. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  8898. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  8899. try {
  8900. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  8901. } catch (\Throwable $e) {
  8902. $this->error('保存失败:' . $e->getMessage());
  8903. }
  8904. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8905. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  8906. $this->success('已添加业务员', null, [
  8907. 'scydgy_id' => $sid,
  8908. 'notify_salesman' => $mergedStr,
  8909. 'added_count' => count($addNames),
  8910. ]);
  8911. }
  8912. /**
  8913. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  8914. */
  8915. public function rfqnotifysalesman()
  8916. {
  8917. if (!$this->request->isPost()) {
  8918. $this->error(__('Invalid parameters'));
  8919. }
  8920. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  8921. $this->error(__('You have no permission'));
  8922. }
  8923. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8924. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8925. $sid = (int)$this->request->post('scydgy_id', 0);
  8926. if ($sid >= 0) {
  8927. $this->error('仅支持手工新增询价单');
  8928. }
  8929. $po = $this->loadManualRfqOrderForNotify($sid);
  8930. $this->assertRfqCanNotifySalesman($po);
  8931. $raw = $this->request->post('salesmen/a', []);
  8932. if (!is_array($raw) || $raw === []) {
  8933. $salesmenJson = $this->request->post('salesmen_json', '');
  8934. if (is_string($salesmenJson) && $salesmenJson !== '') {
  8935. $decoded = json_decode($salesmenJson, true);
  8936. $raw = is_array($decoded) ? $decoded : [];
  8937. }
  8938. }
  8939. // 兼容旧参数:notify_all / 单人 name
  8940. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  8941. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  8942. }
  8943. if ((!is_array($raw) || $raw === [])) {
  8944. $oneName = trim((string)$this->request->post('name', ''));
  8945. if ($oneName !== '') {
  8946. $raw = [$oneName];
  8947. }
  8948. }
  8949. $selectedNames = [];
  8950. foreach ((array)$raw as $item) {
  8951. if (is_array($item)) {
  8952. $n = trim((string)($item['name'] ?? ''));
  8953. } else {
  8954. $n = trim((string)$item);
  8955. }
  8956. if ($n !== '') {
  8957. $selectedNames[] = $n;
  8958. }
  8959. }
  8960. $selectedNames = array_values(array_unique($selectedNames));
  8961. if ($selectedNames === []) {
  8962. $this->error('请选择要通知的业务员');
  8963. }
  8964. $optionMap = [];
  8965. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  8966. $n = trim((string)($opt['name'] ?? ''));
  8967. if ($n === '') {
  8968. continue;
  8969. }
  8970. $optionMap[$n] = $opt;
  8971. }
  8972. $targets = [];
  8973. foreach ($selectedNames as $n) {
  8974. if (!isset($optionMap[$n])) {
  8975. $this->error('业务员不在可选名单中:' . $n);
  8976. }
  8977. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  8978. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  8979. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  8980. }
  8981. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  8982. $targets[] = $resolved[0] ?? [
  8983. 'admin_id' => 0,
  8984. 'name' => $n,
  8985. 'email' => $email,
  8986. ];
  8987. }
  8988. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  8989. try {
  8990. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8991. 'notify_salesman' => $mergedStr,
  8992. ]);
  8993. } catch (\Throwable $e) {
  8994. $this->error('保存通知业务员失败:' . $e->getMessage());
  8995. }
  8996. $po['notify_salesman'] = $mergedStr;
  8997. $mailConfig = $this->loadMailerConfig();
  8998. if (empty($mailConfig['host'])) {
  8999. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9000. }
  9001. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9002. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9003. }
  9004. $this->ensureRfqSalesmanEmailTemplate();
  9005. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  9006. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  9007. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  9008. $qty = trim((string)($po['This_quantity'] ?? ''));
  9009. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  9010. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  9011. if ($supplier === '') {
  9012. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  9013. }
  9014. try {
  9015. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  9016. } catch (\Throwable $e) {
  9017. $this->error($e->getMessage());
  9018. }
  9019. $okNames = [];
  9020. $failMsgs = [];
  9021. foreach ($targets as $contact) {
  9022. $toEmail = trim((string)($contact['email'] ?? ''));
  9023. $toName = trim((string)($contact['name'] ?? ''));
  9024. $notifyVars = [
  9025. 'contact_name' => $toName,
  9026. 'salesman_name' => $toName,
  9027. 'company_name' => $toName,
  9028. 'email' => $toEmail,
  9029. 'ccydh' => $ccydh,
  9030. 'cyjmc' => $cyjmc,
  9031. 'cgymc' => $cgymc,
  9032. 'this_quantity' => $qty,
  9033. 'supplier_name' => $supplier,
  9034. 'cywyxm' => $cywyxm,
  9035. ];
  9036. try {
  9037. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  9038. $mailSubject = $mailSubjectTpl;
  9039. foreach ($notifyVars as $k => $v) {
  9040. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  9041. }
  9042. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  9043. $mailSubject = trim((string)$mailSubject);
  9044. if ($mailSubject === '') {
  9045. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  9046. }
  9047. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9048. $bundle = [
  9049. 'company_name' => $toName,
  9050. 'email' => $toEmail,
  9051. 'mail_plain' => $mailPlain,
  9052. 'mail_body' => $mailBody,
  9053. 'ccydh' => $ccydh,
  9054. 'email_log_scene' => 'rfq_salesman',
  9055. 'email_log_scydgy_id' => $sid,
  9056. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  9057. 'notify_vars' => $notifyVars,
  9058. ];
  9059. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  9060. $okNames[] = $toName . '(' . $toEmail . ')';
  9061. } catch (\Throwable $e) {
  9062. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  9063. }
  9064. }
  9065. if ($okNames === []) {
  9066. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  9067. }
  9068. $now = date('Y-m-d H:i:s');
  9069. try {
  9070. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9071. 'rfq_salesman_notified' => 1,
  9072. 'rfq_salesman_notify_time' => $now,
  9073. ]);
  9074. } catch (\Throwable $e) {
  9075. // ignore
  9076. }
  9077. $this->addOrderLog(
  9078. $sid,
  9079. 'rfq_notify_salesman',
  9080. '邮箱通知业务员:' . implode('、', $okNames),
  9081. (int)($po['id'] ?? 0)
  9082. );
  9083. $msg = '已通知 ' . count($okNames) . ' 人';
  9084. if ($failMsgs !== []) {
  9085. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9086. }
  9087. $this->success($msg, null, [
  9088. 'scydgy_id' => $sid,
  9089. 'notify_salesman' => $mergedStr,
  9090. 'rfq_salesman_notified' => 1,
  9091. 'rfq_salesman_notify_time' => $now,
  9092. 'notify_time_text' => $now,
  9093. 'ok_count' => count($okNames),
  9094. 'fail_count' => count($failMsgs),
  9095. ]);
  9096. }
  9097. /**
  9098. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9099. */
  9100. public function rfqissuesuppliers()
  9101. {
  9102. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  9103. $this->error(__('You have no permission'));
  9104. }
  9105. $sid = (int)$this->request->param('scydgy_id', 0);
  9106. if ($sid >= 0) {
  9107. $this->error('仅支持手工新增询价单');
  9108. }
  9109. $po = $this->loadManualRfqOrderForNotify($sid);
  9110. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9111. if ($supplierRaw === '') {
  9112. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9113. }
  9114. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9115. $list = [];
  9116. foreach ($names as $name) {
  9117. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9118. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9119. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9120. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9121. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9122. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9123. $list[] = [
  9124. 'name' => $name,
  9125. 'username' => $username,
  9126. 'email' => $email,
  9127. 'phone' => $phone,
  9128. 'can_notify' => $okEmail ? 1 : 0,
  9129. 'found' => is_array($contact) ? 1 : 0,
  9130. ];
  9131. }
  9132. $this->success('', null, [
  9133. 'scydgy_id' => $sid,
  9134. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9135. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9136. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9137. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9138. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9139. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9140. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9141. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9142. 'list' => $list,
  9143. ]);
  9144. }
  9145. /**
  9146. * 查询询价 — 补加供应商可选名单
  9147. */
  9148. public function rfqsupplieroptions()
  9149. {
  9150. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9151. $this->error(__('You have no permission'));
  9152. }
  9153. $names = array_values($this->loadRfqSupplierNameOptions());
  9154. $out = [];
  9155. foreach ($names as $name) {
  9156. $out[] = ['name' => $name];
  9157. }
  9158. $this->success('', null, ['list' => $out]);
  9159. }
  9160. /**
  9161. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9162. */
  9163. public function rfqappendsuppliers()
  9164. {
  9165. if (!$this->request->isPost()) {
  9166. $this->error(__('Invalid parameters'));
  9167. }
  9168. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  9169. $this->error(__('You have no permission'));
  9170. }
  9171. $sid = (int)$this->request->post('scydgy_id', 0);
  9172. if ($sid >= 0) {
  9173. $this->error('仅支持手工新增询价单');
  9174. }
  9175. $po = $this->loadManualRfqOrderForNotify($sid);
  9176. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9177. $this->error('订单已完结,无法补加供应商');
  9178. }
  9179. $raw = $this->request->post('suppliers/a', []);
  9180. if (!is_array($raw) || $raw === []) {
  9181. $suppliersJson = $this->request->post('suppliers_json', '');
  9182. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9183. $decoded = json_decode($suppliersJson, true);
  9184. $raw = is_array($decoded) ? $decoded : [];
  9185. }
  9186. }
  9187. $addNames = [];
  9188. foreach ((array)$raw as $item) {
  9189. if (is_array($item)) {
  9190. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9191. } else {
  9192. $n = trim((string)$item);
  9193. }
  9194. if ($n !== '') {
  9195. $addNames[] = $n;
  9196. }
  9197. }
  9198. $addNames = array_values(array_unique($addNames));
  9199. if ($addNames === []) {
  9200. $this->error('请选择要补加的供应商');
  9201. }
  9202. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9203. if ($existingRaw === '') {
  9204. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9205. }
  9206. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9207. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9208. try {
  9209. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9210. } catch (\Throwable $e) {
  9211. $this->error('保存失败:' . $e->getMessage());
  9212. }
  9213. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9214. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9215. $this->success('已补加供应商', null, [
  9216. 'scydgy_id' => $sid,
  9217. 'cGzzxMc' => $mergedStr,
  9218. 'added_count' => count($addNames),
  9219. ]);
  9220. }
  9221. /**
  9222. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9223. */
  9224. public function rfqissue()
  9225. {
  9226. if (!$this->request->isPost()) {
  9227. $this->error(__('Invalid parameters'));
  9228. }
  9229. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  9230. $this->error(__('You have no permission'));
  9231. }
  9232. $this->ensureRfqSupplierEmailTemplate();
  9233. $sid = (int)$this->request->post('scydgy_id', 0);
  9234. if ($sid >= 0) {
  9235. $this->error('仅支持手工新增询价单');
  9236. }
  9237. $po = $this->loadManualRfqOrderForNotify($sid);
  9238. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9239. $this->error('订单已完结,无法下发');
  9240. }
  9241. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9242. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9243. $this->error('订单已进入后续流程,无法再下发');
  9244. }
  9245. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9246. if ($supplierRaw === '') {
  9247. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9248. }
  9249. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9250. if ($supplierNames === []) {
  9251. $this->error('请先在新增询价时选择供应商');
  9252. }
  9253. $companies = [];
  9254. $missing = [];
  9255. $noEmail = [];
  9256. foreach ($supplierNames as $name) {
  9257. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9258. if ($contact === null) {
  9259. $missing[] = $name;
  9260. continue;
  9261. }
  9262. $em = trim((string)($contact['email'] ?? ''));
  9263. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9264. $noEmail[] = $name;
  9265. continue;
  9266. }
  9267. $companies[] = $contact;
  9268. }
  9269. if ($missing !== []) {
  9270. $this->error('未找到供应商档案:' . implode('、', $missing));
  9271. }
  9272. if ($noEmail !== []) {
  9273. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9274. }
  9275. if ($companies === []) {
  9276. $this->error('没有可通知的供应商');
  9277. }
  9278. $mailConfig = $this->loadMailerConfig();
  9279. if (empty($mailConfig['host'])) {
  9280. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9281. }
  9282. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9283. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9284. }
  9285. $mergeRow = $po;
  9286. $mergeRow['ID'] = $sid;
  9287. $mergeRow['id'] = $sid;
  9288. $mergeRows = [$mergeRow];
  9289. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9290. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9291. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9292. }
  9293. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9294. $issueTime = date('Y-m-d H:i:s');
  9295. $nameLabels = [];
  9296. foreach ($companies as $c) {
  9297. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9298. }
  9299. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9300. Db::startTrans();
  9301. try {
  9302. $this->upsertPurchaseOrderFromRow(
  9303. $mergeRow,
  9304. $sysRqDb,
  9305. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9306. $issueTime,
  9307. $po,
  9308. null,
  9309. $scoreRule
  9310. );
  9311. foreach ($companies as $c) {
  9312. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9313. }
  9314. Db::commit();
  9315. } catch (\Throwable $e) {
  9316. Db::rollback();
  9317. $this->error($e->getMessage());
  9318. }
  9319. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9320. if ($poId <= 0) {
  9321. try {
  9322. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9323. } catch (\Throwable $e) {
  9324. $poId = 0;
  9325. }
  9326. }
  9327. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9328. $posNotify = [];
  9329. try {
  9330. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9331. if (is_array($fresh)) {
  9332. $fresh['sys_rq'] = $sysRqDb;
  9333. $posNotify = [$fresh];
  9334. }
  9335. } catch (\Throwable $e) {
  9336. $posNotify = [$po];
  9337. $posNotify[0]['sys_rq'] = $sysRqDb;
  9338. }
  9339. $notifyBundle = [
  9340. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9341. 'pos' => $posNotify,
  9342. 'merge_rows' => $mergeRows,
  9343. ];
  9344. $notifyErrors = [];
  9345. foreach ($companies as $c) {
  9346. $cname = trim((string)($c['name'] ?? ''));
  9347. try {
  9348. // 询价下发:仅邮箱通知供应商
  9349. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9350. } catch (\Throwable $e) {
  9351. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9352. }
  9353. }
  9354. if ($notifyErrors !== []) {
  9355. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9356. }
  9357. $this->success('已询价并邮件通知供应商', null, [
  9358. 'scydgy_id' => $sid,
  9359. 'progress_text' => '待报价',
  9360. 'supplier_count' => count($companies),
  9361. ]);
  9362. }
  9363. /**
  9364. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9365. */
  9366. public function rfqissuesendmail()
  9367. {
  9368. if (!$this->request->isPost()) {
  9369. $this->error(__('Invalid parameters'));
  9370. }
  9371. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  9372. $this->error(__('You have no permission'));
  9373. }
  9374. $this->ensureRfqSupplierEmailTemplate();
  9375. $sid = (int)$this->request->post('scydgy_id', 0);
  9376. $companyName = trim((string)$this->request->post('company_name', ''));
  9377. if ($sid >= 0) {
  9378. $this->error('仅支持手工新增询价单');
  9379. }
  9380. if ($companyName === '') {
  9381. $this->error('请选择供应商');
  9382. }
  9383. $po = $this->loadManualRfqOrderForNotify($sid);
  9384. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9385. $this->error('订单已完结,无法发送');
  9386. }
  9387. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9388. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9389. $this->error('订单已进入后续流程,无法再发送');
  9390. }
  9391. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9392. if ($contact === null) {
  9393. $this->error('未找到供应商档案:' . $companyName);
  9394. }
  9395. $email = trim((string)($contact['email'] ?? ''));
  9396. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9397. $this->error('该供应商未填写有效邮箱');
  9398. }
  9399. $mailConfig = $this->loadMailerConfig();
  9400. if (empty($mailConfig['host'])) {
  9401. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9402. }
  9403. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9404. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9405. }
  9406. $mergeRow = $po;
  9407. $mergeRow['ID'] = $sid;
  9408. $mergeRow['id'] = $sid;
  9409. $mergeRows = [$mergeRow];
  9410. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9411. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9412. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9413. }
  9414. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9415. $issueTime = date('Y-m-d H:i:s');
  9416. Db::startTrans();
  9417. try {
  9418. $this->upsertPurchaseOrderFromRow(
  9419. $mergeRow,
  9420. $sysRqDb,
  9421. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9422. $issueTime,
  9423. $po,
  9424. null,
  9425. $scoreRule
  9426. );
  9427. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9428. Db::commit();
  9429. } catch (\Throwable $e) {
  9430. Db::rollback();
  9431. $this->error($e->getMessage());
  9432. }
  9433. $posNotify = [];
  9434. try {
  9435. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9436. if (is_array($fresh)) {
  9437. $fresh['sys_rq'] = $sysRqDb;
  9438. $posNotify = [$fresh];
  9439. }
  9440. } catch (\Throwable $e) {
  9441. $posNotify = [$po];
  9442. $posNotify[0]['sys_rq'] = $sysRqDb;
  9443. }
  9444. $notifyBundle = [
  9445. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9446. 'pos' => $posNotify,
  9447. 'merge_rows' => $mergeRows,
  9448. ];
  9449. try {
  9450. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9451. } catch (\Throwable $e) {
  9452. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  9453. }
  9454. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9455. if ($poId <= 0) {
  9456. try {
  9457. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9458. } catch (\Throwable $e) {
  9459. $poId = 0;
  9460. }
  9461. }
  9462. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  9463. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  9464. 'scydgy_id' => $sid,
  9465. 'company_name' => $companyName,
  9466. ]);
  9467. }
  9468. /**
  9469. * 查询询价 — 查看各供应商报价(单价)
  9470. */
  9471. public function rfqquotes()
  9472. {
  9473. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  9474. $this->error(__('You have no permission'));
  9475. }
  9476. $sid = (int)$this->request->param('scydgy_id', 0);
  9477. if ($sid >= 0) {
  9478. $this->error('仅支持手工新增询价单');
  9479. }
  9480. $po = $this->loadManualRfqOrderForNotify($sid);
  9481. $rows = [];
  9482. try {
  9483. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  9484. $q = Db::table('purchase_order_detail')
  9485. ->where('scydgy_id', $sid)
  9486. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  9487. ->order('id', 'asc');
  9488. $this->applyActivePurchaseOrderDetailWhere($q);
  9489. $rows = $q->select();
  9490. } catch (\Throwable $e) {
  9491. try {
  9492. $q = Db::table('purchase_order_detail')
  9493. ->where('scydgy_id', $sid)
  9494. ->order('id', 'asc');
  9495. $this->applyActivePurchaseOrderDetailWhere($q);
  9496. $rows = $q->select();
  9497. } catch (\Throwable $e2) {
  9498. $rows = [];
  9499. }
  9500. }
  9501. if (!is_array($rows)) {
  9502. $rows = [];
  9503. }
  9504. $list = [];
  9505. foreach ($rows as $row) {
  9506. if (!is_array($row)) {
  9507. continue;
  9508. }
  9509. $amount = trim((string)($row['amount'] ?? ''));
  9510. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  9511. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  9512. $oper = '';
  9513. if ($isQuoted) {
  9514. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  9515. if ($oper === '') {
  9516. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  9517. }
  9518. }
  9519. $list[] = [
  9520. 'id' => (int)($row['id'] ?? 0),
  9521. 'company_name' => trim((string)($row['company_name'] ?? '')),
  9522. 'amount' => $amount,
  9523. 'amount_text' => $isQuoted ? $amount : '',
  9524. 'is_quoted' => $isQuoted,
  9525. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  9526. 'status_name' => trim((string)($row['status_name'] ?? '')),
  9527. 'oper_time' => $oper,
  9528. ];
  9529. }
  9530. $this->success('', null, [
  9531. 'scydgy_id' => $sid,
  9532. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9533. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9534. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9535. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9536. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9537. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9538. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9539. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9540. 'list' => $list,
  9541. ]);
  9542. }
  9543. /**
  9544. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  9545. */
  9546. protected function isRfqOrderIssued(array $po): bool
  9547. {
  9548. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  9549. return true;
  9550. }
  9551. $sid = (int)($po['scydgy_id'] ?? 0);
  9552. if ($sid >= 0) {
  9553. return false;
  9554. }
  9555. try {
  9556. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9557. $this->applyActivePurchaseOrderDetailWhere($q);
  9558. return (int)$q->count() > 0;
  9559. } catch (\Throwable $e) {
  9560. return false;
  9561. }
  9562. }
  9563. /**
  9564. * 批量:已有下发明细的手工询价 scydgy_id
  9565. *
  9566. * @param int[] $scydgyIds
  9567. * @return array<int, bool>
  9568. */
  9569. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  9570. {
  9571. $set = [];
  9572. $ids = [];
  9573. foreach ($scydgyIds as $sid) {
  9574. $sid = (int)$sid;
  9575. if ($sid < 0) {
  9576. $ids[$sid] = true;
  9577. }
  9578. }
  9579. if ($ids === []) {
  9580. return $set;
  9581. }
  9582. try {
  9583. $q = Db::table('purchase_order_detail')
  9584. ->where('scydgy_id', 'in', array_keys($ids))
  9585. ->field('scydgy_id');
  9586. $this->applyActivePurchaseOrderDetailWhere($q);
  9587. $rows = $q->select();
  9588. } catch (\Throwable $e) {
  9589. return $set;
  9590. }
  9591. if (!is_array($rows)) {
  9592. return $set;
  9593. }
  9594. foreach ($rows as $row) {
  9595. if (!is_array($row)) {
  9596. continue;
  9597. }
  9598. $sid = (int)($row['scydgy_id'] ?? 0);
  9599. if ($sid < 0) {
  9600. $set[$sid] = true;
  9601. }
  9602. }
  9603. return $set;
  9604. }
  9605. /**
  9606. * 批量:已填单价(已报价)的手工询价 scydgy_id
  9607. *
  9608. * @param int[] $scydgyIds
  9609. * @return array<int, bool>
  9610. */
  9611. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  9612. {
  9613. $set = [];
  9614. $ids = [];
  9615. foreach ($scydgyIds as $sid) {
  9616. $sid = (int)$sid;
  9617. if ($sid < 0) {
  9618. $ids[$sid] = true;
  9619. }
  9620. }
  9621. if ($ids === []) {
  9622. return $set;
  9623. }
  9624. try {
  9625. $q = Db::table('purchase_order_detail')
  9626. ->where('scydgy_id', 'in', array_keys($ids))
  9627. ->field('scydgy_id,amount');
  9628. $this->applyActivePurchaseOrderDetailWhere($q);
  9629. $rows = $q->select();
  9630. } catch (\Throwable $e) {
  9631. return $set;
  9632. }
  9633. if (!is_array($rows)) {
  9634. return $set;
  9635. }
  9636. foreach ($rows as $row) {
  9637. if (!is_array($row)) {
  9638. continue;
  9639. }
  9640. $amount = trim((string)($row['amount'] ?? ''));
  9641. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  9642. continue;
  9643. }
  9644. $sid = (int)($row['scydgy_id'] ?? 0);
  9645. if ($sid < 0) {
  9646. $set[$sid] = true;
  9647. }
  9648. }
  9649. return $set;
  9650. }
  9651. /**
  9652. * 已下发且至少一家供应商已报价,才允许通知业务员
  9653. */
  9654. protected function canRfqNotifySalesman(array $po): bool
  9655. {
  9656. if (!$this->isRfqOrderIssued($po)) {
  9657. return false;
  9658. }
  9659. $sid = (int)($po['scydgy_id'] ?? 0);
  9660. if ($sid >= 0) {
  9661. return false;
  9662. }
  9663. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  9664. return isset($quoted[$sid]);
  9665. }
  9666. protected function assertRfqCanNotifySalesman(array $po): void
  9667. {
  9668. if (!$this->isRfqOrderIssued($po)) {
  9669. $this->error('请先询价并等待供应商报价后再通知业务员');
  9670. }
  9671. if (!$this->canRfqNotifySalesman($po)) {
  9672. $this->error('供应商尚未报价,暂不能通知业务员');
  9673. }
  9674. }
  9675. /**
  9676. * 加载手工询价单(含可见性校验)
  9677. *
  9678. * @return array<string, mixed>
  9679. */
  9680. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  9681. {
  9682. try {
  9683. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9684. } catch (\Throwable $e) {
  9685. $po = null;
  9686. }
  9687. if (!is_array($po)) {
  9688. $this->error('订单不存在');
  9689. }
  9690. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9691. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9692. $this->error('订单不存在');
  9693. }
  9694. if ($this->auth->isSuperAdmin()) {
  9695. return $po;
  9696. }
  9697. if ($this->canViewManualRfqOrder($po)) {
  9698. return $po;
  9699. }
  9700. $this->error('无权操作该订单');
  9701. }
  9702. /**
  9703. * @return string[]
  9704. */
  9705. protected function splitRfqSalesmanNames(string $raw): array
  9706. {
  9707. $parts = [];
  9708. $raw = trim($raw);
  9709. if ($raw === '') {
  9710. return [];
  9711. }
  9712. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  9713. $v = trim((string)$piece);
  9714. if ($v !== '' && !in_array($v, $parts, true)) {
  9715. $parts[] = $v;
  9716. }
  9717. }
  9718. return $parts;
  9719. }
  9720. /**
  9721. * 按姓名匹配 fa_admin 邮箱
  9722. *
  9723. * @param string[] $names
  9724. * @return array<int, array{admin_id:int,name:string,email:string}>
  9725. */
  9726. protected function resolveRfqSalesmanContactRows(array $names): array
  9727. {
  9728. $out = [];
  9729. foreach ($names as $name) {
  9730. $name = trim((string)$name);
  9731. if ($name === '') {
  9732. continue;
  9733. }
  9734. $adminId = 0;
  9735. $email = '';
  9736. try {
  9737. $row = Db::name('admin')
  9738. ->where(function ($q) use ($name) {
  9739. $q->where('nickname', $name)->whereOr('username', $name);
  9740. })
  9741. ->where('status', 'normal')
  9742. ->order('id', 'asc')
  9743. ->field('id,nickname,username,email')
  9744. ->find();
  9745. } catch (\Throwable $e) {
  9746. $row = null;
  9747. }
  9748. if (is_array($row)) {
  9749. $adminId = (int)($row['id'] ?? 0);
  9750. $email = trim((string)($row['email'] ?? ''));
  9751. $disp = trim((string)($row['nickname'] ?? ''));
  9752. if ($disp === '') {
  9753. $disp = trim((string)($row['username'] ?? ''));
  9754. }
  9755. if ($disp !== '') {
  9756. $name = $disp;
  9757. }
  9758. }
  9759. $out[] = [
  9760. 'admin_id' => $adminId,
  9761. 'name' => $name,
  9762. 'email' => $email,
  9763. ];
  9764. }
  9765. return $out;
  9766. }
  9767. /**
  9768. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  9769. */
  9770. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  9771. {
  9772. if ($scydgyId >= 0) {
  9773. return;
  9774. }
  9775. try {
  9776. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9777. } catch (\Throwable $e) {
  9778. $po = null;
  9779. }
  9780. if (!is_array($po)) {
  9781. $this->error('订单不存在');
  9782. }
  9783. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9784. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9785. $this->error('订单不存在');
  9786. }
  9787. if ($this->auth->isSuperAdmin()) {
  9788. return;
  9789. }
  9790. [, $adminName] = $this->GetUseName();
  9791. $cywy = trim((string)($po['cywyxm'] ?? ''));
  9792. if ($cywy !== '' && $cywy === $adminName) {
  9793. return;
  9794. }
  9795. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  9796. try {
  9797. if ($this->auth->check($rule)) {
  9798. return;
  9799. }
  9800. } catch (\Throwable $e) {
  9801. }
  9802. }
  9803. $this->error('无权查看该订单');
  9804. }
  9805. /**
  9806. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  9807. */
  9808. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  9809. {
  9810. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  9811. return ProcuremenStatus::PO_COMPLETED;
  9812. }
  9813. $sid = (int)($row['scydgy_id'] ?? 0);
  9814. if ($sid < 0) {
  9815. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  9816. return '已通知业务员';
  9817. }
  9818. if ($hasQuoted) {
  9819. return '供应商已报价';
  9820. }
  9821. if ($hasIssued
  9822. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  9823. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  9824. return '待报价';
  9825. }
  9826. try {
  9827. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9828. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  9829. if ((int)$detCntQuery->count() > 0) {
  9830. return '待报价';
  9831. }
  9832. } catch (\Throwable $e) {
  9833. }
  9834. return '待询价';
  9835. }
  9836. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  9837. return '待入库评分';
  9838. }
  9839. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  9840. return '待采购确认';
  9841. }
  9842. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  9843. return '待确认供应商';
  9844. }
  9845. return '待协助下发';
  9846. }
  9847. /**
  9848. * 协助初选列表 — 批量软删除
  9849. */
  9850. public function pickDelete()
  9851. {
  9852. if (!$this->request->isPost() || !$this->request->isAjax()) {
  9853. $this->error(__('Invalid parameters'));
  9854. }
  9855. if (!$this->procuremenCanPickDelete()) {
  9856. $this->error(__('You have no permission'));
  9857. }
  9858. $rowsRaw = $this->request->post('rows_json', '[]');
  9859. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  9860. if (!is_array($rows) || $rows === []) {
  9861. $this->error('请至少勾选一条工序');
  9862. }
  9863. $done = 0;
  9864. Db::startTrans();
  9865. try {
  9866. foreach ($rows as $row) {
  9867. if (!is_array($row)) {
  9868. continue;
  9869. }
  9870. $this->softDeleteProcuremenPickRow($row);
  9871. $done++;
  9872. }
  9873. if ($done < 1) {
  9874. throw new \Exception('没有可删除的工序');
  9875. }
  9876. Db::commit();
  9877. } catch (\InvalidArgumentException $e) {
  9878. Db::rollback();
  9879. $this->error($e->getMessage());
  9880. } catch (\Throwable $e) {
  9881. Db::rollback();
  9882. $this->error($e->getMessage());
  9883. }
  9884. $this->pickHiddenScydgySetCache = null;
  9885. $this->success('已删除 ' . $done . ' 条工序');
  9886. }
  9887. /**
  9888. * 下发 — 手工新增工序(弹窗)
  9889. */
  9890. public function pickAdd()
  9891. {
  9892. if ($this->request->isPost()) {
  9893. $params = $this->request->post('row/a');
  9894. if (!is_array($params)) {
  9895. $this->error(__('Parameter %s can not be empty', ''));
  9896. }
  9897. try {
  9898. $sid = $this->saveManualPickOrder($params);
  9899. } catch (\InvalidArgumentException $e) {
  9900. $this->error($e->getMessage());
  9901. } catch (\Throwable $e) {
  9902. $this->error($e->getMessage());
  9903. }
  9904. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  9905. }
  9906. return $this->view->fetch('procuremen/pick_add');
  9907. }
  9908. /**
  9909. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  9910. */
  9911. public function pickSubmit()
  9912. {
  9913. if (!$this->request->isPost()) {
  9914. $this->error(__('Invalid parameters'));
  9915. }
  9916. // ---------- 接口订单数据 ----------
  9917. $rowJson = $this->request->post('row_json', '');
  9918. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  9919. $companiesJson = $this->request->post('companies_json', '[]');
  9920. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  9921. $companies = json_decode($companiesJson, true);
  9922. if (!is_array($companies)) {
  9923. $this->error('供应商数据无效');
  9924. }
  9925. $issueCompanies = $this->normalizePickCompanies($companies);
  9926. if ($issueCompanies === []) {
  9927. $this->error('请至少选择一家合作供应商');
  9928. }
  9929. $issueNameLabels = [];
  9930. foreach ($issueCompanies as $pc) {
  9931. $issueNameLabels[] = $pc['name'];
  9932. }
  9933. $issueNamesSummary = implode('、', $issueNameLabels);
  9934. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  9935. if ($sysRq === '') {
  9936. $this->error('请选择招标截止日期');
  9937. }
  9938. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  9939. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  9940. (string)$this->request->post('delivery_deadline', ''),
  9941. true
  9942. );
  9943. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  9944. if ($scoreRuleId <= 0) {
  9945. $this->error('请选择订单类型');
  9946. }
  9947. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  9948. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  9949. $this->error('订单类型无效,请刷新后重选');
  9950. }
  9951. $scoreRuleId = (int)$scoreRule['id'];
  9952. $this->ensurePurchaseOrderScoreRuleIdColumn();
  9953. $isMerge = count($mergeRows) > 1;
  9954. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  9955. $logMsg = '下发' . $procPart
  9956. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  9957. $issueTime = date('Y-m-d H:i:s');
  9958. $logSidList = [];
  9959. foreach ($mergeRows as $row) {
  9960. if (!is_array($row)) {
  9961. continue;
  9962. }
  9963. $sid = $this->extractScydgyRowId($row);
  9964. if ($this->isValidScydgyRowId($sid)) {
  9965. $logSidList[$sid] = true;
  9966. }
  9967. }
  9968. $existingBySid = [];
  9969. if ($logSidList !== []) {
  9970. try {
  9971. $existingRows = Db::table('purchase_order')
  9972. ->where('scydgy_id', 'in', array_keys($logSidList))
  9973. ->select();
  9974. if (is_array($existingRows)) {
  9975. foreach ($existingRows as $poRow) {
  9976. if (!is_array($poRow)) {
  9977. continue;
  9978. }
  9979. $sid = (int)($poRow['scydgy_id'] ?? 0);
  9980. if ($this->isValidScydgyRowId($sid)) {
  9981. $existingBySid[$sid] = $poRow;
  9982. }
  9983. }
  9984. }
  9985. } catch (\Throwable $e) {
  9986. $existingBySid = [];
  9987. }
  9988. }
  9989. Db::startTrans();
  9990. try {
  9991. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  9992. foreach ($mergeRows as $row) {
  9993. if (!is_array($row)) {
  9994. continue;
  9995. }
  9996. $sid = $this->extractScydgyRowId($row);
  9997. $this->upsertPurchaseOrderFromRow(
  9998. $row,
  9999. $sysRqDb,
  10000. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10001. $issueTime,
  10002. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  10003. $deliveryDeadlineDb,
  10004. $scoreRule
  10005. );
  10006. }
  10007. foreach ($issueCompanies as $c) {
  10008. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10009. }
  10010. Db::commit();
  10011. } catch (\Throwable $e) {
  10012. Db::rollback();
  10013. $this->error($e->getMessage());
  10014. }
  10015. $poIdBySid = [];
  10016. if ($logSidList !== []) {
  10017. try {
  10018. $poIdBySid = Db::table('purchase_order')
  10019. ->where('scydgy_id', 'in', array_keys($logSidList))
  10020. ->column('id', 'scydgy_id');
  10021. } catch (\Throwable $e) {
  10022. $poIdBySid = [];
  10023. }
  10024. }
  10025. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  10026. if ($logSidList !== []) {
  10027. list($adminId, $adminName) = $this->GetUseName();
  10028. $logRows = [];
  10029. $seenLogSid = [];
  10030. foreach ($mergeRows as $row) {
  10031. if (!is_array($row)) {
  10032. continue;
  10033. }
  10034. $ids = $this->extractScydgyRowId($row);
  10035. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  10036. continue;
  10037. }
  10038. $seenLogSid[$ids] = true;
  10039. $poIdLog = null;
  10040. if (isset($poIdBySid[$ids])) {
  10041. $tid = (int)$poIdBySid[$ids];
  10042. $poIdLog = $tid > 0 ? $tid : null;
  10043. }
  10044. $logRows[] = ProcuremenOperLog::buildInsertRow(
  10045. $ids,
  10046. 'issue_submit',
  10047. $logMsg,
  10048. $poIdLog,
  10049. (int)$adminId,
  10050. (string)$adminName
  10051. );
  10052. }
  10053. if ($logRows !== []) {
  10054. try {
  10055. Db::table('purchase_order_oper_log')->insertAll($logRows);
  10056. } catch (\Throwable $e) {
  10057. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  10058. }
  10059. }
  10060. }
  10061. $notifyErrors = [];
  10062. $posNotify = [];
  10063. if ($logSidList !== []) {
  10064. try {
  10065. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  10066. } catch (\Throwable $e) {
  10067. $posNotify = [];
  10068. }
  10069. }
  10070. if (!is_array($posNotify)) {
  10071. $posNotify = [];
  10072. }
  10073. foreach ($posNotify as $i => $prow) {
  10074. if (is_array($posNotify[$i])) {
  10075. $posNotify[$i]['sys_rq'] = $sysRqDb;
  10076. }
  10077. }
  10078. $ccydhPick = '';
  10079. foreach ($mergeRows as $row) {
  10080. if (!is_array($row)) {
  10081. continue;
  10082. }
  10083. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10084. if ($ccydhPick !== '') {
  10085. break;
  10086. }
  10087. }
  10088. $notifyBundleBase = [
  10089. 'ccydh' => $ccydhPick,
  10090. 'pos' => $posNotify,
  10091. 'merge_rows' => $mergeRows,
  10092. ];
  10093. try {
  10094. $this->notifyDryRunPreview = [];
  10095. foreach ($issueCompanies as $c) {
  10096. if (!is_array($c)) {
  10097. continue;
  10098. }
  10099. $cname = trim((string)($c['name'] ?? ''));
  10100. if ($cname === '') {
  10101. continue;
  10102. }
  10103. try {
  10104. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10105. } catch (\Throwable $e) {
  10106. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10107. }
  10108. }
  10109. } catch (\Throwable $e) {
  10110. $this->error('通知发送失败:' . $e->getMessage());
  10111. }
  10112. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10113. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10114. }
  10115. if ($this->isProcuremenNotifyDryRun()) {
  10116. $this->success('【演练模式】已保存并生成通知预览', '', [
  10117. 'notify_dry_run' => true,
  10118. 'notify_preview' => $this->notifyDryRunPreview,
  10119. ]);
  10120. }
  10121. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10122. }
  10123. /**
  10124. * 确认供应商弹窗
  10125. */
  10126. public function auditIssue()
  10127. {
  10128. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10129. if (is_array($ids)) {
  10130. $ids = isset($ids[0]) ? $ids[0] : '';
  10131. }
  10132. $ids = trim((string)$ids);
  10133. if ($ids === '') {
  10134. $this->error(__('Invalid parameters'));
  10135. }
  10136. if ($this->request->isPost()) {
  10137. $this->error('请使用弹窗内「确认」提交');
  10138. }
  10139. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10140. $pos = $bundle['pos'];
  10141. if ($pos === []) {
  10142. $this->error('该订单不在待确认供应商状态');
  10143. }
  10144. $po = $pos[0];
  10145. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10146. if ($quoteGroups === []) {
  10147. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10148. }
  10149. $pickedName = '';
  10150. foreach ($pos as $poRow) {
  10151. if (!is_array($poRow)) {
  10152. continue;
  10153. }
  10154. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10155. if ($pn !== '') {
  10156. $pickedName = $pn;
  10157. break;
  10158. }
  10159. }
  10160. $this->view->assign('po', $po);
  10161. $this->view->assign('scydgyId', $ids);
  10162. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10163. $mergeRows = $bundle['merge_rows'];
  10164. $this->view->assign('processRows', $mergeRows);
  10165. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10166. $this->view->assign('processCount', count($mergeRows));
  10167. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10168. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10169. $this->view->assign('pickedCompanyName', $pickedName);
  10170. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10171. if ($sysRqForView === '') {
  10172. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10173. }
  10174. $this->view->assign('sysRq', $sysRqForView);
  10175. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10176. if ($deliveryDeadlineForView === '') {
  10177. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10178. }
  10179. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10180. $this->ensurePurchaseOrderManualPickColumns();
  10181. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10182. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10183. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10184. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10185. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10186. $pickedName = $manualPickInfo['company'];
  10187. $this->view->assign('pickedCompanyName', $pickedName);
  10188. }
  10189. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10190. $this->view->assign('manualPicked', $manualPicked);
  10191. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10192. $this->view->assign('quoteVisible', $quoteVisible);
  10193. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10194. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10195. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10196. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10197. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10198. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10199. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10200. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10201. return $this->view->fetch('procuremen/audit_issue');
  10202. }
  10203. /**
  10204. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10205. *
  10206. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10207. */
  10208. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10209. {
  10210. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10211. return false;
  10212. }
  10213. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10214. return false;
  10215. }
  10216. return true;
  10217. }
  10218. /**
  10219. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10220. *
  10221. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10222. */
  10223. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10224. {
  10225. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10226. return false;
  10227. }
  10228. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10229. return false;
  10230. }
  10231. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10232. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10233. return true;
  10234. }
  10235. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10236. }
  10237. /**
  10238. * 确认页 — 补加供应商弹窗
  10239. */
  10240. public function auditAppend()
  10241. {
  10242. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10243. $this->error(__('You have no permission'));
  10244. }
  10245. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10246. if (is_array($ids)) {
  10247. $ids = isset($ids[0]) ? $ids[0] : '';
  10248. }
  10249. $ids = trim((string)$ids);
  10250. if ($ids === '') {
  10251. $this->error(__('Invalid parameters'));
  10252. }
  10253. if ($this->request->isPost()) {
  10254. $this->error('请使用弹窗内「确认」提交');
  10255. }
  10256. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10257. if (($bundle['pos'] ?? []) === []) {
  10258. $this->error('该订单不在待确认供应商状态');
  10259. }
  10260. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10261. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10262. $this->error('已开标验证,不能再补加供应商');
  10263. }
  10264. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10265. $this->error('已指定供应商,不能再补加供应商');
  10266. }
  10267. $this->error('已经超过了招标截止日期,不可操作');
  10268. }
  10269. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10270. $existingNames = [];
  10271. foreach ($quoteGroups as $g) {
  10272. if (!is_array($g)) {
  10273. continue;
  10274. }
  10275. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10276. if ($n !== '') {
  10277. $existingNames[$n] = true;
  10278. }
  10279. }
  10280. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10281. $mergeRows = $bundle['merge_rows'] ?? [];
  10282. $this->view->assign('scydgyId', $ids);
  10283. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10284. $this->view->assign('po', $po);
  10285. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10286. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10287. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10288. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10289. if ($sysRqForView === '') {
  10290. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10291. }
  10292. $this->view->assign('sysRq', $sysRqForView);
  10293. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10294. if ($deliveryDeadlineForView === '') {
  10295. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10296. }
  10297. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10298. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10299. }
  10300. /**
  10301. * 确认页 — 补加供应商提交
  10302. */
  10303. public function auditAppendSubmit()
  10304. {
  10305. if (!$this->request->isPost()) {
  10306. $this->error(__('Invalid parameters'));
  10307. }
  10308. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10309. $this->error(__('You have no permission'));
  10310. }
  10311. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10312. if ($ids === '') {
  10313. $this->error(__('Invalid parameters'));
  10314. }
  10315. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10316. if (($bundle['pos'] ?? []) === []) {
  10317. $this->error('该订单不在待确认供应商状态');
  10318. }
  10319. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10320. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10321. $this->error('已开标验证,不能再补加供应商');
  10322. }
  10323. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10324. $this->error('已指定供应商,不能再补加供应商');
  10325. }
  10326. $this->error('已经超过了招标截止日期,不可操作');
  10327. }
  10328. $companiesJson = $this->request->post('companies_json', '[]');
  10329. $companies = json_decode((string)$companiesJson, true);
  10330. if (!is_array($companies)) {
  10331. $this->error('供应商数据无效');
  10332. }
  10333. $issueCompanies = $this->normalizePickCompanies($companies);
  10334. if ($issueCompanies === []) {
  10335. $this->error('请至少选择一家合作供应商');
  10336. }
  10337. $mergeRows = $bundle['merge_rows'] ?? [];
  10338. if (!is_array($mergeRows) || $mergeRows === []) {
  10339. $this->error('未找到工序行,无法补加');
  10340. }
  10341. $existingNames = [];
  10342. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10343. if (!is_array($g)) {
  10344. continue;
  10345. }
  10346. $n = trim((string)($g['company_name'] ?? ''));
  10347. if ($n !== '') {
  10348. $existingNames[$n] = true;
  10349. }
  10350. }
  10351. $toAdd = [];
  10352. foreach ($issueCompanies as $c) {
  10353. if (!is_array($c)) {
  10354. continue;
  10355. }
  10356. $n = trim((string)($c['name'] ?? ''));
  10357. if ($n === '' || isset($existingNames[$n])) {
  10358. continue;
  10359. }
  10360. $toAdd[] = $c;
  10361. }
  10362. if ($toAdd === []) {
  10363. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10364. }
  10365. $addedNames = [];
  10366. Db::startTrans();
  10367. try {
  10368. foreach ($toAdd as $c) {
  10369. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10370. $addedNames[] = trim((string)($c['name'] ?? ''));
  10371. }
  10372. Db::commit();
  10373. } catch (\Throwable $e) {
  10374. Db::rollback();
  10375. $this->error($e->getMessage());
  10376. }
  10377. $notifyErrors = [];
  10378. $notifyBundleBase = [
  10379. 'ccydh' => $bundle['ccydh'] ?? '',
  10380. 'pos' => $bundle['pos'] ?? [],
  10381. 'merge_rows' => $mergeRows,
  10382. ];
  10383. foreach ($toAdd as $c) {
  10384. if (!is_array($c)) {
  10385. continue;
  10386. }
  10387. $cname = trim((string)($c['name'] ?? ''));
  10388. if ($cname === '') {
  10389. continue;
  10390. }
  10391. try {
  10392. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10393. } catch (\Throwable $e) {
  10394. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10395. }
  10396. }
  10397. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10398. $seenLogSid = [];
  10399. foreach ($bundle['pos'] ?? [] as $poRow) {
  10400. if (!is_array($poRow)) {
  10401. continue;
  10402. }
  10403. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10404. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10405. continue;
  10406. }
  10407. $seenLogSid[$sid] = true;
  10408. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10409. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10410. }
  10411. if ($seenLogSid === []) {
  10412. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10413. if ($this->isValidScydgyRowId($logSid)) {
  10414. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10415. }
  10416. }
  10417. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10418. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  10419. }
  10420. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  10421. }
  10422. /**
  10423. * 开标双重验证 — 可选验证人列表
  10424. */
  10425. public function bidOpenUsers()
  10426. {
  10427. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10428. $this->error('无权限');
  10429. }
  10430. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  10431. if ($scydgyId !== '') {
  10432. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10433. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10434. $this->success('已完成开标验证', null, [
  10435. 'verified' => 1,
  10436. 'users' => [],
  10437. ]);
  10438. }
  10439. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10440. $this->error('本单已指定供应商,无需再开标');
  10441. }
  10442. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10443. }
  10444. $this->success('', null, [
  10445. 'verified' => 0,
  10446. 'users' => $this->listBidOpenVerifierCandidates(),
  10447. ]);
  10448. }
  10449. /**
  10450. * 开标双重验证 — 向指定管理员发送短信验证码
  10451. */
  10452. public function bidOpenSendCode()
  10453. {
  10454. if (!$this->request->isPost()) {
  10455. $this->error(__('Invalid parameters'));
  10456. }
  10457. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10458. $this->error('无权限');
  10459. }
  10460. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10461. $adminId = (int)$this->request->post('admin_id', 0);
  10462. if ($scydgyId === '' || $adminId <= 0) {
  10463. $this->error('参数无效');
  10464. }
  10465. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10466. if ($bundle['pos'] === []) {
  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. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10477. if ($ccydh === '') {
  10478. $this->error('订单号无效');
  10479. }
  10480. $admin = $this->loadBidOpenAdminUser($adminId);
  10481. if ($admin === null) {
  10482. $this->error('验证人无效或未绑定手机号');
  10483. }
  10484. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  10485. $cd = max(30, min(120, $cd));
  10486. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  10487. $this->error('发送过于频繁,请稍后再试');
  10488. }
  10489. $code = (string)random_int(100000, 999999);
  10490. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  10491. $ttl = max(60, min(600, $ttl));
  10492. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  10493. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  10494. try {
  10495. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  10496. } catch (\Throwable $e) {
  10497. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  10498. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  10499. $this->error($e->getMessage());
  10500. }
  10501. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  10502. }
  10503. /**
  10504. * 开标双重验证 — 两人验证码校验并记录
  10505. */
  10506. public function bidOpenVerify()
  10507. {
  10508. if (!$this->request->isPost()) {
  10509. $this->error(__('Invalid parameters'));
  10510. }
  10511. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10512. $this->error('无权限');
  10513. }
  10514. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10515. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  10516. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  10517. $code1 = trim((string)$this->request->post('code1', ''));
  10518. $code2 = trim((string)$this->request->post('code2', ''));
  10519. if ($scydgyId === '') {
  10520. $this->error('参数无效');
  10521. }
  10522. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  10523. $this->error('请选择两位验证人');
  10524. }
  10525. if ($verifier1Id === $verifier2Id) {
  10526. $this->error('两位验证人不能相同');
  10527. }
  10528. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  10529. $this->error('请输入6位短信验证码');
  10530. }
  10531. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10532. if ($bundle['pos'] === []) {
  10533. $this->error('该订单不在待确认供应商状态');
  10534. }
  10535. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10536. if ($ccydh === '') {
  10537. $this->error('订单号无效');
  10538. }
  10539. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10540. $this->success('已完成开标验证');
  10541. }
  10542. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10543. $this->error('本单已指定供应商,无需再开标');
  10544. }
  10545. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10546. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  10547. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  10548. if ($verifier1 === null || $verifier2 === null) {
  10549. $this->error('验证人无效或未绑定手机号');
  10550. }
  10551. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  10552. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  10553. }
  10554. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  10555. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  10556. }
  10557. try {
  10558. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  10559. } catch (\Throwable $e) {
  10560. $this->error($e->getMessage());
  10561. }
  10562. $this->success('开标验证成功,可查看供应商报价与交货日期');
  10563. }
  10564. /**
  10565. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  10566. */
  10567. public function auditManualPick()
  10568. {
  10569. if (!$this->request->isPost()) {
  10570. $this->error(__('Invalid parameters'));
  10571. }
  10572. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  10573. $this->error('无权限');
  10574. }
  10575. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10576. if ($scydgyId === '') {
  10577. $this->error('参数无效');
  10578. }
  10579. $companyName = trim((string)$this->request->post('selected_company', ''));
  10580. $reason = trim((string)$this->request->post('pick_reason', ''));
  10581. if ($companyName === '') {
  10582. $this->error('请选择一家供应商');
  10583. }
  10584. if ($reason === '') {
  10585. $this->error('请填写选择说明');
  10586. }
  10587. if (mb_strlen($reason) > 500) {
  10588. $this->error('选择说明不能超过500字');
  10589. }
  10590. $this->ensurePurchaseOrderManualPickColumns();
  10591. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10592. $pos = $bundle['pos'];
  10593. if ($pos === []) {
  10594. $this->error('该订单不在待确认供应商状态');
  10595. }
  10596. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10597. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  10598. }
  10599. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10600. if ($quoteGroups === []) {
  10601. $this->error('暂无供应商,请确认已完成协助初选通知');
  10602. }
  10603. $matched = null;
  10604. foreach ($quoteGroups as $g) {
  10605. if (!is_array($g)) {
  10606. continue;
  10607. }
  10608. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10609. $matched = $g;
  10610. break;
  10611. }
  10612. }
  10613. if ($matched === null) {
  10614. $this->error('所选供应商不在本单报价列表中');
  10615. }
  10616. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  10617. Db::startTrans();
  10618. try {
  10619. foreach ($pos as $poRow) {
  10620. if (!is_array($poRow)) {
  10621. continue;
  10622. }
  10623. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10624. if (!$this->isValidScydgyRowId($sid)) {
  10625. continue;
  10626. }
  10627. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10628. 'pick_company_name' => $companyName,
  10629. 'manual_pick' => 1,
  10630. 'manual_pick_reason' => $reason,
  10631. ]);
  10632. }
  10633. Db::commit();
  10634. } catch (\Throwable $e) {
  10635. Db::rollback();
  10636. $this->error($e->getMessage());
  10637. }
  10638. foreach ($pos as $poRow) {
  10639. if (!is_array($poRow)) {
  10640. continue;
  10641. }
  10642. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10643. if (!$this->isValidScydgyRowId($sid)) {
  10644. continue;
  10645. }
  10646. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10647. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10648. }
  10649. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  10650. try {
  10651. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10652. if ($ccydh !== '') {
  10653. // 重新加载以拿到未掩码报价参与计分
  10654. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10655. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  10656. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  10657. }
  10658. } catch (\Throwable $e) {
  10659. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  10660. }
  10661. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  10662. }
  10663. /**
  10664. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  10665. */
  10666. public function auditSubmit()
  10667. {
  10668. if (!$this->request->isPost()) {
  10669. $this->error(__('Invalid parameters'));
  10670. }
  10671. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10672. if ($scydgyId === '') {
  10673. $this->error('参数无效');
  10674. }
  10675. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10676. $pos = $bundle['pos'];
  10677. $mergeRows = $bundle['merge_rows'];
  10678. if ($pos === [] || $mergeRows === []) {
  10679. $this->error('该订单不在待确认供应商状态');
  10680. }
  10681. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10682. if ($quoteGroups === []) {
  10683. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  10684. }
  10685. $companyName = trim((string)$this->request->post('selected_company', ''));
  10686. if ($companyName === '') {
  10687. $this->error('请选择一家供应商');
  10688. }
  10689. $matched = null;
  10690. foreach ($quoteGroups as $g) {
  10691. if (!is_array($g)) {
  10692. continue;
  10693. }
  10694. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10695. $matched = $g;
  10696. break;
  10697. }
  10698. }
  10699. if ($matched === null) {
  10700. $this->error('所选供应商不在本单报价列表中');
  10701. }
  10702. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10703. if ($sysRqDb === '') {
  10704. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  10705. } else {
  10706. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  10707. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  10708. }
  10709. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  10710. $this->error('未到招标截止日期,暂不可确认');
  10711. }
  10712. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  10713. && !$this->isProcuremenManualPickedForBundle($bundle)
  10714. ) {
  10715. $this->error('请先完成开标双重验证或指定供应商后再确认');
  10716. }
  10717. $procCnt = count($mergeRows);
  10718. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  10719. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  10720. Db::startTrans();
  10721. try {
  10722. foreach ($pos as $poRow) {
  10723. if (!is_array($poRow)) {
  10724. continue;
  10725. }
  10726. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10727. if (!$this->isValidScydgyRowId($sid)) {
  10728. continue;
  10729. }
  10730. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10731. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  10732. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10733. 'pick_company_name' => $companyName,
  10734. 'sys_rq' => $sysRqDb,
  10735. ]);
  10736. }
  10737. Db::commit();
  10738. } catch (\Throwable $e) {
  10739. Db::rollback();
  10740. $this->error($e->getMessage());
  10741. }
  10742. foreach ($pos as $poRow) {
  10743. if (!is_array($poRow)) {
  10744. continue;
  10745. }
  10746. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10747. if (!$this->isValidScydgyRowId($sid)) {
  10748. continue;
  10749. }
  10750. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10751. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10752. }
  10753. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  10754. }
  10755. /**
  10756. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  10757. */
  10758. public function auditResendSms()
  10759. {
  10760. if (!$this->request->isPost()) {
  10761. $this->error(__('Invalid parameters'));
  10762. }
  10763. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10764. if ($scydgyId === '') {
  10765. $this->error('参数无效');
  10766. }
  10767. $loaded = $this->loadAuditResendBundle($scydgyId);
  10768. $mergeRows = $loaded['merge_rows'];
  10769. $bundle = $loaded['bundle'];
  10770. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10771. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10772. if ($quoteGroups === []) {
  10773. $this->error('暂无可通知的供应商');
  10774. }
  10775. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10776. $companiesJson = (string)$this->request->post('companies_json', '');
  10777. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10778. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  10779. }
  10780. /**
  10781. * 确认供应商 — 二次发送邮件(可选单家/批量)
  10782. */
  10783. public function auditResendEmail()
  10784. {
  10785. if (!$this->request->isPost()) {
  10786. $this->error(__('Invalid parameters'));
  10787. }
  10788. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10789. if ($scydgyId === '') {
  10790. $this->error('参数无效');
  10791. }
  10792. $loaded = $this->loadAuditResendBundle($scydgyId);
  10793. $mergeRows = $loaded['merge_rows'];
  10794. $bundle = $loaded['bundle'];
  10795. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10796. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10797. if ($quoteGroups === []) {
  10798. $this->error('暂无可通知的供应商');
  10799. }
  10800. $companiesJson = (string)$this->request->post('companies_json', '');
  10801. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10802. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10803. if ($companiesJson === '' && $selectedCompany === '') {
  10804. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  10805. }
  10806. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  10807. }
  10808. /**
  10809. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  10810. *
  10811. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  10812. * @return array<int, true> 已处理的 scydgy_id 集合
  10813. */
  10814. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  10815. {
  10816. $pos = $bundle['pos'] ?? [];
  10817. if (!is_array($pos) || $pos === []) {
  10818. return [];
  10819. }
  10820. $sids = [];
  10821. $poIdBySid = [];
  10822. foreach ($pos as $poRow) {
  10823. if (!is_array($poRow)) {
  10824. continue;
  10825. }
  10826. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10827. if ($this->isValidScydgyRowId($sid)) {
  10828. $sids[$sid] = true;
  10829. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10830. if ($poId > 0) {
  10831. $poIdBySid[$sid] = $poId;
  10832. }
  10833. }
  10834. }
  10835. if ($sids === []) {
  10836. return [];
  10837. }
  10838. $logMsg = '重新下发';
  10839. $suffix = trim((string)$logSuffix, ',, ');
  10840. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  10841. $logMsg .= ':从历史存证退回协助初选';
  10842. } else {
  10843. $logMsg .= ':退回协助初选';
  10844. }
  10845. Db::table('purchase_order')
  10846. ->where('scydgy_id', 'in', array_keys($sids))
  10847. ->update([
  10848. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  10849. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10850. 'pick_company_name' => '',
  10851. 'pick_time' => null,
  10852. 'sys_rq' => null,
  10853. 'mod_rq' => null,
  10854. ]);
  10855. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  10856. foreach (array_keys($sids) as $sid) {
  10857. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  10858. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10859. }
  10860. return $sids;
  10861. }
  10862. /**
  10863. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  10864. *
  10865. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10866. */
  10867. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  10868. {
  10869. $scydgyId = trim($scydgyId);
  10870. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10871. if ($scydgyId === '') {
  10872. return $empty;
  10873. }
  10874. try {
  10875. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10876. } catch (\Throwable $e) {
  10877. $anchor = null;
  10878. }
  10879. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  10880. return $empty;
  10881. }
  10882. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10883. if ($ccydh === '') {
  10884. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10885. }
  10886. try {
  10887. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  10888. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  10889. $pos = $query->order('scydgy_id', 'asc')->select();
  10890. } catch (\Throwable $e) {
  10891. $pos = [$anchor];
  10892. }
  10893. if (!is_array($pos) || $pos === []) {
  10894. $pos = [$anchor];
  10895. }
  10896. return [
  10897. 'ccydh' => $ccydh,
  10898. 'pos' => $pos,
  10899. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10900. ];
  10901. }
  10902. protected function purchaseOrderRowIsCompleted(array $po): bool
  10903. {
  10904. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  10905. }
  10906. /**
  10907. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  10908. *
  10909. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10910. */
  10911. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  10912. {
  10913. $scydgyId = trim($scydgyId);
  10914. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10915. if ($scydgyId === '') {
  10916. return $empty;
  10917. }
  10918. try {
  10919. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10920. } catch (\Throwable $e) {
  10921. $anchor = null;
  10922. }
  10923. if (!is_array($anchor)) {
  10924. return $empty;
  10925. }
  10926. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10927. if ($ccydh === '') {
  10928. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10929. }
  10930. try {
  10931. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  10932. } catch (\Throwable $e) {
  10933. $pos = [$anchor];
  10934. }
  10935. if (!is_array($pos) || $pos === []) {
  10936. $pos = [$anchor];
  10937. }
  10938. return [
  10939. 'ccydh' => $ccydh,
  10940. 'pos' => $pos,
  10941. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10942. ];
  10943. }
  10944. /**
  10945. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  10946. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  10947. */
  10948. public function auditAbandon()
  10949. {
  10950. if (!$this->request->isPost()) {
  10951. $this->error(__('Invalid parameters'));
  10952. }
  10953. $anchorIds = [];
  10954. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  10955. if ($batchRaw !== '') {
  10956. $decoded = json_decode($batchRaw, true);
  10957. if (is_array($decoded)) {
  10958. foreach ($decoded as $id) {
  10959. $s = trim((string)$id);
  10960. if ($s !== '') {
  10961. $anchorIds[] = $s;
  10962. }
  10963. }
  10964. }
  10965. }
  10966. if ($anchorIds === []) {
  10967. $single = trim((string)$this->request->post('scydgy_id', ''));
  10968. if ($single !== '') {
  10969. $anchorIds[] = $single;
  10970. }
  10971. }
  10972. if ($anchorIds === []) {
  10973. $this->error('请至少选择一条订单');
  10974. }
  10975. $processedCcydh = [];
  10976. $doneOrders = 0;
  10977. $allSids = [];
  10978. Db::startTrans();
  10979. try {
  10980. foreach ($anchorIds as $anchorId) {
  10981. $fromArchive = false;
  10982. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  10983. if (($bundle['pos'] ?? []) === []) {
  10984. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  10985. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10986. }
  10987. if (($bundle['pos'] ?? []) === []) {
  10988. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  10989. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10990. }
  10991. if (($bundle['pos'] ?? []) === []) {
  10992. continue;
  10993. }
  10994. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10995. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  10996. if (isset($processedCcydh[$dedupeKey])) {
  10997. continue;
  10998. }
  10999. $processedCcydh[$dedupeKey] = true;
  11000. $sids = $fromArchive
  11001. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  11002. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  11003. if ($sids === []) {
  11004. continue;
  11005. }
  11006. $doneOrders++;
  11007. foreach (array_keys($sids) as $sid) {
  11008. $allSids[(int)$sid] = true;
  11009. }
  11010. }
  11011. if ($doneOrders < 1) {
  11012. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  11013. }
  11014. Db::commit();
  11015. } catch (\Throwable $e) {
  11016. Db::rollback();
  11017. $this->error($e->getMessage());
  11018. }
  11019. $this->pickHiddenScydgySetCache = null;
  11020. $msg = $doneOrders > 1
  11021. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  11022. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  11023. $this->success($msg);
  11024. }
  11025. /**
  11026. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  11027. */
  11028. public function archiveAbandon()
  11029. {
  11030. return $this->auditAbandon();
  11031. }
  11032. /**
  11033. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  11034. */
  11035. public function purchaseApprovalReject()
  11036. {
  11037. if (!$this->request->isPost() || !$this->request->isAjax()) {
  11038. $this->error(__('Invalid parameters'));
  11039. }
  11040. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  11041. $this->error(__('You have no permission'));
  11042. }
  11043. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  11044. $decoded = json_decode($batchRaw, true);
  11045. if (!is_array($decoded) || $decoded === []) {
  11046. $this->error('提交数据无效');
  11047. }
  11048. $done = 0;
  11049. Db::startTrans();
  11050. try {
  11051. foreach ($decoded as $item) {
  11052. if (!is_array($item)) {
  11053. continue;
  11054. }
  11055. $sid = (int)($item['scydgy_id'] ?? 0);
  11056. if (!$this->isValidScydgyRowId($sid)) {
  11057. continue;
  11058. }
  11059. $this->runPurchaseApprovalRejectForSid($sid);
  11060. $done++;
  11061. }
  11062. if ($done < 1) {
  11063. throw new \Exception('所选订单均不在待审批状态');
  11064. }
  11065. Db::commit();
  11066. } catch (\Throwable $e) {
  11067. Db::rollback();
  11068. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  11069. }
  11070. $this->pickHiddenScydgySetCache = null;
  11071. $this->success('已驳回并退回「协助审批下发」');
  11072. }
  11073. /**
  11074. * @throws \Exception
  11075. */
  11076. protected function runPurchaseApprovalRejectForSid(int $sid): void
  11077. {
  11078. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  11079. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  11080. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11081. $allIds = $this->purchaseOrderDetail($sid);
  11082. if ($allIds === []) {
  11083. throw new \Exception('未找到下发明细');
  11084. }
  11085. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11086. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11087. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11088. 'pick_company_name' => '',
  11089. ]);
  11090. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11091. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11092. $poId = 0;
  11093. try {
  11094. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11095. if (is_array($po)) {
  11096. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11097. }
  11098. } catch (\Throwable $e) {
  11099. }
  11100. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11101. }
  11102. /**
  11103. * 审核弹窗(旧入口,POST 已关闭)
  11104. */
  11105. public function review()
  11106. {
  11107. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11108. $this->error(__('You have no permission'));
  11109. }
  11110. if ($this->request->isPost()) {
  11111. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11112. }
  11113. $this->view->assign('pickMode', 0);
  11114. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11115. }
  11116. /**
  11117. * 审核弹窗获取公司列表
  11118. */
  11119. public function reviewCompanies()
  11120. {
  11121. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11122. $this->error(__('You have no permission'));
  11123. }
  11124. if (!$this->request->isAjax()) {
  11125. $this->error(__('Invalid parameters'));
  11126. }
  11127. $list = [];
  11128. try {
  11129. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11130. $rows = Db::table('customer')
  11131. ->where(function ($q) {
  11132. $q->where('status', 1)
  11133. ->whereOr('status', '1')
  11134. ->whereOr('status', '')
  11135. ->whereNull('status');
  11136. })
  11137. ->order('id', 'desc')
  11138. ->select();
  11139. } catch (\Throwable $e) {
  11140. $this->success('', '', []);
  11141. return;
  11142. }
  11143. if (!is_array($rows)) {
  11144. $this->success('', '', []);
  11145. return;
  11146. }
  11147. $detailColCandidates = [
  11148. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11149. 'company_detail', 'company_desc', 'address',
  11150. ];
  11151. foreach ($rows as $row) {
  11152. if (!is_array($row)) {
  11153. continue;
  11154. }
  11155. $norm = [];
  11156. foreach ($row as $k => $v) {
  11157. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11158. }
  11159. $row = $norm;
  11160. $st = $row['status'] ?? '';
  11161. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11162. continue;
  11163. }
  11164. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11165. if ($payload === null) {
  11166. continue;
  11167. }
  11168. $detail = '';
  11169. foreach ($detailColCandidates as $dk) {
  11170. if (!isset($row[$dk])) {
  11171. continue;
  11172. }
  11173. $dv = trim((string)$row[$dk]);
  11174. if ($dv !== '') {
  11175. $detail = $dv;
  11176. break;
  11177. }
  11178. }
  11179. $payload['detail'] = $detail;
  11180. $list[] = $this->maskSupplierContactFields($payload);
  11181. }
  11182. $this->success('', '', $list);
  11183. }
  11184. /**
  11185. * 采购确认-下发明细弹窗:
  11186. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11187. */
  11188. public function outward_detail()
  11189. {
  11190. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11191. if (is_array($ids)) {
  11192. $ids = isset($ids[0]) ? $ids[0] : '';
  11193. }
  11194. $ids = trim((string)$ids);
  11195. if ($ids === '') {
  11196. $this->error(__('Invalid parameters'));
  11197. }
  11198. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11199. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11200. $wffTab = 'all';
  11201. }
  11202. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11203. $purchaseOrderId = 0;
  11204. $po = null;
  11205. try {
  11206. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11207. if (is_array($po)) {
  11208. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11209. }
  11210. } catch (\Throwable $e) {
  11211. $purchaseOrderId = 0;
  11212. $po = null;
  11213. }
  11214. if (!$isPurchaseConfirm && is_array($po)) {
  11215. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11216. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11217. $isPurchaseConfirm = true;
  11218. }
  11219. }
  11220. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11221. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11222. $confirmProcessCount = 1;
  11223. $confirmPickGroups = [];
  11224. $processDisplayRows = [];
  11225. $allDetailsBySid = [];
  11226. $requiredSidList = [];
  11227. $sidList = [$ids];
  11228. if ($isPurchaseConfirm) {
  11229. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11230. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11231. if ($mergeRows !== []) {
  11232. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11233. }
  11234. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11235. if ($confirmBundle['pos'] !== []) {
  11236. $sidList = [];
  11237. foreach ($confirmBundle['pos'] as $poRow) {
  11238. if (!is_array($poRow)) {
  11239. continue;
  11240. }
  11241. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11242. if (!$this->isValidScydgyRowId($sid)) {
  11243. continue;
  11244. }
  11245. $sidList[] = (string)$sid;
  11246. $requiredSidList[] = $sid;
  11247. }
  11248. }
  11249. if ($sidList === []) {
  11250. $sidList = [$ids];
  11251. $requiredSidList = [(int)$ids];
  11252. }
  11253. $confirmProcessCount = max(1, count($requiredSidList));
  11254. if (is_array($po) && $purchaseOrderId <= 0) {
  11255. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11256. }
  11257. }
  11258. $rows = [];
  11259. try {
  11260. if (count($sidList) === 1) {
  11261. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11262. } else {
  11263. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11264. }
  11265. } catch (\Throwable $e) {
  11266. $rows = [];
  11267. }
  11268. if ($isPurchaseConfirm) {
  11269. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11270. }
  11271. foreach ($rows as &$r) {
  11272. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11273. $r['id'] = $r['ID'];
  11274. }
  11275. if (isset($r['createtime'])) {
  11276. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11277. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11278. } else {
  11279. $r['createtime_text'] = (string)$r['createtime'];
  11280. }
  11281. } else {
  11282. $r['createtime_text'] = '';
  11283. }
  11284. if (is_array($r)) {
  11285. $r = $this->maskSupplierContactFields($r);
  11286. }
  11287. }
  11288. unset($r);
  11289. $pickedCompanyName = '';
  11290. $manualPicked = 0;
  11291. $manualPickReason = '';
  11292. $quoteVisible = 0;
  11293. $bidOpenVerified = 0;
  11294. if ($isPurchaseConfirm) {
  11295. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11296. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11297. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11298. }
  11299. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11300. $confirmBundle['pos'] = [$po];
  11301. }
  11302. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11303. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11304. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11305. if ($manualPickInfo['company'] !== '') {
  11306. $pickedCompanyName = $manualPickInfo['company'];
  11307. }
  11308. if ($pickedCompanyName === '') {
  11309. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11310. if (!is_array($poRow)) {
  11311. continue;
  11312. }
  11313. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11314. if ($pn !== '') {
  11315. $pickedCompanyName = $pn;
  11316. break;
  11317. }
  11318. }
  11319. }
  11320. // 再兜底:直接读当前主单字段
  11321. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11322. $manualPicked = 1;
  11323. if ($manualPickReason === '') {
  11324. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11325. }
  11326. if ($pickedCompanyName === '') {
  11327. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11328. }
  11329. }
  11330. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11331. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11332. }
  11333. $this->view->assign('rows', $rows ?: []);
  11334. $this->view->assign('rowCount', count($rows ?: []));
  11335. $this->view->assign('scydgyId', $ids);
  11336. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11337. $this->view->assign('headTitle', $headTitle);
  11338. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11339. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11340. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11341. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11342. $this->view->assign('processDisplayRows', $processDisplayRows);
  11343. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11344. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11345. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11346. $this->view->assign('manualPicked', $manualPicked);
  11347. $this->view->assign('manualPickReason', $manualPickReason);
  11348. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11349. $this->view->assign('quoteVisible', $quoteVisible);
  11350. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11351. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11352. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11353. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11354. $sysRqDisplay = '—';
  11355. if ($isPurchaseConfirm) {
  11356. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11357. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11358. );
  11359. }
  11360. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11361. $this->view->assign('sysRq', $isPurchaseConfirm
  11362. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11363. : '');
  11364. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11365. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11366. : '');
  11367. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11368. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11369. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11370. if ($isPurchaseConfirm) {
  11371. return $this->view->fetch();
  11372. }
  11373. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11374. $this->view->engine->layout(false);
  11375. try {
  11376. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11377. $this->view->assign('dialogBody', $bodyHtml);
  11378. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11379. } finally {
  11380. if ($restoreLayout) {
  11381. $this->view->engine->layout($restoreLayout);
  11382. }
  11383. }
  11384. }
  11385. /**
  11386. * 月度导出记录表(不存在时自动创建)
  11387. */
  11388. protected function ensurePurchaseMonthExportLogTable(): void
  11389. {
  11390. try {
  11391. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11392. } catch (\Throwable $e) {
  11393. Db::execute(
  11394. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11395. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11396. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11397. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11398. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11399. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11400. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11401. `createtime` int(10) unsigned DEFAULT NULL,
  11402. PRIMARY KEY (`id`),
  11403. KEY `idx_ym` (`ym`),
  11404. KEY `idx_ct` (`createtime`)
  11405. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11406. );
  11407. }
  11408. }
  11409. /**
  11410. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11411. *
  11412. * @param array<int, mixed> $dbRows
  11413. * @return array<int, array<string, mixed>>
  11414. */
  11415. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11416. {
  11417. $keyword = trim((string)$this->request->get('search', ''));
  11418. if ($keyword === '') {
  11419. $keyword = trim((string)$this->request->request('search', ''));
  11420. }
  11421. $filter = $this->request->get('filter', '');
  11422. $op = $this->request->get('op', '');
  11423. if (is_string($filter) && $filter !== '') {
  11424. $filterArr = (array)json_decode($filter, true);
  11425. } else {
  11426. $filterArr = is_array($filter) ? $filter : [];
  11427. }
  11428. if (is_string($op) && $op !== '') {
  11429. $opArr = (array)json_decode($op, true);
  11430. } else {
  11431. $opArr = is_array($op) ? $op : [];
  11432. }
  11433. if ($keyword === '' && $filterArr === []) {
  11434. return array_values(array_filter($dbRows, 'is_array'));
  11435. }
  11436. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  11437. $out = [];
  11438. foreach ($dbRows as $row) {
  11439. if (!is_array($row)) {
  11440. continue;
  11441. }
  11442. if ($keyword !== '') {
  11443. $hit = false;
  11444. foreach ($searchFields as $f) {
  11445. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  11446. $hit = true;
  11447. break;
  11448. }
  11449. }
  11450. if (!$hit) {
  11451. continue;
  11452. }
  11453. }
  11454. $passFilter = true;
  11455. foreach ($filterArr as $field => $val) {
  11456. $field = (string)$field;
  11457. $val = trim((string)$val);
  11458. if ($field === '' || $val === '') {
  11459. continue;
  11460. }
  11461. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  11462. continue;
  11463. }
  11464. $cell = (string)($row[$field] ?? '');
  11465. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  11466. if ($mode === '=' || $mode === 'EQUAL') {
  11467. if (strcasecmp($cell, $val) !== 0) {
  11468. $passFilter = false;
  11469. break;
  11470. }
  11471. } elseif (mb_stripos($cell, $val) === false) {
  11472. $passFilter = false;
  11473. break;
  11474. }
  11475. }
  11476. if (!$passFilter) {
  11477. continue;
  11478. }
  11479. $out[] = $row;
  11480. }
  11481. return $out;
  11482. }
  11483. /**
  11484. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  11485. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  11486. */
  11487. public function export_month_outward()
  11488. {
  11489. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  11490. $this->error(__('You have no permission'));
  11491. }
  11492. $bundle = $this->prepareMonthOutwardExportBundle();
  11493. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11494. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  11495. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  11496. $spreadsheet = new Spreadsheet();
  11497. $sheet = $spreadsheet->getActiveSheet();
  11498. $sheet->setTitle('外协加工明细');
  11499. $mon = (int)substr($ym, 5, 2);
  11500. $sheet->mergeCells('A1:H1');
  11501. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  11502. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  11503. $sheet->getStyle('A1')->getAlignment()
  11504. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11505. ->setVertical(Alignment::VERTICAL_CENTER);
  11506. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  11507. $col = 'A';
  11508. foreach ($headers as $h) {
  11509. $sheet->setCellValue($col . '2', $h);
  11510. $col++;
  11511. }
  11512. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  11513. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11514. $rowNum = 3;
  11515. $sumSubtotalCounts = 0;
  11516. $grandAmount = 0.0;
  11517. $globalSeq = 0;
  11518. if ($groups === []) {
  11519. $sheet->mergeCells('A3:H3');
  11520. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  11521. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11522. $rowNum = 4;
  11523. } else {
  11524. foreach ($groups as $items) {
  11525. if ($items === []) {
  11526. continue;
  11527. }
  11528. $groupLineCount = count($items);
  11529. $subAmount = 0.0;
  11530. foreach ($items as $line) {
  11531. $globalSeq++;
  11532. $dr = $line['detail'];
  11533. $amt = $this->procuremenExportAmount($dr);
  11534. $subAmount += $amt;
  11535. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  11536. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  11537. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  11538. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  11539. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  11540. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  11541. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  11542. $sheet->setCellValue('H' . $rowNum, $amt);
  11543. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  11544. $rowNum++;
  11545. }
  11546. $sumSubtotalCounts += $groupLineCount;
  11547. $grandAmount += $subAmount;
  11548. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11549. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  11550. $sheet->getStyle('G' . $rowNum)->getAlignment()
  11551. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11552. ->setVertical(Alignment::VERTICAL_CENTER);
  11553. $rowNum++;
  11554. }
  11555. }
  11556. $sheet->setCellValue('A' . $rowNum, '总计');
  11557. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  11558. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11559. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  11560. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11561. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  11562. $lastRow = $rowNum;
  11563. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  11564. 'borders' => [
  11565. 'allBorders' => [
  11566. 'borderStyle' => Border::BORDER_THIN,
  11567. 'color' => ['rgb' => '000000'],
  11568. ],
  11569. ],
  11570. ]);
  11571. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11572. if ($lastRow >= 3) {
  11573. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11574. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11575. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11576. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11577. }
  11578. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  11579. $sheet->getColumnDimension('A')->setWidth(7);
  11580. $sheet->getColumnDimension('B')->setWidth(16);
  11581. $sheet->getColumnDimension('C')->setWidth(52);
  11582. $sheet->getColumnDimension('D')->setWidth(32);
  11583. $sheet->getColumnDimension('E')->setWidth(12);
  11584. $sheet->getColumnDimension('F')->setWidth(44);
  11585. $sheet->getColumnDimension('G')->setWidth(26);
  11586. $sheet->getColumnDimension('H')->setWidth(13);
  11587. $sheet->getRowDimension(1)->setRowHeight(28);
  11588. $ymCompact = str_replace('-', '', $ym);
  11589. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  11590. $filename = $fileBase . '.xlsx';
  11591. try {
  11592. $this->ensurePurchaseMonthExportLogTable();
  11593. list($adminId, $adminName) = $this->GetUseName();
  11594. Db::table('purchase_month_export_log')->insert([
  11595. 'ym' => $ym,
  11596. 'admin_id' => (int)$adminId,
  11597. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  11598. 'row_count' => count($exportLines),
  11599. 'total_amount' => round($grandAmount, 2),
  11600. 'createtime' => time(),
  11601. ]);
  11602. } catch (\Throwable $e) {
  11603. Log::write('month export log: ' . $e->getMessage(), 'error');
  11604. }
  11605. if (ob_get_length()) {
  11606. ob_end_clean();
  11607. }
  11608. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  11609. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11610. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11611. header('Cache-Control: max-age=0');
  11612. $writer = new Xlsx($spreadsheet);
  11613. $writer->save('php://output');
  11614. $spreadsheet->disconnectWorksheets();
  11615. unset($spreadsheet);
  11616. exit;
  11617. }
  11618. /**
  11619. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  11620. */
  11621. public function export_month_quote()
  11622. {
  11623. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  11624. $this->error(__('You have no permission'));
  11625. }
  11626. $bundle = $this->prepareMonthOutwardExportBundle();
  11627. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11628. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  11629. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  11630. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  11631. $spreadsheet = new Spreadsheet();
  11632. $sheet = $spreadsheet->getActiveSheet();
  11633. $sheet->setTitle('供应商报价明细');
  11634. $mon = (int)substr($ym, 5, 2);
  11635. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  11636. $sheet->getColumnDimension('A')->setWidth(7);
  11637. $sheet->getColumnDimension('B')->setWidth(16);
  11638. $sheet->getColumnDimension('C')->setWidth(52);
  11639. $sheet->getColumnDimension('D')->setWidth(26);
  11640. $sheet->getColumnDimension('E')->setWidth(32);
  11641. $sheet->getColumnDimension('F')->setWidth(12);
  11642. $sheet->getColumnDimension('G')->setWidth(14);
  11643. $sheet->getColumnDimension('H')->setWidth(12);
  11644. if ($quoteLastRow < 1) {
  11645. $quoteLastRow = 3;
  11646. }
  11647. $ymCompact = str_replace('-', '', $ym);
  11648. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  11649. if (ob_get_length()) {
  11650. ob_end_clean();
  11651. }
  11652. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  11653. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11654. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11655. header('Cache-Control: max-age=0');
  11656. $writer = new Xlsx($spreadsheet);
  11657. $writer->save('php://output');
  11658. $spreadsheet->disconnectWorksheets();
  11659. unset($spreadsheet);
  11660. exit;
  11661. }
  11662. /**
  11663. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  11664. *
  11665. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  11666. */
  11667. protected function prepareMonthOutwardExportBundle(): array
  11668. {
  11669. $this->request->filter(['strip_tags', 'trim']);
  11670. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  11671. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  11672. $ym = date('Y-m');
  11673. }
  11674. $dbRows = [];
  11675. try {
  11676. $query = Db::table('purchase_order');
  11677. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11678. $dbRows = $query->select();
  11679. } catch (\Throwable $e) {
  11680. $dbRows = [];
  11681. }
  11682. if (!is_array($dbRows)) {
  11683. $dbRows = [];
  11684. }
  11685. $completeTsMap = [];
  11686. $sidList = [];
  11687. foreach ($dbRows as $dbRow) {
  11688. if (!is_array($dbRow)) {
  11689. continue;
  11690. }
  11691. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  11692. if ($sid > 0) {
  11693. $sidList[$sid] = true;
  11694. }
  11695. }
  11696. if ($sidList !== []) {
  11697. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  11698. }
  11699. $searchKw = trim((string)$this->request->get('search', ''));
  11700. if ($searchKw === '') {
  11701. $searchKw = trim((string)$this->request->request('search', ''));
  11702. }
  11703. $filterRaw = $this->request->get('filter', '');
  11704. $filterArrTmp = [];
  11705. if (is_string($filterRaw) && $filterRaw !== '') {
  11706. $filterArrTmp = (array)json_decode($filterRaw, true);
  11707. } elseif (is_array($filterRaw)) {
  11708. $filterArrTmp = $filterRaw;
  11709. }
  11710. $hasSearch = ($searchKw !== '');
  11711. if (!$hasSearch) {
  11712. foreach ($filterArrTmp as $fv) {
  11713. if (trim((string)$fv) !== '') {
  11714. $hasSearch = true;
  11715. break;
  11716. }
  11717. }
  11718. }
  11719. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  11720. if (!is_array($dbRow)) {
  11721. return false;
  11722. }
  11723. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  11724. if ($done['ts'] <= 0) {
  11725. return false;
  11726. }
  11727. if ($hasSearch) {
  11728. return true;
  11729. }
  11730. return date('Y-m', $done['ts']) === $ym;
  11731. }));
  11732. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  11733. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  11734. $mainBySid = [];
  11735. foreach ($pool as $rw) {
  11736. if (!is_array($rw)) {
  11737. continue;
  11738. }
  11739. $rid = (int)($rw['ID'] ?? 0);
  11740. if ($rid > 0) {
  11741. $mainBySid[$rid] = $rw;
  11742. }
  11743. }
  11744. if ($mainBySid === []) {
  11745. $detailRows = [];
  11746. } else {
  11747. try {
  11748. $detailRows = Db::table('purchase_order_detail')
  11749. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11750. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11751. ->order('status', 'desc')
  11752. ->order('CCYDH', 'asc')
  11753. ->order('company_name', 'asc')
  11754. ->order('id', 'asc')
  11755. ->select();
  11756. } catch (\Throwable $e) {
  11757. try {
  11758. $detailRows = Db::table('purchase_order_detail')
  11759. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11760. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11761. ->order('status', 'desc')
  11762. ->order('CCYDH', 'asc')
  11763. ->order('company_name', 'asc')
  11764. ->order('ID', 'asc')
  11765. ->select();
  11766. } catch (\Throwable $e2) {
  11767. $detailRows = [];
  11768. }
  11769. }
  11770. }
  11771. if (!is_array($detailRows)) {
  11772. $detailRows = [];
  11773. }
  11774. $exportLines = [];
  11775. $detailSidSeen = [];
  11776. foreach ($detailRows as $dr) {
  11777. if (!is_array($dr)) {
  11778. continue;
  11779. }
  11780. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11781. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11782. continue;
  11783. }
  11784. if (isset($detailSidSeen[$sid])) {
  11785. continue;
  11786. }
  11787. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  11788. continue;
  11789. }
  11790. $detailSidSeen[$sid] = true;
  11791. $m = $mainBySid[$sid];
  11792. $exportLines[] = [
  11793. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11794. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11795. 'company_name' => (string)($dr['company_name'] ?? ''),
  11796. 'CDF' => (string)($m['CDF'] ?? ''),
  11797. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11798. 'gx' => $this->procuremenExportGxText($m),
  11799. 'detail' => $dr,
  11800. ];
  11801. }
  11802. foreach ($detailRows as $dr) {
  11803. if (!is_array($dr)) {
  11804. continue;
  11805. }
  11806. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11807. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  11808. continue;
  11809. }
  11810. $detailSidSeen[$sid] = true;
  11811. $m = $mainBySid[$sid];
  11812. $exportLines[] = [
  11813. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11814. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11815. 'company_name' => (string)($dr['company_name'] ?? ''),
  11816. 'CDF' => (string)($m['CDF'] ?? ''),
  11817. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11818. 'gx' => $this->procuremenExportGxText($m),
  11819. 'detail' => $dr,
  11820. ];
  11821. }
  11822. foreach ($mainBySid as $sid => $m) {
  11823. if (isset($detailSidSeen[$sid])) {
  11824. continue;
  11825. }
  11826. $company = trim((string)($m['pick_company_name'] ?? ''));
  11827. $exportLines[] = [
  11828. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  11829. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  11830. 'company_name' => $company,
  11831. 'CDF' => (string)($m['CDF'] ?? ''),
  11832. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11833. 'gx' => $this->procuremenExportGxText($m),
  11834. 'detail' => [],
  11835. ];
  11836. }
  11837. $groups = [];
  11838. foreach ($exportLines as $line) {
  11839. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  11840. if (!isset($groups[$k])) {
  11841. $groups[$k] = [];
  11842. }
  11843. $groups[$k][] = $line;
  11844. }
  11845. ksort($groups, SORT_STRING);
  11846. return [
  11847. 'ym' => $ym,
  11848. 'mainBySid' => $mainBySid,
  11849. 'detailRows' => $detailRows,
  11850. 'exportLines' => $exportLines,
  11851. 'groups' => $groups,
  11852. ];
  11853. }
  11854. /**
  11855. * 导出用:工序列文案
  11856. */
  11857. protected function procuremenExportGxText(array $r)
  11858. {
  11859. $a = trim((string)($r['CDXMC'] ?? ''));
  11860. $b = trim((string)($r['CGYMC'] ?? ''));
  11861. if ($a !== '' && $b !== '') {
  11862. return $a . ':' . $b;
  11863. }
  11864. return $a !== '' ? $a : $b;
  11865. }
  11866. /**
  11867. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  11868. */
  11869. protected function procuremenExportAmount(array $r)
  11870. {
  11871. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  11872. if (!array_key_exists($k, $r)) {
  11873. continue;
  11874. }
  11875. $v = $r[$k];
  11876. if ($v === null || $v === '') {
  11877. continue;
  11878. }
  11879. if (is_numeric($v)) {
  11880. return (float)$v;
  11881. }
  11882. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  11883. if ($v !== '' && is_numeric($v)) {
  11884. return (float)$v;
  11885. }
  11886. }
  11887. return 0.0;
  11888. }
  11889. /**
  11890. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  11891. *
  11892. * @param array<int, array<string, mixed>> $detailRows
  11893. * @param array<int, array<string, mixed>> $mainBySid
  11894. * @return array<int, array<string, mixed>>
  11895. */
  11896. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  11897. {
  11898. $lines = [];
  11899. foreach ($detailRows as $dr) {
  11900. if (!is_array($dr)) {
  11901. continue;
  11902. }
  11903. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11904. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11905. continue;
  11906. }
  11907. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  11908. continue;
  11909. }
  11910. $cn = trim((string)($dr['company_name'] ?? ''));
  11911. if ($cn === '') {
  11912. continue;
  11913. }
  11914. $m = $mainBySid[$sid];
  11915. $am = trim((string)($dr['amount'] ?? ''));
  11916. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  11917. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  11918. $amountText = $amountFilled
  11919. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  11920. : '未填写';
  11921. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  11922. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  11923. if ($deliveryShow === '' && $deliveryRaw !== '') {
  11924. $deliveryShow = $deliveryRaw;
  11925. }
  11926. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  11927. ? $deliveryShow
  11928. : '未填写';
  11929. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  11930. $lines[] = [
  11931. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11932. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11933. 'gx' => $this->procuremenExportGxText($m),
  11934. 'company_name' => $cn,
  11935. 'amount_text' => $amountText,
  11936. 'amount_num' => $amountFilled ? $amountNum : null,
  11937. 'delivery_text' => $deliveryText,
  11938. 'picked_text' => $picked ? '中标' : '未中标',
  11939. 'picked' => $picked,
  11940. ];
  11941. }
  11942. $winnerSupplierByOrder = [];
  11943. foreach ($lines as $line) {
  11944. $dh = trim((string)($line['CCYDH'] ?? ''));
  11945. $cn = trim((string)($line['company_name'] ?? ''));
  11946. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  11947. $winnerSupplierByOrder[$dh][$cn] = true;
  11948. }
  11949. }
  11950. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  11951. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  11952. if ($c !== 0) {
  11953. return $c;
  11954. }
  11955. $dh = trim((string)($a['CCYDH'] ?? ''));
  11956. $aCn = trim((string)($a['company_name'] ?? ''));
  11957. $bCn = trim((string)($b['company_name'] ?? ''));
  11958. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  11959. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  11960. if ($aSupplierWin !== $bSupplierWin) {
  11961. return $aSupplierWin ? -1 : 1;
  11962. }
  11963. $c = strcmp($aCn, $bCn);
  11964. if ($c !== 0) {
  11965. return $c;
  11966. }
  11967. if (!empty($a['picked']) !== !empty($b['picked'])) {
  11968. return !empty($a['picked']) ? -1 : 1;
  11969. }
  11970. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  11971. if ($c !== 0) {
  11972. return $c;
  11973. }
  11974. return 0;
  11975. });
  11976. return $lines;
  11977. }
  11978. /**
  11979. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  11980. *
  11981. * @param array<int, array<string, mixed>> $quoteLines
  11982. */
  11983. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  11984. {
  11985. $mon = (int)substr($ym, 5, 2);
  11986. $titleRow = $startRow;
  11987. $headerRow = $startRow + 1;
  11988. $dataStartRow = $startRow + 2;
  11989. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  11990. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  11991. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  11992. $sheet->getStyle('A' . $titleRow)->getAlignment()
  11993. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11994. ->setVertical(Alignment::VERTICAL_CENTER);
  11995. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  11996. $col = 'A';
  11997. foreach ($headers as $h) {
  11998. $sheet->setCellValue($col . $headerRow, $h);
  11999. $col++;
  12000. }
  12001. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  12002. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12003. $rowNum = $dataStartRow;
  12004. if ($quoteLines === []) {
  12005. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  12006. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  12007. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12008. $rowNum = $dataStartRow + 1;
  12009. } else {
  12010. $i = 0;
  12011. foreach ($quoteLines as $line) {
  12012. $i++;
  12013. $sheet->setCellValue('A' . $rowNum, $i);
  12014. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  12015. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  12016. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  12017. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  12018. if ($line['amount_num'] !== null) {
  12019. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  12020. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  12021. } else {
  12022. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  12023. }
  12024. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  12025. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  12026. if (!empty($line['picked'])) {
  12027. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12028. }
  12029. $rowNum++;
  12030. }
  12031. }
  12032. $lastRow = $rowNum - 1;
  12033. if ($lastRow >= $headerRow) {
  12034. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  12035. 'borders' => [
  12036. 'allBorders' => [
  12037. 'borderStyle' => Border::BORDER_THIN,
  12038. 'color' => ['rgb' => '000000'],
  12039. ],
  12040. ],
  12041. ]);
  12042. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12043. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12044. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12045. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12046. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  12047. if ($lastRow >= $dataStartRow) {
  12048. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  12049. }
  12050. }
  12051. return $lastRow;
  12052. }
  12053. /**
  12054. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  12055. */
  12056. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  12057. {
  12058. if ($lastRow < $dataStartRow || $headerRow < 1) {
  12059. return;
  12060. }
  12061. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  12062. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12063. ->setVertical(Alignment::VERTICAL_CENTER);
  12064. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  12065. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12066. ->setVertical(Alignment::VERTICAL_CENTER);
  12067. if ($lastCol > 'B') {
  12068. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  12069. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12070. ->setVertical(Alignment::VERTICAL_CENTER);
  12071. }
  12072. }
  12073. /**
  12074. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  12075. */
  12076. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  12077. {
  12078. $s = trim($ccydh);
  12079. if ($s === '') {
  12080. return 'ORDER';
  12081. }
  12082. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12083. $s = trim($s, '._-');
  12084. if ($s === '') {
  12085. return 'ORDER';
  12086. }
  12087. if (function_exists('mb_substr')) {
  12088. return mb_substr($s, 0, 80, 'UTF-8');
  12089. }
  12090. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12091. }
  12092. /**
  12093. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12094. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12095. *
  12096. * @return array{objectKey: string, webPath: string}
  12097. */
  12098. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12099. {
  12100. $sid = (int)$scydgyId;
  12101. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12102. $y = date('Y');
  12103. $m = date('m');
  12104. $d = date('d');
  12105. $basename = $safeOrder . '_' . $sid . '.pdf';
  12106. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12107. return [
  12108. 'objectKey' => $objectKey,
  12109. 'webPath' => '/' . $objectKey,
  12110. ];
  12111. }
  12112. /**
  12113. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12114. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12115. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12116. *
  12117. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12118. */
  12119. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12120. {
  12121. if (!$this->isValidScydgyRowId($scydgyId)) {
  12122. return '';
  12123. }
  12124. $ids = trim((string)$scydgyId);
  12125. $prep = $this->prepareProcuremenDetailsView($ids);
  12126. if (!$prep['ok']) {
  12127. return '';
  12128. }
  12129. $ccydh = $prep['ccydh'];
  12130. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12131. $objectKey = $paths['objectKey'];
  12132. $webPath = $paths['webPath'];
  12133. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  12134. $this->view->assign([
  12135. 'pdf_export' => 1,
  12136. 'pdfMetaLine' => $meta,
  12137. ]);
  12138. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12139. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12140. $this->view->engine->layout(false);
  12141. try {
  12142. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12143. } catch (\Throwable $e) {
  12144. if ($restoreLayout) {
  12145. $this->view->engine->layout($restoreLayout);
  12146. }
  12147. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12148. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12149. return '';
  12150. }
  12151. if ($restoreLayout) {
  12152. $this->view->engine->layout($restoreLayout);
  12153. }
  12154. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12155. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12156. if (!is_dir($tempDir)) {
  12157. @mkdir($tempDir, 0755, true);
  12158. }
  12159. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12160. try {
  12161. $mpdf = new \Mpdf\Mpdf([
  12162. 'mode' => 'utf-8',
  12163. 'format' => 'A4',
  12164. 'margin_left' => 12,
  12165. 'margin_right' => 12,
  12166. 'margin_top' => 14,
  12167. 'margin_bottom' => 14,
  12168. 'tempDir' => $tempDir,
  12169. 'autoScriptToLang' => true,
  12170. 'autoLangToFont' => true,
  12171. ]);
  12172. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12173. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12174. $mpdf->SetBasePath('http://127.0.0.1/');
  12175. $mpdf->WriteHTML($html);
  12176. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12177. } catch (\Throwable $e) {
  12178. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12179. if (is_file($tempPdf)) {
  12180. @unlink($tempPdf);
  12181. }
  12182. return '';
  12183. }
  12184. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12185. if ($ossUrl !== '') {
  12186. @unlink($tempPdf);
  12187. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12188. return $ossUrl;
  12189. }
  12190. $pi = pathinfo($objectKey);
  12191. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12192. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12193. if ($baseFile === '') {
  12194. @unlink($tempPdf);
  12195. return '';
  12196. }
  12197. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12198. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12199. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12200. @unlink($tempPdf);
  12201. return '';
  12202. }
  12203. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12204. if (!@copy($tempPdf, $fullPath)) {
  12205. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12206. @unlink($tempPdf);
  12207. return '';
  12208. }
  12209. @unlink($tempPdf);
  12210. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12211. return $webPath;
  12212. }
  12213. /**
  12214. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12215. */
  12216. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12217. {
  12218. if ($scydgyId <= 0 || $webPath === '') {
  12219. return;
  12220. }
  12221. try {
  12222. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12223. } catch (\Throwable $e) {
  12224. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12225. }
  12226. }
  12227. /**
  12228. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12229. *
  12230. * @param array<string, string> $vars
  12231. * @return array<string, string>
  12232. */
  12233. protected function normalizeSmsTemplateVars(array $vars): array
  12234. {
  12235. $out = [];
  12236. foreach ($vars as $k => $v) {
  12237. $out[(string)$k] = trim((string)$v);
  12238. }
  12239. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12240. $out['contact_name'] = $out['company_name'];
  12241. }
  12242. return $out;
  12243. }
  12244. /**
  12245. * 按手机号或公司名称查 customer 表联系人姓名
  12246. */
  12247. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12248. {
  12249. $phone = trim($phone);
  12250. $companyName = trim($companyName);
  12251. try {
  12252. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12253. $row = Db::table('customer')
  12254. ->where(function ($q) use ($phone) {
  12255. $q->where('phone', $phone)->whereOr('account', $phone);
  12256. })
  12257. ->order('id', 'asc')
  12258. ->find();
  12259. if (is_array($row)) {
  12260. $nm = trim((string)($row['username'] ?? ''));
  12261. if ($nm !== '') {
  12262. return $nm;
  12263. }
  12264. }
  12265. }
  12266. if ($companyName !== '') {
  12267. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12268. if (is_array($row)) {
  12269. return trim((string)($row['username'] ?? ''));
  12270. }
  12271. }
  12272. } catch (\Throwable $e) {
  12273. }
  12274. return '';
  12275. }
  12276. /**
  12277. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  12278. */
  12279. protected function plainTextToHtmlEmailBody(string $text): string
  12280. {
  12281. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12282. $parts = explode("\n", $text);
  12283. $out = [];
  12284. foreach ($parts as $line) {
  12285. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12286. $out[] = $line;
  12287. } else {
  12288. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12289. }
  12290. }
  12291. return implode("<br>\n", $out);
  12292. }
  12293. /**
  12294. * 短信场景:去掉链接类变量,避免误填 URL
  12295. *
  12296. * @param array<string, string> $vars
  12297. * @return array<string, string>
  12298. */
  12299. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12300. {
  12301. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12302. return $vars;
  12303. }
  12304. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12305. $vars[$k] = '';
  12306. }
  12307. return $vars;
  12308. }
  12309. /**
  12310. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12311. *
  12312. * @param array<string, string> $vars
  12313. */
  12314. protected function renderNotifyTemplate(string $scene, array $vars): string
  12315. {
  12316. $vars = $this->normalizeSmsTemplateVars($vars);
  12317. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12318. $row = $this->loadNotifyTemplateRow($scene);
  12319. if ($row === null) {
  12320. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12321. }
  12322. $tpl = trim((string)($row['content'] ?? ''));
  12323. if ($tpl === '') {
  12324. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12325. }
  12326. foreach ($vars as $k => $v) {
  12327. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12328. }
  12329. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12330. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12331. return $tpl;
  12332. }
  12333. protected function resolveProcuremenEmailSubject(string $scene): string
  12334. {
  12335. // 询价通知业务员 / 供应商询价:模版名称即邮件主题
  12336. if ($scene === 'rfq_salesman_email' || $scene === 'rfq_supplier_email') {
  12337. $row = $this->loadNotifyTemplateRow($scene);
  12338. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12339. if ($title !== '') {
  12340. return $title;
  12341. }
  12342. return $scene === 'rfq_supplier_email' ? '供应商询价通知' : '协助采购询价通知';
  12343. }
  12344. $map = [
  12345. 'review_email' => '您有新的协助加工订单',
  12346. ];
  12347. $subject = trim((string)($map[$scene] ?? ''));
  12348. if ($subject === '') {
  12349. $this->error('未配置邮件主题:' . $scene);
  12350. }
  12351. return $subject;
  12352. }
  12353. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12354. {
  12355. $map = [
  12356. 'review_email' => '协助下发-邮箱',
  12357. 'review_sms' => '协助下发-短信',
  12358. 'confirm_ok' => '采购确认-通过',
  12359. 'confirm_fail' => '采购确认-未通过',
  12360. 'bid_open' => '开标双重验证',
  12361. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12362. 'rfq_supplier_email' => '供应商询价通知',
  12363. ];
  12364. $label = $map[$scene] ?? $scene;
  12365. if ($titleRequired) {
  12366. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12367. }
  12368. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12369. }
  12370. /**
  12371. * 是否开启协助通知演练(不发真实短信/邮件)
  12372. */
  12373. protected function isProcuremenNotifyDryRun(): bool
  12374. {
  12375. return (bool)Config::get('procuremen_notify_dry_run');
  12376. }
  12377. /**
  12378. * @param array<string, mixed> $payload
  12379. */
  12380. protected function recordNotifyDryRunPreview(array $payload): void
  12381. {
  12382. $this->notifyDryRunPreview[] = $payload;
  12383. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  12384. }
  12385. /**
  12386. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  12387. * @throws \Exception
  12388. */
  12389. protected function smsbao($phone, $content)
  12390. {
  12391. if ($this->isProcuremenNotifyDryRun()) {
  12392. $this->recordNotifyDryRunPreview([
  12393. 'scene' => 'sms_only',
  12394. 'phone' => $phone,
  12395. 'sms_content' => $content,
  12396. ]);
  12397. return;
  12398. }
  12399. $statusStr = [
  12400. '0' => '短信发送成功',
  12401. '-1' => '参数不全',
  12402. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  12403. '30' => '密码错误',
  12404. '40' => '账号不存在',
  12405. '41' => '余额不足',
  12406. '42' => '帐户已过期',
  12407. '43' => 'IP地址限制',
  12408. '50' => '内容含有敏感词',
  12409. ];
  12410. $smsapi = 'http://api.smsbao.com/';
  12411. $user = 'zhuwei123';
  12412. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  12413. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  12414. $result = @file_get_contents($sendurl);
  12415. if ($result === false) {
  12416. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  12417. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  12418. }
  12419. $result = trim((string)$result);
  12420. if ($result !== '0') {
  12421. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  12422. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  12423. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  12424. }
  12425. }
  12426. }