Procuremen.php 279 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenStatus;
  6. use PHPMailer\PHPMailer\PHPMailer;
  7. use think\Config;
  8. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  9. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  10. use PhpOffice\PhpSpreadsheet\Style\Border;
  11. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  12. use think\Db;
  13. use think\Log;
  14. class Procuremen extends Backend
  15. {
  16. /**
  17. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  18. */
  19. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  20. /**
  21. * Procuremen模型对象
  22. * @var \app\admin\model\Procuremen
  23. */
  24. protected $model = null;
  25. /**
  26. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  27. */
  28. protected $notifyDryRunPreview = [];
  29. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  30. protected $procuremenRedisCache = null;
  31. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  32. protected $pickHiddenScydgySetCache = null;
  33. /**
  34. * @var array
  35. */
  36. protected $noNeedRight = [
  37. 'review', 'reviewCompanies', 'outward_detail', 'export_month_outward', 'snapshotToProcure',
  38. 'pick', 'audit', 'confirm', 'pickreview', 'picksubmit', 'pickadd', 'auditissue', 'auditsubmit',
  39. 'auditresendsms', 'auditabandon', 'archiveabandon', 'auditresendemail', 'purchaseconfirmpick', 'purchaseapprovalreject', 'add', 'pickdelete', 'completeDirectly', 'rfqlist', 'details',
  40. ];
  41. public function _initialize()
  42. {
  43. parent::_initialize();
  44. $this->model = new \app\admin\model\Procuremen;
  45. }
  46. /**
  47. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  48. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  49. *
  50. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  51. */
  52. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  53. {
  54. static $mprocCfgLoaded = false;
  55. if (!$mprocCfgLoaded) {
  56. $mprocCfgLoaded = true;
  57. if (is_file(APP_PATH . 'extra/mproc.php')) {
  58. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  59. }
  60. }
  61. $eid = (int)$purchaseOrderDetailId;
  62. $base = $this->resolveMprocMobilePublicBaseUrl();
  63. if ($base === '') {
  64. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  65. }
  66. $path = trim((string)Config::get('mproc.mobile_index_path'));
  67. if ($path === '') {
  68. $path = '/index.php/index/index/index';
  69. } else {
  70. $path = '/' . ltrim($path, '/');
  71. }
  72. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  73. if ($eid > 0) {
  74. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  75. }
  76. return $base . $path . '?main_tab=orders';
  77. }
  78. /**
  79. * 邮件/短信外链:须为带点的公网域名
  80. */
  81. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  82. {
  83. $u = trim((string)$baseUrl);
  84. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  85. return false;
  86. }
  87. $host = parse_url($u, PHP_URL_HOST);
  88. if (!is_string($host) || $host === '') {
  89. return false;
  90. }
  91. if (strcasecmp($host, 'localhost') === 0) {
  92. return false;
  93. }
  94. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  95. return false;
  96. }
  97. if (strpos($host, '.') === false) {
  98. return false;
  99. }
  100. return true;
  101. }
  102. /**
  103. * 解析用于协助邮件/短信的手机端站点根
  104. */
  105. protected function resolveMprocMobilePublicBaseUrl()
  106. {
  107. $candidates = [];
  108. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  109. $candidates[] = trim((string)Config::get('site.indexurl'));
  110. $cdn = trim((string)Config::get('site.cdnurl'));
  111. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  112. $candidates[] = rtrim($cdn, '/');
  113. }
  114. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  115. $candidates[] = $reqBase;
  116. foreach ($candidates as $c) {
  117. if ($c === '') {
  118. continue;
  119. }
  120. $c = rtrim($c, '/');
  121. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  122. return $c;
  123. }
  124. }
  125. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  126. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  127. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  128. return $reqBase;
  129. }
  130. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  131. return '';
  132. }
  133. /**
  134. * 排除 mcyd.dputrecord 空串、零日期等非法值,避免 MySQL 1525(DATE_FORMAT/BETWEEN 遇 '' 报错)
  135. */
  136. protected function whereMcydDputrecordValid($query, $alias = 'a')
  137. {
  138. $c = $alias . '.dStamp';
  139. // 先转成 CHAR 再判断,避免 DATETIME 列里存 '' / 0000-00-00 时参与日期函数报错
  140. return $query->whereRaw(
  141. $c . ' IS NOT NULL'
  142. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) <> \'\''
  143. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) NOT LIKE \'0000-00-00%\''
  144. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) REGEXP \'^[12][0-9]{3}-[01][0-9]-[0-3][0-9]\''
  145. );
  146. }
  147. /**
  148. * 获取 Redis 中 procuremen_redis
  149. */
  150. protected function ProcuremenRedis(): array
  151. {
  152. if ($this->procuremenRedisCache !== null) {
  153. return $this->procuremenRedisCache;
  154. }
  155. try {
  156. $redis = redis();
  157. $raw = $redis->get('procuremen_redis');
  158. if ($raw === false || $raw === '') {
  159. $this->procuremenRedisCache = [];
  160. return $this->procuremenRedisCache;
  161. }
  162. $decoded = json_decode($raw, true);
  163. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  164. $this->procuremenRedisCache = [];
  165. return $this->procuremenRedisCache;
  166. }
  167. $this->procuremenRedisCache = $decoded['data'];
  168. return $this->procuremenRedisCache;
  169. } catch (\Throwable $e) {
  170. $this->procuremenRedisCache = [];
  171. return $this->procuremenRedisCache;
  172. }
  173. }
  174. /**
  175. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  176. *
  177. * @return array<int, array<string, mixed>>
  178. */
  179. protected function procuremenFetchErpPoolFromDb(): array
  180. {
  181. try {
  182. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  183. $endTime = date('Y-m-d 23:59:59');
  184. $list = Db::table('scydgy')
  185. ->alias('a')
  186. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  187. ->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, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  188. ->where([
  189. 'a.bwjg' => 1,
  190. 'a.iEndBz' => 0,
  191. 'a.iType' => 0,
  192. 'a.iStatus' => 10,
  193. ])
  194. ->where('a.dStamp', '>=', $startTime)
  195. ->where('a.dStamp', '<=', $endTime)
  196. ->order('a.dStamp', 'desc')
  197. ->select();
  198. if (!is_array($list)) {
  199. return [];
  200. }
  201. try {
  202. $redis = redis();
  203. $payload = [
  204. 'code' => 200,
  205. 'msg' => 'success',
  206. 'data' => $list,
  207. ];
  208. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  209. $this->procuremenRedisCache = $list;
  210. } catch (\Throwable $e) {
  211. }
  212. return $list;
  213. } catch (\Throwable $e) {
  214. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  215. return [];
  216. }
  217. }
  218. /**
  219. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  220. *
  221. * @return array<int, array<string, mixed>>
  222. */
  223. protected function procuremenEnsureRedisPool(): array
  224. {
  225. $pool = $this->ProcuremenRedis();
  226. if (is_array($pool) && $pool !== []) {
  227. return $pool;
  228. }
  229. static $warmed = false;
  230. if ($warmed) {
  231. return is_array($pool) ? $pool : [];
  232. }
  233. $warmed = true;
  234. return $this->procuremenFetchErpPoolFromDb();
  235. }
  236. /**
  237. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  238. *
  239. * @param array<string, mixed> $row
  240. */
  241. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  242. {
  243. $t = $this->procuremenRowListSortTime($row, $primary);
  244. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  245. return null;
  246. }
  247. $mo = (int)$m[2];
  248. if ($mo < 1 || $mo > 12) {
  249. return null;
  250. }
  251. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  252. }
  253. /**
  254. * @param array<int, array{year:string, months:array}> $sidebar
  255. * @return array<int, array{year:string, months:array}>
  256. */
  257. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  258. {
  259. $ym = trim($ym);
  260. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  261. return $sidebar;
  262. }
  263. foreach ($sidebar as $block) {
  264. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  265. continue;
  266. }
  267. foreach ($block['months'] as $item) {
  268. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  269. return $sidebar;
  270. }
  271. }
  272. }
  273. $y = substr($ym, 0, 4);
  274. $mo = (int)substr($ym, 5, 2);
  275. $sidebar[] = [
  276. 'year' => $y,
  277. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  278. ];
  279. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  280. }
  281. /**
  282. * @param array<int, array{year:string, months:array}> $sidebar
  283. * @return string[]
  284. */
  285. protected function flattenProcuremenSidebarYms(array $sidebar): array
  286. {
  287. $yms = [];
  288. foreach ($sidebar as $block) {
  289. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  290. continue;
  291. }
  292. foreach ($block['months'] as $item) {
  293. if (!is_array($item)) {
  294. continue;
  295. }
  296. $ym = trim((string)($item['ym'] ?? ''));
  297. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  298. $yms[$ym] = true;
  299. }
  300. }
  301. }
  302. return array_keys($yms);
  303. }
  304. /**
  305. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  306. */
  307. protected function GetIndexYearMonths()
  308. {
  309. $ymSet = [];
  310. $pool = $this->procuremenEnsureRedisPool();
  311. foreach ($pool as $r) {
  312. if (!is_array($r)) {
  313. continue;
  314. }
  315. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  316. if ($ym !== null) {
  317. $ymSet[$ym] = true;
  318. }
  319. }
  320. foreach ($this->loadPickManualOrderRows() as $r) {
  321. if (!is_array($r)) {
  322. continue;
  323. }
  324. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  325. if ($ym !== null) {
  326. $ymSet[$ym] = true;
  327. }
  328. }
  329. $ymList = array_keys($ymSet);
  330. if ($ymList === []) {
  331. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  332. }
  333. return $this->buildYearMonthSidebar($ymList);
  334. }
  335. /**
  336. * @param string[] $ymList 形如 2026-06
  337. * @return array<int, array{year:string, months:array}>
  338. */
  339. protected function buildYearMonthSidebar(array $ymList): array
  340. {
  341. rsort($ymList, SORT_STRING);
  342. $byYear = [];
  343. foreach ($ymList as $ym) {
  344. $y = substr($ym, 0, 4);
  345. $mo = (int)substr($ym, 5, 2);
  346. if (!isset($byYear[$y])) {
  347. $byYear[$y] = [];
  348. }
  349. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  350. }
  351. krsort($byYear, SORT_NUMERIC);
  352. foreach ($byYear as $y => $items) {
  353. usort($byYear[$y], function ($a, $b) {
  354. return strcmp($b['ym'], $a['ym']);
  355. });
  356. }
  357. $sidebar = [];
  358. foreach ($byYear as $y => $months) {
  359. $sidebar[] = ['year' => $y, 'months' => $months];
  360. }
  361. return $sidebar;
  362. }
  363. /**
  364. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  365. */
  366. protected function GetIssuedOrderYearMonths(string $stage): array
  367. {
  368. $ymSet = [];
  369. try {
  370. $query = Db::table('purchase_order');
  371. $this->applyPurchaseOrderNotDeletedWhere($query);
  372. if ($stage === 'audit') {
  373. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  374. } elseif ($stage === 'confirm') {
  375. $query->whereRaw(ProcuremenStatus::sqlPoInProgress('status'))->where(function ($q) {
  376. $q->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  377. ->whereOr(function ($q2) {
  378. $q2->whereIn('wflow_status', ProcuremenStatus::wflowPendingIssueValues())
  379. ->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  380. });
  381. });
  382. } else {
  383. return $this->GetIndexYearMonths();
  384. }
  385. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  386. if (is_array($rows)) {
  387. foreach ($rows as $r) {
  388. if (!is_array($r)) {
  389. continue;
  390. }
  391. $ym = $this->procuremenRowYearMonth($r, 'pick_time');
  392. if ($ym !== null) {
  393. $ymSet[$ym] = true;
  394. }
  395. }
  396. }
  397. } catch (\Throwable $e) {
  398. $ymSet = [];
  399. }
  400. $ymList = array_keys($ymSet);
  401. if ($ymList === []) {
  402. $def = $this->resolveProcuremenDefaultYm($stage);
  403. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  404. }
  405. return $this->buildYearMonthSidebar($ymList);
  406. }
  407. /**
  408. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  409. */
  410. protected function resolveProcuremenDefaultYm(string $stage): string
  411. {
  412. if ($stage === 'pick') {
  413. return date('Y-m');
  414. }
  415. try {
  416. $query = Db::table('purchase_order');
  417. $this->applyPurchaseOrderNotDeletedWhere($query);
  418. if ($stage === 'audit') {
  419. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  420. } elseif ($stage === 'confirm') {
  421. $query->whereRaw(ProcuremenStatus::sqlPoInProgress('status'))->where(function ($q) {
  422. $q->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  423. ->whereOr(function ($q2) {
  424. $q2->whereIn('wflow_status', ProcuremenStatus::wflowPendingIssueValues())
  425. ->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  426. });
  427. });
  428. } else {
  429. return date('Y-m');
  430. }
  431. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  432. if ($latest === null || $latest === '') {
  433. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  434. }
  435. $t = $this->formatProcuremenDetailTime($latest);
  436. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  437. return $m[1] . '-' . $m[2];
  438. }
  439. } catch (\Throwable $e) {
  440. }
  441. return date('Y-m');
  442. }
  443. protected function applyPurchaseOrderNotDeletedWhere($query): void
  444. {
  445. $query->whereRaw(
  446. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  447. );
  448. }
  449. /** @deprecated 使用 {@see ProcuremenStatus::POD_VOID} */
  450. protected const PURCHASE_DETAIL_STATUS_VOID = '已废弃';
  451. protected function isPurchaseOrderDetailVoid(array $row): bool
  452. {
  453. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  454. return true;
  455. }
  456. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  457. }
  458. /**
  459. * 仅当前有效下发明细(排除废弃归档)
  460. */
  461. protected function applyActivePurchaseOrderDetailWhere($query): void
  462. {
  463. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  464. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  465. }
  466. /**
  467. * 列表/流程判定:存在有效下发明细
  468. */
  469. protected function purchaseOrderDetailActiveExistsSql(string $detailAlias = 'd'): string
  470. {
  471. $void = ProcuremenStatus::POD_VOID;
  472. return 'EXISTS (SELECT 1 FROM purchase_order_detail ' . $detailAlias
  473. . ' WHERE ' . $detailAlias . '.scydgy_id = purchase_order.scydgy_id'
  474. . ' AND ' . str_replace('`status`', $detailAlias . '.`status`', ProcuremenStatus::sqlPodNotVoid($detailAlias . '.status'))
  475. . ' AND (' . $detailAlias . '.status_name IS NULL OR TRIM(' . $detailAlias . '.status_name) = \'\' OR ' . $detailAlias . '.status_name <> \'' . $void . '\')'
  476. . ' LIMIT 1)';
  477. }
  478. /**
  479. * 废弃退回初选:下发明细标记归档,不物理删除
  480. *
  481. * @param array<int, int|string> $scydgyIds
  482. */
  483. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  484. {
  485. $ids = [];
  486. foreach ($scydgyIds as $sid) {
  487. $n = (int)$sid;
  488. if ($this->isValidScydgyRowId($n) || $n < 0) {
  489. $ids[$n] = true;
  490. }
  491. }
  492. if ($ids === []) {
  493. return;
  494. }
  495. $void = ProcuremenStatus::POD_VOID;
  496. Db::table('purchase_order_detail')
  497. ->where('scydgy_id', 'in', array_keys($ids))
  498. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  499. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  500. ->update([
  501. 'status' => $void,
  502. 'status_name' => $void,
  503. ]);
  504. }
  505. /**
  506. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  507. */
  508. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  509. {
  510. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  511. $norm = function (string $col) use ($p): string {
  512. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  513. };
  514. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  515. $parts = [];
  516. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  517. if ($key === 'createtime') {
  518. $parts[] = $createtime;
  519. } else {
  520. $parts[] = $norm($key);
  521. }
  522. }
  523. return 'COALESCE(' . implode(', ', $parts) . ')';
  524. }
  525. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  526. {
  527. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  528. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  529. }
  530. /**
  531. * @return array<int, array<string, mixed>>
  532. */
  533. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  534. {
  535. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  536. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  537. try {
  538. $query = Db::table('purchase_order')->field($fields);
  539. $this->applyPurchaseOrderNotDeletedWhere($query);
  540. if ($stage === 'audit') {
  541. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('pick_time', 'desc')->order('id', 'desc');
  542. } elseif ($stage === 'confirm') {
  543. $query->whereRaw(ProcuremenStatus::sqlPoInProgress('status'))->where(function ($q) {
  544. $q->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  545. ->whereOr(function ($q2) {
  546. $q2->whereIn('wflow_status', ProcuremenStatus::wflowPendingIssueValues())
  547. ->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  548. });
  549. })->order('pick_time', 'desc')->order('id', 'desc');
  550. } else {
  551. return [];
  552. }
  553. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  554. $monthStart = $ym . '-01 00:00:00';
  555. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  556. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  557. }
  558. $rows = $query->select();
  559. } catch (\Throwable $e) {
  560. $rows = [];
  561. }
  562. return is_array($rows) ? $rows : [];
  563. }
  564. /**
  565. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  566. */
  567. protected function resolveProcuremenListStage(): string
  568. {
  569. $action = strtolower((string)$this->request->action());
  570. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  571. return $action;
  572. }
  573. $tab = trim((string)$this->request->request('wff_tab', 'pick'));
  574. return in_array($tab, ['pick', 'audit', 'confirm'], true) ? $tab : 'pick';
  575. }
  576. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  577. {
  578. $rootTrue = rtrim((string)$this->request->root(true), '/');
  579. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  580. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  581. $indexPhpRoot = $rootTrue . '/index.php';
  582. }
  583. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  584. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  585. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  586. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  587. $this->view->assign('defaultYm', $defaultYm);
  588. $this->view->assign('sidebarYearMonths', $sidebar);
  589. $this->view->assign('procuremenStage', $stage);
  590. $this->view->assign('procuremenPageTitle', $pageTitle);
  591. }
  592. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  593. public function pick()
  594. {
  595. $this->request->filter(['strip_tags', 'trim']);
  596. if (!$this->request->isAjax()) {
  597. $this->assignProcuremenListPage('pick', '协助下发');
  598. return $this->view->fetch('procuremen/index');
  599. }
  600. return $this->index();
  601. }
  602. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  603. public function audit()
  604. {
  605. $this->request->filter(['strip_tags', 'trim']);
  606. if (!$this->request->isAjax()) {
  607. $this->assignProcuremenListPage('audit', '确认供应商');
  608. return $this->view->fetch('procuremen/index');
  609. }
  610. return $this->index();
  611. }
  612. /** 采购确认(定标) */
  613. public function confirm()
  614. {
  615. $this->request->filter(['strip_tags', 'trim']);
  616. if (!$this->request->isAjax()) {
  617. $this->assignProcuremenListPage('confirm', '采购确认');
  618. return $this->view->fetch('procuremen/index');
  619. }
  620. return $this->index();
  621. }
  622. /**
  623. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  624. */
  625. public function index()
  626. {
  627. $this->request->filter(['strip_tags', 'trim']);
  628. if (!$this->request->isAjax()) {
  629. $this->assignProcuremenListPage('pick', '协助下发');
  630. return $this->view->fetch('procuremen/index');
  631. }
  632. if ($this->request->request('keyField')) {
  633. return $this->selectpage();
  634. }
  635. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  636. $limit = max(10, min(500, (int)$limit));
  637. $ym = $this->request->request('ym', date('Y-m'));
  638. $ym = is_string($ym) ? trim($ym) : '';
  639. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  640. $ym = date('Y-m');
  641. }
  642. $monthStart = $ym . '-01 00:00:00';
  643. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  644. $search = trim((string)$this->request->get('search', ''));
  645. $hasActiveSearch = ($search !== '');
  646. if (!$hasActiveSearch) {
  647. $filterStr = $this->request->get('filter', '');
  648. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  649. $arr = json_decode($filterStr, true);
  650. if (is_array($arr) && count($arr) > 0) {
  651. foreach ($arr as $v) {
  652. if (is_array($v)) {
  653. if (array_filter($v, function ($x) {
  654. return $x !== '' && $x !== null;
  655. })) {
  656. $hasActiveSearch = true;
  657. break;
  658. }
  659. } elseif ($v !== '' && $v !== null) {
  660. $hasActiveSearch = true;
  661. break;
  662. }
  663. }
  664. }
  665. }
  666. }
  667. $applyMonthRange = !$hasActiveSearch;
  668. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  669. $opArr = (array)json_decode($this->request->get('op', ''), true);
  670. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  671. $wffTab = $this->resolveProcuremenListStage();
  672. try {
  673. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  674. if ($wffTab === 'audit') {
  675. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  676. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  677. );
  678. } elseif ($wffTab === 'confirm') {
  679. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  680. $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange)
  681. );
  682. } else {
  683. $pool = $this->procuremenEnsureRedisPool();
  684. if (!is_array($pool)) {
  685. $pool = [];
  686. }
  687. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  688. $hideSet = $this->loadPickHiddenScydgySet();
  689. if ($pool !== [] && $hideSet !== []) {
  690. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  691. if (!is_array($r)) {
  692. return false;
  693. }
  694. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  695. return $id <= 0 || !isset($hideSet[$id]);
  696. }));
  697. }
  698. $manualPool = $this->loadPickManualOrderRows();
  699. if ($manualPool !== []) {
  700. $pool = array_merge($pool, $manualPool);
  701. }
  702. if ($pool === []) {
  703. return json([
  704. 'total' => 0,
  705. 'rows' => [],
  706. ]);
  707. }
  708. }
  709. $filtered = $this->filterProcuremenIndexPool(
  710. $pool,
  711. $monthStart,
  712. $monthEnd,
  713. $applyMonthRange,
  714. $search,
  715. $filterArr,
  716. $opArr,
  717. $listTimePrimary
  718. );
  719. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  720. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  721. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  722. }
  723. $sortField = 'ID';
  724. if (is_string($sort) && $sort !== '') {
  725. $parts = explode(',', $sort);
  726. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  727. if ($sortField === '') {
  728. $sortField = 'ID';
  729. }
  730. }
  731. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  732. $nFiltered = count($filtered);
  733. if ($nFiltered > 1) {
  734. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  735. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  736. $ta = $this->procuremenRowListSortTime($a, $sortField);
  737. $tb = $this->procuremenRowListSortTime($b, $sortField);
  738. if ($ta === $tb) {
  739. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  740. }
  741. if ($ta === '') {
  742. return 1;
  743. }
  744. if ($tb === '') {
  745. return -1;
  746. }
  747. return strcmp($ta, $tb) * $ord;
  748. });
  749. } elseif ($sortField === 'ID') {
  750. $sortKeys = [];
  751. foreach ($filtered as $i => $row) {
  752. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  753. }
  754. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  755. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  756. } elseif ($sortField === 'CCYDH') {
  757. usort($filtered, function ($a, $b) use ($ord) {
  758. $sa = trim((string)($a['CCYDH'] ?? ''));
  759. $sb = trim((string)($b['CCYDH'] ?? ''));
  760. if ($sa === $sb) {
  761. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  762. }
  763. if ($sa === '') {
  764. return 1;
  765. }
  766. if ($sb === '') {
  767. return -1;
  768. }
  769. return strcmp($sa, $sb) * $ord;
  770. });
  771. } else {
  772. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  773. $va = $a[$sortField] ?? null;
  774. $vb = $b[$sortField] ?? null;
  775. $sa = (string)$va;
  776. $sb = (string)$vb;
  777. if ($sa === $sb) {
  778. return 0;
  779. }
  780. return strcmp($sa, $sb) * $ord;
  781. });
  782. }
  783. }
  784. $offset = max(0, (int)$offset);
  785. $limit = max(1, (int)$limit);
  786. $rows = array_slice($filtered, $offset, $limit);
  787. foreach ($rows as &$rw) {
  788. if (!is_array($rw)) {
  789. continue;
  790. }
  791. $rid = (int)($rw['ID'] ?? 0);
  792. $rw['_iss_out'] = ($wffTab !== 'pick');
  793. }
  794. unset($rw);
  795. if ($wffTab === 'confirm' && count($rows) > 0) {
  796. $idList = [];
  797. foreach ($rows as $rw) {
  798. if (!is_array($rw)) {
  799. continue;
  800. }
  801. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  802. foreach ($rw['_order_merge_rows'] as $mr) {
  803. $mid = (int)($mr['ID'] ?? 0);
  804. if ($this->isValidScydgyRowId($mid)) {
  805. $idList[$mid] = true;
  806. }
  807. }
  808. }
  809. $id = (int)($rw['ID'] ?? 0);
  810. if ($this->isValidScydgyRowId($id)) {
  811. $idList[$id] = true;
  812. }
  813. }
  814. $sumMap = $this->OrderDetailSummary(array_keys($idList));
  815. foreach ($rows as &$rw) {
  816. if (!is_array($rw)) {
  817. continue;
  818. }
  819. $mergeIds = [];
  820. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  821. foreach ($rw['_order_merge_rows'] as $mr) {
  822. $mid = (int)($mr['ID'] ?? 0);
  823. if ($this->isValidScydgyRowId($mid)) {
  824. $mergeIds[$mid] = true;
  825. }
  826. }
  827. }
  828. $rid = (int)($rw['ID'] ?? 0);
  829. if ($this->isValidScydgyRowId($rid)) {
  830. $mergeIds[$rid] = true;
  831. }
  832. $cnt = 0;
  833. $amt = 0;
  834. $deliv = 0;
  835. foreach (array_keys($mergeIds) as $mid) {
  836. $s = isset($sumMap[$mid]) ? $sumMap[$mid] : ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  837. $cnt += (int)($s['cnt'] ?? 0);
  838. $amt += (int)($s['amt'] ?? 0);
  839. $deliv += (int)($s['deliv'] ?? 0);
  840. }
  841. $rw['po_detail_count'] = $cnt;
  842. $rw['po_amount_fill_cnt'] = $amt;
  843. $rw['po_delivery_fill_cnt'] = $deliv;
  844. }
  845. unset($rw);
  846. }
  847. if ($wffTab === 'confirm' && count($rows) > 0) {
  848. $idList = [];
  849. foreach ($rows as $rw) {
  850. if (!is_array($rw)) {
  851. continue;
  852. }
  853. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  854. foreach ($rw['_order_merge_rows'] as $mr) {
  855. $mid = (int)($mr['ID'] ?? 0);
  856. if ($this->isValidScydgyRowId($mid)) {
  857. $idList[$mid] = true;
  858. }
  859. }
  860. }
  861. $id = (int)($rw['ID'] ?? 0);
  862. if ($this->isValidScydgyRowId($id)) {
  863. $idList[$id] = true;
  864. }
  865. }
  866. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  867. foreach ($rows as &$rw) {
  868. if (!is_array($rw)) {
  869. continue;
  870. }
  871. $mergeIds = [];
  872. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  873. foreach ($rw['_order_merge_rows'] as $mr) {
  874. $mid = (int)($mr['ID'] ?? 0);
  875. if ($this->isValidScydgyRowId($mid)) {
  876. $mergeIds[$mid] = true;
  877. }
  878. }
  879. }
  880. $rid = (int)($rw['ID'] ?? 0);
  881. if ($this->isValidScydgyRowId($rid)) {
  882. $mergeIds[$rid] = true;
  883. }
  884. $buckets = [];
  885. foreach (array_keys($mergeIds) as $mid) {
  886. if (isset($quoteBucket[$mid])) {
  887. $buckets[] = $quoteBucket[$mid];
  888. }
  889. }
  890. $rw['picked_supplier_name'] = $buckets !== []
  891. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  892. : '';
  893. }
  894. unset($rw);
  895. }
  896. if ($wffTab === 'audit' && count($rows) > 0) {
  897. $idList = [];
  898. foreach ($rows as $rw) {
  899. if (!is_array($rw)) {
  900. continue;
  901. }
  902. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  903. foreach ($rw['_order_merge_rows'] as $mr) {
  904. $mid = (int)($mr['ID'] ?? 0);
  905. if ($this->isValidScydgyRowId($mid)) {
  906. $idList[$mid] = true;
  907. }
  908. }
  909. }
  910. $id = (int)($rw['ID'] ?? 0);
  911. if ($this->isValidScydgyRowId($id)) {
  912. $idList[$id] = true;
  913. }
  914. }
  915. $notifyMap = $this->loadNotifySupplierNamesByScydgyIds(array_keys($idList));
  916. foreach ($rows as &$rw) {
  917. if (!is_array($rw)) {
  918. continue;
  919. }
  920. $mergeIds = [];
  921. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  922. foreach ($rw['_order_merge_rows'] as $mr) {
  923. $mid = (int)($mr['ID'] ?? 0);
  924. if ($this->isValidScydgyRowId($mid)) {
  925. $mergeIds[$mid] = true;
  926. }
  927. }
  928. }
  929. $rid = (int)($rw['ID'] ?? 0);
  930. if ($this->isValidScydgyRowId($rid)) {
  931. $mergeIds[$rid] = true;
  932. }
  933. $names = [];
  934. foreach (array_keys($mergeIds) as $mid) {
  935. foreach ($notifyMap[$mid] ?? [] as $cn) {
  936. if ($cn !== '' && !in_array($cn, $names, true)) {
  937. $names[] = $cn;
  938. }
  939. }
  940. }
  941. sort($names, SORT_STRING);
  942. $rw['notify_supplier_text'] = $this->formatNotifySupplierDisplay($names);
  943. }
  944. unset($rw);
  945. }
  946. if ($wffTab === 'all' && count($rows) > 0) {
  947. $this->mergePurchaseOrder($rows);
  948. }
  949. if ($wffTab === 'pick' && count($rows) > 0) {
  950. $this->mergePurchaseOrder($rows);
  951. }
  952. foreach ($rows as &$rwClean) {
  953. if (is_array($rwClean)) {
  954. unset($rwClean['_order_merge_rows']);
  955. if (array_key_exists('NGZL', $rwClean)) {
  956. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  957. }
  958. }
  959. }
  960. unset($rwClean);
  961. return json([
  962. 'total' => count($filtered),
  963. 'rows' => $rows,
  964. ]);
  965. } catch (\Throwable $e) {
  966. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  967. return json([
  968. 'total' => 0,
  969. 'rows' => [],
  970. ]);
  971. }
  972. }
  973. /**
  974. * 已协助/不可再审核判定(与「未发」列表隐藏规则一致,避免仅保存数量却被当成已下发)
  975. * - purchase_order.status 为 0 或 1:已审核下发或已完结
  976. * - 或存在 purchase_order_detail:已向供应商下过明细
  977. * 仅写入 purchase_order 且 status 为空:视为未发(如只填本次数量、最高限价)
  978. *
  979. * @return array<int, true> scydgy_id => true
  980. */
  981. protected function loadIssuedScydgySet()
  982. {
  983. $issuedSet = [];
  984. try {
  985. $poList = Db::table('purchase_order')
  986. ->whereIn('status', array_merge(
  987. ProcuremenStatus::poInProgressValues(),
  988. ProcuremenStatus::poCompletedValues()
  989. ))
  990. ->column('scydgy_id');
  991. if (is_array($poList)) {
  992. foreach ($poList as $ids) {
  993. $n = (int)$ids;
  994. if ($n > 0) {
  995. $issuedSet[$n] = true;
  996. }
  997. }
  998. }
  999. } catch (\Throwable $e) {
  1000. }
  1001. try {
  1002. $detList = Db::table('purchase_order_detail');
  1003. $this->applyActivePurchaseOrderDetailWhere($detList);
  1004. $detList = $detList->group('scydgy_id')->column('scydgy_id');
  1005. if (is_array($detList)) {
  1006. foreach ($detList as $ids) {
  1007. $n = (int)$ids;
  1008. if ($n > 0) {
  1009. $issuedSet[$n] = true;
  1010. }
  1011. }
  1012. }
  1013. } catch (\Throwable $e) {
  1014. }
  1015. return $issuedSet;
  1016. }
  1017. /**
  1018. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1019. *
  1020. * @return array<int, true>
  1021. */
  1022. protected function loadPickHiddenScydgySet(): array
  1023. {
  1024. if ($this->pickHiddenScydgySetCache !== null) {
  1025. return $this->pickHiddenScydgySetCache;
  1026. }
  1027. $hideSet = [];
  1028. try {
  1029. $poIds = Db::table('purchase_order')
  1030. ->where(function ($q) {
  1031. $q->whereIn('wflow_status', array_merge(
  1032. ProcuremenStatus::wflowPendingConfirmValues(),
  1033. ProcuremenStatus::wflowPendingApprovalValues()
  1034. ))
  1035. ->whereOr(function ($q1) {
  1036. $q1->whereIn('status', ProcuremenStatus::poCompletedValues());
  1037. })
  1038. ->whereOr(function ($q2) {
  1039. $q2->whereNotNull('pick_time')
  1040. ->where('pick_time', '<>', '')
  1041. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1042. })
  1043. ->whereOr(function ($q3) {
  1044. $q3->whereNotNull('mod_rq')
  1045. ->where('mod_rq', '<>', '')
  1046. ->where('mod_rq', 'not like', '0000-00-00%');
  1047. });
  1048. })
  1049. ->column('scydgy_id');
  1050. if (is_array($poIds)) {
  1051. foreach ($poIds as $pid) {
  1052. $k = (int)$pid;
  1053. if ($k !== 0) {
  1054. $hideSet[$k] = true;
  1055. }
  1056. }
  1057. }
  1058. } catch (\Throwable $e) {
  1059. }
  1060. try {
  1061. $detIdsQuery = Db::table('purchase_order_detail');
  1062. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1063. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1064. if (is_array($detIds)) {
  1065. foreach ($detIds as $pid) {
  1066. $k = (int)$pid;
  1067. if ($this->isValidScydgyRowId($k)) {
  1068. $hideSet[$k] = true;
  1069. }
  1070. }
  1071. }
  1072. } catch (\Throwable $e) {
  1073. }
  1074. $this->pickHiddenScydgySetCache = $hideSet;
  1075. return $hideSet;
  1076. }
  1077. /**
  1078. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1079. *
  1080. * @return array<int, array<string, mixed>>
  1081. */
  1082. protected function loadPickManualOrderRows(): array
  1083. {
  1084. try {
  1085. $dbRows = Db::table('purchase_order')
  1086. ->where('scydgy_id', '<', 0)
  1087. ->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%\')')
  1088. ->order('scydgy_id', 'asc')
  1089. ->select();
  1090. } catch (\Throwable $e) {
  1091. try {
  1092. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1093. } catch (\Throwable $e2) {
  1094. return [];
  1095. }
  1096. }
  1097. if (!is_array($dbRows) || $dbRows === []) {
  1098. return [];
  1099. }
  1100. $detailSidSet = [];
  1101. try {
  1102. $negIds = [];
  1103. foreach ($dbRows as $dbRow) {
  1104. if (!is_array($dbRow)) {
  1105. continue;
  1106. }
  1107. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1108. if ($sid < 0) {
  1109. $negIds[$sid] = true;
  1110. }
  1111. }
  1112. if ($negIds !== []) {
  1113. $detQuery = Db::table('purchase_order_detail')
  1114. ->where('scydgy_id', 'in', array_keys($negIds));
  1115. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1116. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1117. if (is_array($detRows)) {
  1118. foreach ($detRows as $did) {
  1119. $detailSidSet[(int)$did] = true;
  1120. }
  1121. }
  1122. }
  1123. } catch (\Throwable $e) {
  1124. }
  1125. $pool = [];
  1126. foreach ($dbRows as $dbRow) {
  1127. if (!is_array($dbRow)) {
  1128. continue;
  1129. }
  1130. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1131. if ($sid >= 0) {
  1132. continue;
  1133. }
  1134. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1135. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1136. continue;
  1137. }
  1138. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1139. if ($st === ProcuremenStatus::PO_COMPLETED || $st === ProcuremenStatus::PO_IN_PROGRESS) {
  1140. continue;
  1141. }
  1142. if (isset($detailSidSet[$sid])) {
  1143. continue;
  1144. }
  1145. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1146. $r['_is_manual'] = 1;
  1147. $pool[] = $r;
  1148. }
  1149. return $pool;
  1150. }
  1151. /**
  1152. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1153. */
  1154. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1155. {
  1156. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1157. foreach ($keys as $k) {
  1158. $t = trim((string)($row[$k] ?? ''));
  1159. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1160. return $t;
  1161. }
  1162. }
  1163. return '';
  1164. }
  1165. /**
  1166. * 分配手工新增工序行 ID(负数递减)
  1167. */
  1168. protected function allocateManualScydgyId(): int
  1169. {
  1170. try {
  1171. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1172. $min = (int)$min;
  1173. return $min < 0 ? $min - 1 : -1;
  1174. } catch (\Throwable $e) {
  1175. return -1;
  1176. }
  1177. }
  1178. /**
  1179. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1180. */
  1181. protected function allocateManualOrderCcydh(): string
  1182. {
  1183. $prefix = 'YW' . date('Ymd');
  1184. $maxSeq = 0;
  1185. try {
  1186. $rows = Db::table('purchase_order')
  1187. ->where('CCYDH', 'like', $prefix . '%')
  1188. ->column('CCYDH');
  1189. if (is_array($rows)) {
  1190. foreach ($rows as $ccydh) {
  1191. $ccydh = trim((string)$ccydh);
  1192. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1193. $maxSeq = max($maxSeq, (int)$m[1]);
  1194. }
  1195. }
  1196. }
  1197. } catch (\Throwable $e) {
  1198. }
  1199. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1200. }
  1201. /**
  1202. * purchase_order.mod_rq 是否有有效软删除时间
  1203. */
  1204. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1205. {
  1206. $t = trim((string)$modRq);
  1207. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1208. }
  1209. /**
  1210. * 列表行 → purchase_order 写入字段
  1211. *
  1212. * @return array<string, mixed>
  1213. */
  1214. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1215. {
  1216. return [
  1217. 'scydgy_id' => $scydgyId,
  1218. 'CCYDH' => $row['CCYDH'] ?? null,
  1219. 'CYJMC' => $row['CYJMC'] ?? null,
  1220. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1221. 'CDXMC' => $row['CDXMC'] ?? null,
  1222. 'CGYBH' => $row['CGYBH'] ?? null,
  1223. 'CGYMC' => $row['CGYMC'] ?? null,
  1224. 'CDW' => $row['CDW'] ?? null,
  1225. 'NGZL' => $row['NGZL'] ?? null,
  1226. 'CDF' => $row['CDF'] ?? null,
  1227. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1228. 'MBZ' => $row['MBZ'] ?? null,
  1229. 'bwjg' => $row['bwjg'] ?? null,
  1230. 'iStatus' => $row['iStatus'] ?? null,
  1231. 'dStamp' => $row['dStamp'] ?? null,
  1232. 'dputrecord' => $row['dputrecord'] ?? null,
  1233. 'cywyxm' => $row['cywyxm'] ?? null,
  1234. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1235. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1236. ];
  1237. }
  1238. /**
  1239. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1240. */
  1241. protected function softDeleteProcuremenPickRow(array $row): void
  1242. {
  1243. $sid = $this->extractScydgyRowId($row);
  1244. if (!$this->isValidScydgyRowId($sid)) {
  1245. throw new \InvalidArgumentException('无效的行主键');
  1246. }
  1247. $hideSet = $this->loadPickHiddenScydgySet();
  1248. if ($sid > 0 && isset($hideSet[$sid])) {
  1249. throw new \InvalidArgumentException('订单号「' . trim((string)($row['CCYDH'] ?? '')) . '」已下发或已进入后续流程,无法删除');
  1250. }
  1251. if ($sid < 0) {
  1252. try {
  1253. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1254. if (is_array($po)) {
  1255. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1256. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1257. }
  1258. if ($this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1259. return;
  1260. }
  1261. }
  1262. } catch (\InvalidArgumentException $e) {
  1263. throw $e;
  1264. } catch (\Throwable $e) {
  1265. }
  1266. }
  1267. $now = date('Y-m-d H:i:s');
  1268. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1269. if (is_array($exists)) {
  1270. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1271. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1272. } else {
  1273. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1274. $data['mod_rq'] = $now;
  1275. $data['createtime'] = $now;
  1276. Db::table('purchase_order')->insert($data);
  1277. $poIdLog = (int)Db::getLastInsID();
  1278. }
  1279. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1280. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1281. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1282. if ($gymcLog !== '') {
  1283. $logTail .= ' / ' . $gymcLog;
  1284. }
  1285. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1286. }
  1287. /**
  1288. * 手工新增协助工序(写入 purchase_order)
  1289. *
  1290. * @param array<string, mixed> $params
  1291. * @return int scydgy_id
  1292. */
  1293. protected function saveManualPickOrder(array $params): int
  1294. {
  1295. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1296. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1297. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1298. if ($ccydh === '') {
  1299. $ccydh = $this->allocateManualOrderCcydh();
  1300. }
  1301. $now = date('Y-m-d H:i:s');
  1302. $sid = $this->allocateManualScydgyId();
  1303. $data = [
  1304. 'scydgy_id' => $sid,
  1305. 'CCYDH' => $ccydh,
  1306. 'CYJMC' => $cyjmc,
  1307. 'CGYMC' => $cgymc,
  1308. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1309. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1310. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1311. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1312. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1313. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1314. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1315. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1316. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1317. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1318. 'createtime' => $now,
  1319. 'dStamp' => $now,
  1320. 'dputrecord' => $now,
  1321. ];
  1322. Db::table('purchase_order')->insert($data);
  1323. $poId = (int)Db::getLastInsID();
  1324. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1325. return $sid;
  1326. }
  1327. protected function formatProcuremenRowLabel(array $row): string
  1328. {
  1329. $dh = trim((string)($row['CCYDH'] ?? ''));
  1330. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1331. if ($dh !== '' && $gymc !== '') {
  1332. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1333. }
  1334. if ($dh !== '') {
  1335. return '订单「' . $dh . '」';
  1336. }
  1337. if ($gymc !== '') {
  1338. return '工序「' . $gymc . '」';
  1339. }
  1340. $id = $this->extractScydgyRowId($row);
  1341. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1342. }
  1343. /**
  1344. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1345. */
  1346. protected function extractScydgyRowId(array $row): int
  1347. {
  1348. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1349. }
  1350. protected function isValidScydgyRowId(int $id): bool
  1351. {
  1352. return $id !== 0;
  1353. }
  1354. protected function isManualScydgyRowId(int $id): bool
  1355. {
  1356. return $id < 0;
  1357. }
  1358. /**
  1359. * 采购确认已选定供应商:明细 purchase_order_detail.status = 1 的工序行 scydgy_id 集合
  1360. *
  1361. * @return array<int, true>
  1362. */
  1363. protected function loadScydgyIdsWithPickedSupplierDetail(): array
  1364. {
  1365. $set = [];
  1366. try {
  1367. $rows = Db::table('purchase_order_detail')->whereIn('status', ProcuremenStatus::podPickedValues())->field('scydgy_id')->select();
  1368. } catch (\Throwable $e) {
  1369. $rows = [];
  1370. }
  1371. if (!is_array($rows)) {
  1372. return $set;
  1373. }
  1374. foreach ($rows as $r) {
  1375. if (!is_array($r)) {
  1376. continue;
  1377. }
  1378. $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
  1379. if ($sid > 0) {
  1380. $set[$sid] = true;
  1381. }
  1382. }
  1383. return $set;
  1384. }
  1385. /**
  1386. * 每个工序行对应已选中供应商名称(取 status=1 的首条明细 company_name)
  1387. *
  1388. * @param int[] $scydgyIds
  1389. * @return array<int, string> scydgy_id => company_name
  1390. */
  1391. protected function loadPickedSupplierCompanyByScydgyIds(array $scydgyIds): array
  1392. {
  1393. $out = [];
  1394. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1395. if ($scydgyIds === []) {
  1396. return $out;
  1397. }
  1398. try {
  1399. $rows = Db::table('purchase_order_detail')
  1400. ->where('scydgy_id', 'in', $scydgyIds)
  1401. ->whereIn('status', ProcuremenStatus::podPickedValues())
  1402. ->field('scydgy_id,company_name')
  1403. ->order('id', 'asc')
  1404. ->select();
  1405. } catch (\Throwable $e) {
  1406. try {
  1407. $rows = Db::table('purchase_order_detail')
  1408. ->where('scydgy_id', 'in', $scydgyIds)
  1409. ->whereIn('status', ProcuremenStatus::podPickedValues())
  1410. ->field('scydgy_id,company_name')
  1411. ->order('ID', 'asc')
  1412. ->select();
  1413. } catch (\Throwable $e2) {
  1414. $rows = [];
  1415. }
  1416. }
  1417. if (!is_array($rows)) {
  1418. return $out;
  1419. }
  1420. foreach ($rows as $r) {
  1421. if (!is_array($r)) {
  1422. continue;
  1423. }
  1424. $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
  1425. if (!$this->isValidScydgyRowId($sid) || isset($out[$sid])) {
  1426. continue;
  1427. }
  1428. $name = trim((string)($r['company_name'] ?? ''));
  1429. $out[$sid] = $name;
  1430. }
  1431. return $out;
  1432. }
  1433. /**
  1434. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1435. *
  1436. * @param int[] $scydgyIds
  1437. * @return array<int, string[]>
  1438. */
  1439. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1440. {
  1441. $out = [];
  1442. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1443. if ($scydgyIds === []) {
  1444. return $out;
  1445. }
  1446. try {
  1447. $rows = Db::table('purchase_order_detail')
  1448. ->where('scydgy_id', 'in', $scydgyIds)
  1449. ->field('scydgy_id,company_name')
  1450. ->order('company_name', 'asc')
  1451. ->select();
  1452. } catch (\Throwable $e) {
  1453. $rows = [];
  1454. }
  1455. if (!is_array($rows)) {
  1456. return $out;
  1457. }
  1458. foreach ($rows as $r) {
  1459. if (!is_array($r)) {
  1460. continue;
  1461. }
  1462. $sid = (int)($r['scydgy_id'] ?? 0);
  1463. $cn = trim((string)($r['company_name'] ?? ''));
  1464. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1465. continue;
  1466. }
  1467. if (!isset($out[$sid])) {
  1468. $out[$sid] = [];
  1469. }
  1470. if (!in_array($cn, $out[$sid], true)) {
  1471. $out[$sid][] = $cn;
  1472. }
  1473. }
  1474. return $out;
  1475. }
  1476. /**
  1477. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1478. *
  1479. * @param string[] $names
  1480. */
  1481. protected function formatNotifySupplierDisplay(array $names): string
  1482. {
  1483. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1484. return trim((string)$n);
  1485. }, $names))));
  1486. if ($names === []) {
  1487. return '';
  1488. }
  1489. sort($names, SORT_STRING);
  1490. return implode('、', $names);
  1491. }
  1492. /**
  1493. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1494. *
  1495. * @param int[] $scydgyIds
  1496. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1497. */
  1498. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1499. {
  1500. $out = [];
  1501. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1502. if ($scydgyIds === []) {
  1503. return $out;
  1504. }
  1505. try {
  1506. $rows = Db::table('purchase_order_detail')
  1507. ->where('scydgy_id', 'in', $scydgyIds)
  1508. ->field('scydgy_id,company_name,amount')
  1509. ->select();
  1510. } catch (\Throwable $e) {
  1511. $rows = [];
  1512. }
  1513. if (!is_array($rows)) {
  1514. return $out;
  1515. }
  1516. foreach ($rows as $r) {
  1517. if (!is_array($r)) {
  1518. continue;
  1519. }
  1520. $sid = (int)($r['scydgy_id'] ?? 0);
  1521. $cn = trim((string)($r['company_name'] ?? ''));
  1522. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1523. continue;
  1524. }
  1525. if (!isset($out[$sid])) {
  1526. $out[$sid] = ['all' => [], 'quoted' => []];
  1527. }
  1528. $out[$sid]['all'][$cn] = true;
  1529. $am = trim((string)($r['amount'] ?? ''));
  1530. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1531. $out[$sid]['quoted'][$cn] = true;
  1532. }
  1533. }
  1534. return $out;
  1535. }
  1536. /**
  1537. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1538. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1539. */
  1540. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1541. {
  1542. $merged = ['all' => [], 'quoted' => []];
  1543. foreach ($buckets as $b) {
  1544. if (!is_array($b)) {
  1545. continue;
  1546. }
  1547. foreach ($b['all'] ?? [] as $cn => $_) {
  1548. $merged['all'][$cn] = true;
  1549. }
  1550. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1551. $merged['quoted'][$cn] = true;
  1552. }
  1553. }
  1554. return $merged;
  1555. }
  1556. /**
  1557. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1558. */
  1559. protected function formatQuotedSupplierLines(array $bucket): string
  1560. {
  1561. $all = array_keys($bucket['all'] ?? []);
  1562. if ($all === []) {
  1563. return '';
  1564. }
  1565. sort($all, SORT_STRING);
  1566. $lines = [];
  1567. foreach ($all as $cn) {
  1568. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1569. $lines[] = $cn . '(' . $status . ')';
  1570. }
  1571. return implode("\n", $lines);
  1572. }
  1573. /**
  1574. * @param int[] $scydgyIds
  1575. * @return array<int, string>
  1576. */
  1577. protected function loadQuotedSupplierSummaryByScydgyIds(array $scydgyIds): array
  1578. {
  1579. $out = [];
  1580. foreach ($this->loadQuotedSupplierBucketByScydgyIds($scydgyIds) as $sid => $bucket) {
  1581. $text = $this->formatQuotedSupplierLines($bucket);
  1582. if ($text !== '') {
  1583. $out[$sid] = $text;
  1584. }
  1585. }
  1586. return $out;
  1587. }
  1588. /**
  1589. * 审核弹窗:按供应商汇总报价明细
  1590. *
  1591. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1592. * @return array<int, array<string, mixed>>
  1593. */
  1594. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  1595. {
  1596. $sids = [];
  1597. foreach ($bundle['pos'] ?? [] as $po) {
  1598. if (!is_array($po)) {
  1599. continue;
  1600. }
  1601. $sid = (int)($po['scydgy_id'] ?? 0);
  1602. if ($this->isValidScydgyRowId($sid)) {
  1603. $sids[$sid] = true;
  1604. }
  1605. }
  1606. if ($sids === []) {
  1607. return [];
  1608. }
  1609. $gymcMap = [];
  1610. $qtyBySid = [];
  1611. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1612. if (!is_array($mr)) {
  1613. continue;
  1614. }
  1615. $gid = $this->extractScydgyRowId($mr);
  1616. if ($this->isValidScydgyRowId($gid)) {
  1617. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1618. $qty = trim((string)($mr['This_quantity'] ?? ''));
  1619. if ($qty === '') {
  1620. $qty = trim((string)($mr['NGZL'] ?? ''));
  1621. }
  1622. $qtyBySid[$gid] = $qty;
  1623. }
  1624. }
  1625. foreach ($bundle['pos'] ?? [] as $po) {
  1626. if (!is_array($po)) {
  1627. continue;
  1628. }
  1629. $gid = (int)($po['scydgy_id'] ?? 0);
  1630. if ($this->isValidScydgyRowId($gid)) {
  1631. $nm = trim((string)($po['CGYMC'] ?? ''));
  1632. if ($nm !== '') {
  1633. $gymcMap[$gid] = $nm;
  1634. }
  1635. }
  1636. }
  1637. try {
  1638. $detailsQuery = Db::table('purchase_order_detail')
  1639. ->where('scydgy_id', 'in', array_keys($sids));
  1640. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1641. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  1642. } catch (\Throwable $e) {
  1643. try {
  1644. $detailsQuery = Db::table('purchase_order_detail')
  1645. ->where('scydgy_id', 'in', array_keys($sids));
  1646. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1647. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  1648. } catch (\Throwable $e2) {
  1649. $details = [];
  1650. }
  1651. }
  1652. if (!is_array($details)) {
  1653. $details = [];
  1654. }
  1655. $byCompany = [];
  1656. foreach ($details as $d) {
  1657. if (!is_array($d)) {
  1658. continue;
  1659. }
  1660. $cn = trim((string)($d['company_name'] ?? ''));
  1661. if ($cn === '') {
  1662. continue;
  1663. }
  1664. if (!isset($byCompany[$cn])) {
  1665. $ph = trim((string)($d['phone'] ?? ''));
  1666. $username = trim((string)($d['username'] ?? ''));
  1667. if ($username === '') {
  1668. $username = $this->resolveCustomerContactName($ph, $cn);
  1669. }
  1670. $byCompany[$cn] = [
  1671. 'name' => $cn,
  1672. 'email' => trim((string)($d['email'] ?? '')),
  1673. 'phone' => $ph,
  1674. 'username' => $username,
  1675. 'has_quote' => false,
  1676. 'lines' => [],
  1677. ];
  1678. }
  1679. $sid = (int)($d['scydgy_id'] ?? 0);
  1680. $am = trim((string)($d['amount'] ?? ''));
  1681. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  1682. if ($gymc === '') {
  1683. $gymc = '工序';
  1684. }
  1685. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  1686. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  1687. if ($deliveryShow === '' && $deliveryRaw !== '') {
  1688. $deliveryShow = $deliveryRaw;
  1689. }
  1690. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  1691. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  1692. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  1693. $subtotal = null;
  1694. if ($amountNum !== null) {
  1695. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  1696. }
  1697. $unitPriceText = $amountFilled
  1698. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  1699. : '未填写';
  1700. $byCompany[$cn]['lines'][] = [
  1701. 'cgymc' => $gymc,
  1702. 'amount' => $am,
  1703. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  1704. 'amount_filled' => $amountFilled,
  1705. 'unit_price_text' => $unitPriceText,
  1706. 'delivery' => $deliveryRaw,
  1707. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  1708. 'delivery_filled' => $deliveryFilled,
  1709. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  1710. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  1711. 'subtotal_num' => $subtotal,
  1712. 'status_name' => trim((string)($d['status_name'] ?? '')),
  1713. 'is_quoted' => $amountFilled,
  1714. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  1715. ];
  1716. }
  1717. foreach ($byCompany as $cn => $g) {
  1718. $total = count($g['lines']);
  1719. $quoted = 0;
  1720. $groupTotal = 0.0;
  1721. $groupHasTotal = false;
  1722. foreach ($g['lines'] as $ln) {
  1723. $am = trim((string)($ln['amount'] ?? ''));
  1724. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1725. $quoted++;
  1726. }
  1727. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  1728. $groupTotal += (float)$ln['subtotal_num'];
  1729. $groupHasTotal = true;
  1730. }
  1731. }
  1732. $byCompany[$cn]['has_quote'] = $total > 0 && $quoted === $total;
  1733. $byCompany[$cn]['line_count'] = $total;
  1734. $byCompany[$cn]['has_total'] = $total > 0;
  1735. $byCompany[$cn]['total_text'] = $groupHasTotal ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  1736. $byCompany[$cn]['display_rowspan'] = $total + ($total > 0 ? 1 : 0);
  1737. }
  1738. return array_values($byCompany);
  1739. }
  1740. /**
  1741. * 确认供应商弹窗:通知对象(不含报价,仅工序与联系方式)
  1742. *
  1743. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1744. * @return array<int, array<string, mixed>>
  1745. */
  1746. protected function loadAuditSupplierNotifyGroups(array $bundle): array
  1747. {
  1748. $groups = $this->loadAuditSupplierQuoteGroups($bundle);
  1749. $out = [];
  1750. foreach ($groups as $g) {
  1751. if (!is_array($g)) {
  1752. continue;
  1753. }
  1754. $processNames = [];
  1755. foreach ($g['lines'] ?? [] as $ln) {
  1756. if (!is_array($ln)) {
  1757. continue;
  1758. }
  1759. $n = trim((string)($ln['cgymc'] ?? ''));
  1760. if ($n !== '' && !in_array($n, $processNames, true)) {
  1761. $processNames[] = $n;
  1762. }
  1763. }
  1764. $out[] = [
  1765. 'name' => trim((string)($g['name'] ?? '')),
  1766. 'email' => trim((string)($g['email'] ?? '')),
  1767. 'phone' => trim((string)($g['phone'] ?? '')),
  1768. 'username' => trim((string)($g['username'] ?? '')),
  1769. 'process_names' => $processNames,
  1770. 'process_text' => implode('、', $processNames),
  1771. ];
  1772. }
  1773. return $out;
  1774. }
  1775. /**
  1776. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  1777. *
  1778. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1779. * @return array<int, array<string, mixed>>
  1780. */
  1781. protected function loadConfirmSupplierPickGroups(array $bundle): array
  1782. {
  1783. $sids = [];
  1784. $poIdMap = [];
  1785. foreach ($bundle['pos'] ?? [] as $po) {
  1786. if (!is_array($po)) {
  1787. continue;
  1788. }
  1789. $sid = (int)($po['scydgy_id'] ?? 0);
  1790. if ($this->isValidScydgyRowId($sid)) {
  1791. $sids[$sid] = true;
  1792. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  1793. }
  1794. }
  1795. if ($sids === []) {
  1796. return [];
  1797. }
  1798. $gymcMap = [];
  1799. $qtyBySid = [];
  1800. $orderedSids = [];
  1801. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1802. if (!is_array($mr)) {
  1803. continue;
  1804. }
  1805. $gid = $this->extractScydgyRowId($mr);
  1806. if ($this->isValidScydgyRowId($gid)) {
  1807. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1808. $orderedSids[] = $gid;
  1809. $qty = trim((string)($mr['This_quantity'] ?? ''));
  1810. if ($qty === '') {
  1811. $qty = trim((string)($mr['NGZL'] ?? ''));
  1812. }
  1813. $qtyBySid[$gid] = $qty;
  1814. }
  1815. }
  1816. foreach ($bundle['pos'] ?? [] as $po) {
  1817. if (!is_array($po)) {
  1818. continue;
  1819. }
  1820. $gid = (int)($po['scydgy_id'] ?? 0);
  1821. if ($this->isValidScydgyRowId($gid)) {
  1822. $nm = trim((string)($po['CGYMC'] ?? ''));
  1823. if ($nm !== '') {
  1824. $gymcMap[$gid] = $nm;
  1825. }
  1826. }
  1827. }
  1828. try {
  1829. $details = Db::table('purchase_order_detail')
  1830. ->where('scydgy_id', 'in', array_keys($sids))
  1831. ->order('company_name', 'asc')
  1832. ->order('id', 'asc')
  1833. ->select();
  1834. } catch (\Throwable $e) {
  1835. try {
  1836. $details = Db::table('purchase_order_detail')
  1837. ->where('scydgy_id', 'in', array_keys($sids))
  1838. ->order('company_name', 'asc')
  1839. ->order('ID', 'asc')
  1840. ->select();
  1841. } catch (\Throwable $e2) {
  1842. $details = [];
  1843. }
  1844. }
  1845. if (!is_array($details)) {
  1846. $details = [];
  1847. }
  1848. $byCompany = [];
  1849. foreach ($details as $d) {
  1850. if (!is_array($d)) {
  1851. continue;
  1852. }
  1853. $cn = trim((string)($d['company_name'] ?? ''));
  1854. if ($cn === '') {
  1855. continue;
  1856. }
  1857. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  1858. $sid = (int)($d['scydgy_id'] ?? 0);
  1859. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  1860. continue;
  1861. }
  1862. if (!isset($byCompany[$cn])) {
  1863. $ph = trim((string)($d['phone'] ?? ''));
  1864. $username = trim((string)($d['username'] ?? ''));
  1865. if ($username === '') {
  1866. $username = $this->resolveCustomerContactName($ph, $cn);
  1867. }
  1868. $byCompany[$cn] = [
  1869. 'name' => $cn,
  1870. 'email' => trim((string)($d['email'] ?? '')),
  1871. 'phone' => $ph,
  1872. 'username' => $username,
  1873. 'pick_lines' => [],
  1874. 'detail_picks' => [],
  1875. ];
  1876. }
  1877. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  1878. if ($gymc === '') {
  1879. $gymc = '工序';
  1880. }
  1881. $am = trim((string)($d['amount'] ?? ''));
  1882. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  1883. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  1884. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  1885. if ($deliveryShow === '' && $deliveryRaw !== '') {
  1886. $deliveryShow = $deliveryRaw;
  1887. }
  1888. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  1889. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  1890. $subtotal = null;
  1891. if ($amountNum !== null) {
  1892. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  1893. }
  1894. $unitPriceText = $amountFilled
  1895. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  1896. : '未填写';
  1897. $byCompany[$cn]['pick_lines'][$sid] = [
  1898. 'cgymc' => $gymc,
  1899. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  1900. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  1901. 'amount_filled' => $amountFilled,
  1902. 'delivery_filled' => $deliveryFilled,
  1903. 'unit_price_text' => $unitPriceText,
  1904. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  1905. 'subtotal_num' => $subtotal,
  1906. 'is_quoted' => $amountFilled,
  1907. ];
  1908. $byCompany[$cn]['detail_picks'][$sid] = [
  1909. 'scydgy_id' => $sid,
  1910. 'detail_id' => $detailId,
  1911. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  1912. 'cgymc' => $gymc,
  1913. ];
  1914. }
  1915. $out = [];
  1916. foreach ($byCompany as $g) {
  1917. $pickLinesMap = $g['pick_lines'] ?? [];
  1918. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  1919. continue;
  1920. }
  1921. $pickLines = [];
  1922. $usedLineSids = [];
  1923. foreach ($orderedSids as $sid) {
  1924. if (!isset($pickLinesMap[$sid])) {
  1925. continue;
  1926. }
  1927. $pickLines[] = $pickLinesMap[$sid];
  1928. $usedLineSids[$sid] = true;
  1929. }
  1930. foreach ($pickLinesMap as $sid => $ln) {
  1931. if (isset($usedLineSids[$sid])) {
  1932. continue;
  1933. }
  1934. $pickLines[] = $ln;
  1935. }
  1936. $groupTotal = 0.0;
  1937. $groupHasTotal = false;
  1938. foreach ($pickLines as $ln) {
  1939. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  1940. $groupTotal += (float)$ln['subtotal_num'];
  1941. $groupHasTotal = true;
  1942. }
  1943. }
  1944. $lineCount = count($pickLines);
  1945. $g['pick_lines'] = $pickLines;
  1946. $g['line_count'] = $lineCount;
  1947. $g['has_total'] = $lineCount > 0;
  1948. $g['total_text'] = $groupHasTotal ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  1949. $g['display_rowspan'] = $lineCount + ($lineCount > 0 ? 1 : 0);
  1950. $detailPicks = $g['detail_picks'] ?? [];
  1951. $g['detail_picks'] = array_values(is_array($detailPicks) ? $detailPicks : []);
  1952. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  1953. unset($g['detail_picks']);
  1954. $out[] = $g;
  1955. }
  1956. return $out;
  1957. }
  1958. /**
  1959. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  1960. * @return array<int, int[]> scydgy_id => detail_id[]
  1961. */
  1962. protected function mapDetailIdsByScydgyId(array $details): array
  1963. {
  1964. $out = [];
  1965. foreach ($details as $d) {
  1966. if (!is_array($d)) {
  1967. continue;
  1968. }
  1969. $sid = (int)($d['scydgy_id'] ?? 0);
  1970. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  1971. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  1972. continue;
  1973. }
  1974. if (!isset($out[$sid])) {
  1975. $out[$sid] = [];
  1976. }
  1977. $out[$sid][] = $pk;
  1978. }
  1979. foreach ($out as $sid => $ids) {
  1980. $out[$sid] = array_values(array_unique($ids));
  1981. }
  1982. return $out;
  1983. }
  1984. /**
  1985. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  1986. *
  1987. * @param array<string, mixed> $dbRow
  1988. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  1989. */
  1990. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  1991. {
  1992. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1993. $r = [
  1994. 'ID' => $sid,
  1995. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  1996. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  1997. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  1998. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  1999. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2000. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2001. 'CDW' => $dbRow['CDW'] ?? '',
  2002. 'NGZL' => $dbRow['NGZL'] ?? '',
  2003. 'CDF' => $dbRow['CDF'] ?? '',
  2004. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2005. 'MBZ' => $dbRow['MBZ'] ?? '',
  2006. 'bwjg' => $dbRow['bwjg'] ?? '',
  2007. 'iStatus' => $dbRow['iStatus'] ?? '',
  2008. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2009. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2010. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2011. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2012. 'dStamp' => $dbRow['dStamp'] ?? '',
  2013. 'pick_time' => $dbRow['pick_time'] ?? '',
  2014. ];
  2015. if ($sid > 0 && isset($dStampMap[$sid])) {
  2016. $t = trim((string)$dStampMap[$sid]);
  2017. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2018. $r['dStamp'] = $dStampMap[$sid];
  2019. }
  2020. }
  2021. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2022. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2023. $ct = $dbRow['createtime'];
  2024. if (is_numeric($ct) && (int)$ct > 946684800) {
  2025. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2026. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2027. $r['dStamp'] = trim($ct);
  2028. }
  2029. }
  2030. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2031. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2032. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2033. $fallback = trim((string)($r['dStamp'] ?? ''));
  2034. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2035. $r['dputrecord'] = $fallback;
  2036. }
  2037. }
  2038. if (array_key_exists('id', $dbRow)) {
  2039. $r['purchase_order_id'] = (int)$dbRow['id'];
  2040. }
  2041. if ($sid < 0) {
  2042. $r['_is_manual'] = 1;
  2043. }
  2044. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2045. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2046. if ($pickNm !== '') {
  2047. $r['pick_company_name'] = $pickNm;
  2048. $r['picked_supplier_name'] = $pickNm;
  2049. }
  2050. return $r;
  2051. }
  2052. /**
  2053. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2054. *
  2055. * @return array<int, array<string, mixed>>
  2056. */
  2057. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2058. {
  2059. $pool = [];
  2060. if (!is_array($dbRows) || $dbRows === []) {
  2061. return $pool;
  2062. }
  2063. $dStampMap = [];
  2064. $sidList = [];
  2065. foreach ($dbRows as $tmpRow) {
  2066. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2067. $sid = (int)$tmpRow['scydgy_id'];
  2068. if ($sid > 0) {
  2069. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2070. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2071. $sidList[$sid] = true;
  2072. }
  2073. }
  2074. }
  2075. }
  2076. if ($sidList !== []) {
  2077. try {
  2078. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2079. } catch (\Throwable $e) {
  2080. $dStampMap = [];
  2081. }
  2082. }
  2083. foreach ($dbRows as $dbRow) {
  2084. if (!is_array($dbRow)) {
  2085. continue;
  2086. }
  2087. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2088. }
  2089. return $pool;
  2090. }
  2091. /**
  2092. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2093. *
  2094. * @param int[] $scydgyIds
  2095. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2096. */
  2097. protected function OrderDetailSummary(array $scydgyIds)
  2098. {
  2099. $out = [];
  2100. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2101. if ($scydgyIds === []) {
  2102. return $out;
  2103. }
  2104. $list = [];
  2105. try {
  2106. $list = Db::table('purchase_order_detail')
  2107. ->where('scydgy_id', 'in', $scydgyIds)
  2108. ->field('id,scydgy_id,amount,delivery')
  2109. ->select();
  2110. } catch (\Throwable $e) {
  2111. $list = [];
  2112. }
  2113. if (!is_array($list)) {
  2114. return $out;
  2115. }
  2116. foreach ($list as $r) {
  2117. if (!is_array($r)) {
  2118. continue;
  2119. }
  2120. $ids = (int)($r['scydgy_id'] ?? 0);
  2121. if (!$this->isValidScydgyRowId($ids)) {
  2122. continue;
  2123. }
  2124. if (!isset($out[$ids])) {
  2125. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2126. }
  2127. $out[$ids]['cnt']++;
  2128. $am = $r['amount'] ?? null;
  2129. if ($am !== null && $am !== '') {
  2130. if (!(is_string($am) && trim($am) === '')) {
  2131. $out[$ids]['amt']++;
  2132. }
  2133. }
  2134. $dv = $r['delivery'] ?? null;
  2135. if ($dv !== null && trim((string)$dv) !== '') {
  2136. $out[$ids]['deliv']++;
  2137. }
  2138. }
  2139. return $out;
  2140. }
  2141. /**
  2142. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  2143. *
  2144. * @return array
  2145. */
  2146. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  2147. {
  2148. $strContains = function ($haystack, $needle) {
  2149. if ($needle === '') {
  2150. return false;
  2151. }
  2152. $haystack = (string)$haystack;
  2153. if (function_exists('mb_stripos')) {
  2154. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  2155. }
  2156. return stripos($haystack, $needle) !== false;
  2157. };
  2158. $stripAlias = function ($f) {
  2159. return preg_replace('/^[ab]\./i', '', (string)$f);
  2160. };
  2161. $searchColNames = [];
  2162. foreach (explode(',', $this->searchFields) as $colRaw) {
  2163. $c = $stripAlias(trim($colRaw));
  2164. if ($c !== '') {
  2165. $searchColNames[] = $c;
  2166. }
  2167. }
  2168. $filtered = [];
  2169. foreach ($pool as $r) {
  2170. if (!is_array($r)) {
  2171. continue;
  2172. }
  2173. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  2174. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  2175. if (!$isManual) {
  2176. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  2177. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  2178. continue;
  2179. }
  2180. if ($applyMonthRange) {
  2181. $mo = (int)$m[2];
  2182. if ($mo < 1 || $mo > 12) {
  2183. continue;
  2184. }
  2185. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2186. $rowMonthStart = $ymRow . '-01 00:00:00';
  2187. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2188. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2189. continue;
  2190. }
  2191. }
  2192. } elseif ($applyMonthRange) {
  2193. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  2194. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2195. $ds = $listTime;
  2196. }
  2197. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  2198. continue;
  2199. }
  2200. $mo = (int)$m[2];
  2201. if ($mo < 1 || $mo > 12) {
  2202. continue;
  2203. }
  2204. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2205. $rowMonthStart = $ymRow . '-01 00:00:00';
  2206. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2207. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2208. continue;
  2209. }
  2210. }
  2211. if ($search !== '') {
  2212. $hitSearch = false;
  2213. foreach ($searchColNames as $c) {
  2214. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  2215. if ($cell !== '' && $strContains($cell, $search)) {
  2216. $hitSearch = true;
  2217. break;
  2218. }
  2219. }
  2220. if (!$hitSearch) {
  2221. continue;
  2222. }
  2223. }
  2224. foreach ($filterArr as $fk => $fv) {
  2225. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  2226. continue;
  2227. }
  2228. if (is_array($fv)) {
  2229. continue;
  2230. }
  2231. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  2232. continue;
  2233. }
  2234. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  2235. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  2236. $field = $stripAlias($fk);
  2237. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  2238. $cellStr = trim((string)$cell);
  2239. switch ($sym) {
  2240. case '=':
  2241. if ((string)$cell !== (string)$fv) {
  2242. continue 3;
  2243. }
  2244. break;
  2245. case '<>':
  2246. if ((string)$cell === (string)$fv) {
  2247. continue 3;
  2248. }
  2249. break;
  2250. case 'LIKE':
  2251. case 'NOT LIKE':
  2252. $needle = trim((string)$fv);
  2253. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  2254. if ($sym === 'LIKE' && !$hit) {
  2255. continue 3;
  2256. }
  2257. if ($sym === 'NOT LIKE' && $hit) {
  2258. continue 3;
  2259. }
  2260. break;
  2261. case '>':
  2262. case '>=':
  2263. case '<':
  2264. case '<=':
  2265. if (!is_numeric($cell) && $cellStr === '') {
  2266. continue 3;
  2267. }
  2268. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  2269. $vv = (float)$fv;
  2270. if ($sym === '>' && !($cv > $vv)) {
  2271. continue 3;
  2272. }
  2273. if ($sym === '>=' && !($cv >= $vv)) {
  2274. continue 3;
  2275. }
  2276. if ($sym === '<' && !($cv < $vv)) {
  2277. continue 3;
  2278. }
  2279. if ($sym === '<=' && !($cv <= $vv)) {
  2280. continue 3;
  2281. }
  2282. break;
  2283. case 'RANGE':
  2284. case 'NOT RANGE':
  2285. case 'BETWEEN':
  2286. case 'NOT BETWEEN':
  2287. case 'BETWEEN TIME':
  2288. case 'NOT BETWEEN TIME':
  2289. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  2290. $rawR = str_replace(' - ', ',', $rawR);
  2291. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  2292. if (count($arr) < 2) {
  2293. break;
  2294. }
  2295. $lo = $arr[0];
  2296. $hi = $arr[1];
  2297. if ($lo === '' && $hi === '') {
  2298. break;
  2299. }
  2300. $isNot = (strpos($sym, 'NOT') !== false);
  2301. if ($lo === '') {
  2302. $in = ($cellStr !== '' && $cellStr <= $hi);
  2303. if ($isNot ? $in : !$in) {
  2304. continue 3;
  2305. }
  2306. break;
  2307. }
  2308. if ($hi === '') {
  2309. $in = ($cellStr !== '' && $cellStr >= $lo);
  2310. if ($isNot ? $in : !$in) {
  2311. continue 3;
  2312. }
  2313. break;
  2314. }
  2315. $in = ($cellStr >= $lo && $cellStr <= $hi);
  2316. if ($isNot ? $in : !$in) {
  2317. continue 3;
  2318. }
  2319. break;
  2320. case 'NULL':
  2321. case 'IS NULL':
  2322. if ($cell !== null && $cell !== '') {
  2323. continue 3;
  2324. }
  2325. break;
  2326. case 'NOT NULL':
  2327. case 'IS NOT NULL':
  2328. if ($cell === null || $cell === '') {
  2329. continue 3;
  2330. }
  2331. break;
  2332. default:
  2333. break;
  2334. }
  2335. }
  2336. $filtered[] = $r;
  2337. }
  2338. return $filtered;
  2339. }
  2340. /**
  2341. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  2342. */
  2343. public function snapshotToProcure()
  2344. {
  2345. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2346. $this->error(__('Invalid parameters'));
  2347. }
  2348. $row = json_decode($this->request->post('row_json', ''), true);
  2349. if (!is_array($row)) {
  2350. $this->error(__('Invalid parameters'));
  2351. }
  2352. try {
  2353. $ids = $this->extractScydgyRowId($row);
  2354. if (!$this->isValidScydgyRowId($ids)) {
  2355. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2356. }
  2357. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2358. $data = [
  2359. 'scydgy_id' => $ids,
  2360. 'CCYDH' => $row['CCYDH'] ?? null,
  2361. 'CYJMC' => $row['CYJMC'] ?? null,
  2362. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2363. 'CDXMC' => $row['CDXMC'] ?? null,
  2364. 'CGYBH' => $row['CGYBH'] ?? null,
  2365. 'CGYMC' => $row['CGYMC'] ?? null,
  2366. 'CDW' => $row['CDW'] ?? null,
  2367. 'NGZL' => $row['NGZL'] ?? null,
  2368. 'CDF' => $row['CDF'] ?? null,
  2369. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2370. 'MBZ' => $row['MBZ'] ?? null,
  2371. 'bwjg' => $row['bwjg'] ?? null,
  2372. 'iStatus' => $row['iStatus'] ?? null,
  2373. 'dStamp' => $row['dStamp'] ?? null,
  2374. 'dputrecord' => $row['dputrecord'] ?? null,
  2375. 'cywyxm' => $row['cywyxm'] ?? null,
  2376. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2377. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2378. ];
  2379. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  2380. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  2381. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  2382. $this->success('操作成功');
  2383. return;
  2384. }
  2385. if ($exists) {
  2386. $upd = $data;
  2387. unset($upd['scydgy_id'], $upd['status']);
  2388. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2389. } else {
  2390. // 新增:不写 status(空/走库默认);仅写创建时间
  2391. $data['createtime'] = date('Y-m-d H:i:s');
  2392. Db::table('purchase_order')->insert($data);
  2393. }
  2394. } catch (\Throwable $e) {
  2395. $this->error($e->getMessage());
  2396. }
  2397. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  2398. $this->success('操作成功');
  2399. }
  2400. /**
  2401. * 未发列表
  2402. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  2403. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  2404. */
  2405. public function completeDirectly()
  2406. {
  2407. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2408. $this->error(__('参数错误'));
  2409. }
  2410. $row = json_decode($this->request->post('row_json', ''), true);
  2411. if (!is_array($row)) {
  2412. $this->error(__('Invalid parameters'));
  2413. }
  2414. $finishRaw = $this->request->post('finish', '1');
  2415. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  2416. try {
  2417. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  2418. $ids = $this->extractScydgyRowId($row);
  2419. if (!$this->isValidScydgyRowId($ids)) {
  2420. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2421. }
  2422. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2423. $data = [
  2424. 'scydgy_id' => $ids,
  2425. 'CCYDH' => $row['CCYDH'] ?? null,
  2426. 'CYJMC' => $row['CYJMC'] ?? null,
  2427. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2428. 'CDXMC' => $row['CDXMC'] ?? null,
  2429. 'CGYBH' => $row['CGYBH'] ?? null,
  2430. 'CGYMC' => $row['CGYMC'] ?? null,
  2431. 'CDW' => $row['CDW'] ?? null,
  2432. 'NGZL' => $row['NGZL'] ?? null,
  2433. 'CDF' => $row['CDF'] ?? null,
  2434. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2435. 'MBZ' => $row['MBZ'] ?? null,
  2436. 'bwjg' => $row['bwjg'] ?? null,
  2437. 'iStatus' => $row['iStatus'] ?? null,
  2438. 'dStamp' => $row['dStamp'] ?? null,
  2439. 'dputrecord' => $row['dputrecord'] ?? null,
  2440. 'cywyxm' => $row['cywyxm'] ?? null,
  2441. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2442. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2443. ];
  2444. if ($asComplete) {
  2445. // 主表 status 为 varchar 时统一写 '1',档案 procuremenarchive 按 status=1 查询
  2446. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  2447. }
  2448. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  2449. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  2450. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  2451. $this->success('操作成功');
  2452. return;
  2453. }
  2454. if ($exists) {
  2455. $upd = $data;
  2456. unset($upd['scydgy_id']);
  2457. if (!$asComplete) {
  2458. unset($upd['status']);
  2459. }
  2460. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2461. } else {
  2462. // 新增:不写 status;完结时 $data 已含 status=1
  2463. $data['createtime'] = date('Y-m-d H:i:s');
  2464. Db::table('purchase_order')->insert($data);
  2465. }
  2466. } catch (\Throwable $e) {
  2467. $this->error($e->getMessage());
  2468. }
  2469. $poIdLog = null;
  2470. try {
  2471. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2472. if (is_array($rpo)) {
  2473. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  2474. $poIdLog = $tid > 0 ? $tid : null;
  2475. }
  2476. } catch (\Throwable $e) {
  2477. $poIdLog = null;
  2478. }
  2479. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  2480. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  2481. if ($asComplete) {
  2482. $this->addOrderLog(
  2483. $ids,
  2484. 'mark_complete',
  2485. '点击「完结」,已标记为已完结',
  2486. $poIdLog
  2487. );
  2488. try {
  2489. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  2490. if ($pdfPublicPath === '') {
  2491. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  2492. }
  2493. } catch (\Throwable $e) {
  2494. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  2495. }
  2496. } else {
  2497. $this->addOrderLog(
  2498. $ids,
  2499. 'save_qty_price',
  2500. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  2501. $poIdLog
  2502. );
  2503. }
  2504. $this->success("操作成功");
  2505. }
  2506. /**
  2507. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  2508. *
  2509. * @param array<int, array> $rows 引用传递当前页行
  2510. */
  2511. protected function mergePurchaseOrder(array &$rows)
  2512. {
  2513. if ($rows === []) {
  2514. return;
  2515. }
  2516. $ids = [];
  2517. foreach ($rows as $rw) {
  2518. if (!is_array($rw)) {
  2519. continue;
  2520. }
  2521. $id = (int)($rw['ID'] ?? 0);
  2522. if ($id > 0) {
  2523. $ids[$id] = true;
  2524. }
  2525. }
  2526. $idList = array_keys($ids);
  2527. if ($idList === []) {
  2528. return;
  2529. }
  2530. try {
  2531. $list = Db::table('purchase_order')
  2532. ->where('scydgy_id', 'in', $idList)
  2533. ->field('scydgy_id,This_quantity,ceilingPrice')
  2534. ->select();
  2535. } catch (\Throwable $e) {
  2536. return;
  2537. }
  2538. if (!is_array($list)) {
  2539. return;
  2540. }
  2541. $byId = [];
  2542. foreach ($list as $dbRow) {
  2543. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  2544. continue;
  2545. }
  2546. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  2547. }
  2548. foreach ($rows as &$rw) {
  2549. if (!is_array($rw)) {
  2550. continue;
  2551. }
  2552. $sid = (int)($rw['ID'] ?? 0);
  2553. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  2554. continue;
  2555. }
  2556. $db = $byId[$sid];
  2557. if (array_key_exists('This_quantity', $db) && $db['This_quantity'] !== null && $db['This_quantity'] !== '') {
  2558. $rw['This_quantity'] = $db['This_quantity'];
  2559. }
  2560. if (array_key_exists('ceilingPrice', $db) && $db['ceilingPrice'] !== null && $db['ceilingPrice'] !== '') {
  2561. $rw['ceilingPrice'] = $db['ceilingPrice'];
  2562. } elseif (array_key_exists('ceiling_price', $db) && $db['ceiling_price'] !== null && $db['ceiling_price'] !== '') {
  2563. $rw['ceilingPrice'] = $db['ceiling_price'];
  2564. }
  2565. }
  2566. unset($rw);
  2567. }
  2568. /**
  2569. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  2570. */
  2571. public function purchaseConfirmPick()
  2572. {
  2573. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2574. $this->error(__('Invalid parameters'));
  2575. }
  2576. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  2577. if ($batchRaw !== '') {
  2578. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  2579. return;
  2580. }
  2581. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  2582. $sid = (int)$scydgyId;
  2583. if (!$this->isValidScydgyRowId($sid)) {
  2584. $this->error('参数无效');
  2585. }
  2586. $parseIdList = function ($raw) {
  2587. if (is_array($raw)) {
  2588. $arr = $raw;
  2589. } else {
  2590. $decoded = json_decode((string)$raw, true);
  2591. $arr = is_array($decoded) ? $decoded : [];
  2592. }
  2593. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  2594. };
  2595. $selectedRaw = $this->request->post('selected_ids', null);
  2596. if ($selectedRaw === null || $selectedRaw === '') {
  2597. $legacy = (int)$this->request->post('selected_id', 0);
  2598. $selectedIds = $legacy > 0 ? [$legacy] : [];
  2599. } else {
  2600. $selectedIds = $parseIdList($selectedRaw);
  2601. }
  2602. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  2603. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  2604. try {
  2605. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  2606. } catch (\InvalidArgumentException $e) {
  2607. $this->error($e->getMessage());
  2608. } catch (\Throwable $e) {
  2609. $this->error($e->getMessage());
  2610. }
  2611. $this->success('操作成功', '', $result);
  2612. }
  2613. /**
  2614. * 整单采购确认(多道工序一次提交)
  2615. */
  2616. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  2617. {
  2618. $decoded = json_decode($batchRaw, true);
  2619. if (!is_array($decoded) || $decoded === []) {
  2620. $this->error('提交数据无效');
  2621. }
  2622. $picks = [];
  2623. foreach ($decoded as $item) {
  2624. if (!is_array($item)) {
  2625. continue;
  2626. }
  2627. $sid = (int)($item['scydgy_id'] ?? 0);
  2628. if (!$this->isValidScydgyRowId($sid)) {
  2629. continue;
  2630. }
  2631. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  2632. if (!is_array($sel)) {
  2633. $sel = [(int)$sel];
  2634. }
  2635. $unsel = $item['unselected_ids'] ?? [];
  2636. if (!is_array($unsel)) {
  2637. $unsel = json_decode((string)$unsel, true);
  2638. $unsel = is_array($unsel) ? $unsel : [];
  2639. }
  2640. $picks[] = [
  2641. 'scydgy_id' => $sid,
  2642. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  2643. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  2644. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  2645. ];
  2646. }
  2647. if ($picks === []) {
  2648. $this->error('提交数据无效');
  2649. }
  2650. Db::startTrans();
  2651. $results = [];
  2652. try {
  2653. foreach ($picks as $pick) {
  2654. $results[] = $this->runPurchaseConfirmPick(
  2655. (int)$pick['scydgy_id'],
  2656. $pick['selected_ids'],
  2657. $pick['unselected_ids'],
  2658. (int)$pick['purchase_order_id'],
  2659. false
  2660. );
  2661. }
  2662. Db::commit();
  2663. } catch (\Throwable $e) {
  2664. Db::rollback();
  2665. $msg = $e->getMessage();
  2666. $this->error($msg !== '' ? $msg : '提交失败');
  2667. }
  2668. $this->success('操作成功', '', ['batch' => $results]);
  2669. }
  2670. /**
  2671. * @return array<string, mixed>
  2672. */
  2673. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true): array
  2674. {
  2675. $scydgyId = (string)$sid;
  2676. if ($selectedIds === []) {
  2677. throw new \InvalidArgumentException('请至少勾选一条明细');
  2678. }
  2679. $inter = array_intersect($selectedIds, $unselectedIds);
  2680. if ($inter !== []) {
  2681. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  2682. }
  2683. $allIds = $this->purchaseOrderDetail($sid);
  2684. if ($allIds === []) {
  2685. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  2686. }
  2687. foreach ($selectedIds as $id) {
  2688. if (!in_array($id, $allIds, true)) {
  2689. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  2690. }
  2691. }
  2692. foreach ($unselectedIds as $id) {
  2693. if (!in_array($id, $allIds, true)) {
  2694. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  2695. }
  2696. }
  2697. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  2698. sort($union, SORT_NUMERIC);
  2699. $expect = $allIds;
  2700. sort($expect, SORT_NUMERIC);
  2701. if ($union !== $expect) {
  2702. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  2703. }
  2704. if ($manageTransaction) {
  2705. Db::startTrans();
  2706. }
  2707. try {
  2708. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  2709. $aff = 0;
  2710. try {
  2711. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  2712. } catch (\Throwable $e) {
  2713. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  2714. }
  2715. if ($aff < 1) {
  2716. throw new \Exception('更新选中状态失败');
  2717. }
  2718. if ($purchaseOrderId > 0) {
  2719. $poAff = (int)Db::table('purchase_order')
  2720. ->where('id', $purchaseOrderId)
  2721. ->where('scydgy_id', $sid)
  2722. ->update(['status' => ProcuremenStatus::POD_PICKED]);
  2723. if ($poAff < 1) {
  2724. throw new \Exception('主表订单不存在或与工序行不匹配');
  2725. }
  2726. } else {
  2727. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::PO_COMPLETED]);
  2728. if ($poAff < 1) {
  2729. throw new \Exception('未找到');
  2730. }
  2731. }
  2732. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  2733. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  2734. if ($manageTransaction) {
  2735. Db::commit();
  2736. }
  2737. } catch (\Throwable $e) {
  2738. if ($manageTransaction) {
  2739. Db::rollback();
  2740. }
  2741. throw $e;
  2742. }
  2743. $poIdFinal = $purchaseOrderId;
  2744. if ($poIdFinal <= 0) {
  2745. try {
  2746. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2747. if (is_array($rpo)) {
  2748. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  2749. }
  2750. } catch (\Throwable $e) {
  2751. $poIdFinal = 0;
  2752. }
  2753. }
  2754. $pickNames = [];
  2755. foreach ($selectedIds as $pid) {
  2756. $dr = $this->purchaseOrderDetai($sid, $pid);
  2757. $nm = trim((string)($dr['company_name'] ?? ''));
  2758. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  2759. }
  2760. $this->addOrderLog(
  2761. $sid,
  2762. 'purchase_confirm',
  2763. '采购确认:已选中供应商「' . implode('、', $pickNames) . '」;',
  2764. $poIdFinal > 0 ? $poIdFinal : null
  2765. );
  2766. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars($sid, $selectedIds[0] ?? 0);
  2767. $sendSmsSafe = function ($phone, $content) {
  2768. $phone = trim((string)$phone);
  2769. if ($phone === '') {
  2770. return;
  2771. }
  2772. try {
  2773. $this->smsbao($phone, $content);
  2774. } catch (\Throwable $e) {
  2775. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  2776. }
  2777. };
  2778. foreach ($selectedIds as $pid) {
  2779. $dr = $this->purchaseOrderDetai($sid, $pid);
  2780. if (!is_array($dr)) {
  2781. continue;
  2782. }
  2783. $cname = trim((string)($dr['company_name'] ?? ''));
  2784. $ph = trim((string)($dr['phone'] ?? ''));
  2785. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  2786. 'company_name' => $cname,
  2787. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  2788. 'phone' => $ph,
  2789. ]));
  2790. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  2791. }
  2792. foreach ($unselectedIds as $pid) {
  2793. $dr = $this->purchaseOrderDetai($sid, $pid);
  2794. if (!is_array($dr)) {
  2795. continue;
  2796. }
  2797. $cname = trim((string)($dr['company_name'] ?? ''));
  2798. $ph = trim((string)($dr['phone'] ?? ''));
  2799. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  2800. 'company_name' => $cname,
  2801. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  2802. 'phone' => $ph,
  2803. ]));
  2804. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  2805. }
  2806. Log::write(sprintf(
  2807. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  2808. $scydgyId,
  2809. $purchaseOrderId,
  2810. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  2811. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  2812. ), 'notice');
  2813. $pdfPublicPath = '';
  2814. try {
  2815. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  2816. } catch (\Throwable $e) {
  2817. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  2818. }
  2819. return [
  2820. 'scydgy_id' => $scydgyId,
  2821. 'purchase_order_id' => $purchaseOrderId,
  2822. 'selected_ids' => $selectedIds,
  2823. 'unselected_ids' => $unselectedIds,
  2824. 'purchase_confirm_pdf' => $pdfPublicPath,
  2825. ];
  2826. }
  2827. /**
  2828. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  2829. *
  2830. * @param int[] $detailIds
  2831. */
  2832. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  2833. {
  2834. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  2835. if ($detailIds === []) {
  2836. return;
  2837. }
  2838. $payload = ['status_name' => $statusName];
  2839. try {
  2840. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  2841. } catch (\Throwable $e) {
  2842. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  2843. }
  2844. }
  2845. /**
  2846. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  2847. */
  2848. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  2849. {
  2850. try {
  2851. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  2852. } catch (\Throwable $e) {
  2853. return;
  2854. }
  2855. if (!is_array($rows)) {
  2856. return;
  2857. }
  2858. foreach ($rows as $dr) {
  2859. if (!is_array($dr)) {
  2860. continue;
  2861. }
  2862. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  2863. if ($id <= 0) {
  2864. continue;
  2865. }
  2866. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  2867. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  2868. try {
  2869. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  2870. } catch (\Throwable $e) {
  2871. }
  2872. }
  2873. }
  2874. /**
  2875. * @param array<string, mixed> $detailRow
  2876. */
  2877. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  2878. {
  2879. $am = $detailRow['amount'] ?? null;
  2880. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  2881. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2882. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2883. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  2884. }
  2885. /**
  2886. * @return int[]
  2887. */
  2888. protected function purchaseOrderDetail(int $scydgyId): array
  2889. {
  2890. if (!$this->isValidScydgyRowId($scydgyId)) {
  2891. return [];
  2892. }
  2893. try {
  2894. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  2895. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  2896. $list = $listQuery->select();
  2897. } catch (\Throwable $e) {
  2898. return [];
  2899. }
  2900. if (!is_array($list)) {
  2901. return [];
  2902. }
  2903. $ids = [];
  2904. foreach ($list as $r) {
  2905. if (!is_array($r)) {
  2906. continue;
  2907. }
  2908. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  2909. if ($pk > 0) {
  2910. $ids[] = $pk;
  2911. }
  2912. }
  2913. return array_values(array_unique($ids));
  2914. }
  2915. /**
  2916. * 获取当前登录用户信息 [id, 展示名]
  2917. */
  2918. protected function GetUseName(): array
  2919. {
  2920. $id = 0;
  2921. $name = '';
  2922. try {
  2923. if ($this->auth && $this->auth->isLogin()) {
  2924. $u = $this->auth->getUserInfo();
  2925. if (is_array($u)) {
  2926. $id = (int)($u['id'] ?? 0);
  2927. $name = trim((string)($u['nickname'] ?? ''));
  2928. if ($name === '') {
  2929. $name = trim((string)($u['username'] ?? ''));
  2930. }
  2931. }
  2932. }
  2933. } catch (\Throwable $e) {
  2934. }
  2935. if ($name === '') {
  2936. $name = '未知用户';
  2937. }
  2938. return [$id, $name];
  2939. }
  2940. /**
  2941. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  2942. */
  2943. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  2944. {
  2945. if (!$this->isValidScydgyRowId($scydgyId) || $content === '') {
  2946. return;
  2947. }
  2948. list($adminId, $adminName) = $this->GetUseName();
  2949. $cut = function ($s, $max) {
  2950. if (function_exists('mb_substr')) {
  2951. return mb_substr($s, 0, $max, 'UTF-8');
  2952. }
  2953. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  2954. };
  2955. try {
  2956. Db::table('purchase_order_oper_log')->insert([
  2957. 'scydgy_id' => $scydgyId,
  2958. 'purchase_order_id' => $purchaseOrderId,
  2959. 'admin_id' => $adminId,
  2960. 'admin_name' => $cut($adminName, 64),
  2961. 'action' => $cut((string)$action, 64),
  2962. 'content' => $cut($content, 1000),
  2963. // 表结构 createtime 为 int Unix 时间戳;日期字符串会导致插入失败或时间为 0,详情「操作记录」为空
  2964. 'createtime' => time(),
  2965. ]);
  2966. } catch (\Throwable $e) {
  2967. Log::write('procuremen addOrderLog: ' . $e->getMessage(), 'error');
  2968. }
  2969. }
  2970. /**
  2971. * 按主键取一条
  2972. */
  2973. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  2974. {
  2975. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  2976. return [];
  2977. }
  2978. try {
  2979. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  2980. if (is_array($one)) {
  2981. return $one;
  2982. }
  2983. } catch (\Throwable $e) {
  2984. }
  2985. try {
  2986. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  2987. if (is_array($one)) {
  2988. return $one;
  2989. }
  2990. } catch (\Throwable $e) {
  2991. }
  2992. return [];
  2993. }
  2994. /**
  2995. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  2996. */
  2997. protected function formatProcuremenDetailTime($v): string
  2998. {
  2999. if ($v === null || $v === '') {
  3000. return '';
  3001. }
  3002. if (is_numeric($v) && (int)$v > 946684800) {
  3003. return date('Y-m-d H:i:s', (int)$v);
  3004. }
  3005. $s = trim((string)$v);
  3006. if ($s !== '' && stripos($s, '0000-00-00') !== 0) {
  3007. return $s;
  3008. }
  3009. return '';
  3010. }
  3011. /**
  3012. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3013. */
  3014. protected function formatDeliveryYmd($v): string
  3015. {
  3016. if ($v === null || $v === '') {
  3017. return '';
  3018. }
  3019. $s = trim((string)$v);
  3020. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3021. return '';
  3022. }
  3023. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  3024. return $m[1];
  3025. }
  3026. $ts = strtotime($s);
  3027. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  3028. }
  3029. /**
  3030. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  3031. */
  3032. protected function detailRowSupplierOperated(array $r): bool
  3033. {
  3034. $am = $r['amount'] ?? null;
  3035. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3036. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3037. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3038. return $okAmt || $okDel;
  3039. }
  3040. /**
  3041. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  3042. */
  3043. protected function resolveDetailSupplierOperTime(array $r): string
  3044. {
  3045. if (!$this->detailRowSupplierOperated($r)) {
  3046. return '';
  3047. }
  3048. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  3049. if ($t !== '') {
  3050. return $t;
  3051. }
  3052. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  3053. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  3054. continue;
  3055. }
  3056. $t = $this->formatProcuremenDetailTime($r[$col]);
  3057. if ($t !== '') {
  3058. return $t;
  3059. }
  3060. }
  3061. return '';
  3062. }
  3063. /**
  3064. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  3065. */
  3066. protected function detailRowSupplierAccepted(array $r): bool
  3067. {
  3068. $am = $r['amount'] ?? null;
  3069. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3070. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3071. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3072. return $okAmt && $okDel;
  3073. }
  3074. /**
  3075. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  3076. */
  3077. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  3078. {
  3079. if ($detailCount > 0) {
  3080. return true;
  3081. }
  3082. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  3083. return true;
  3084. }
  3085. $pickTime = trim((string)($main['pick_time'] ?? ''));
  3086. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  3087. return true;
  3088. }
  3089. return false;
  3090. }
  3091. /**
  3092. * 下发时间:优先 pick_time,其次首条下发明细时间
  3093. */
  3094. protected function resolveProcuremenIssueTime(array $main, array $details): string
  3095. {
  3096. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  3097. if ($issueTime !== '') {
  3098. return $issueTime;
  3099. }
  3100. foreach ($details as $dr) {
  3101. if (!is_array($dr)) {
  3102. continue;
  3103. }
  3104. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3105. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  3106. $issueTime = $t;
  3107. }
  3108. }
  3109. if ($issueTime !== '') {
  3110. return $issueTime;
  3111. }
  3112. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3113. }
  3114. /**
  3115. * 直接点「完结」时间:优先操作记录 mark_complete
  3116. */
  3117. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  3118. {
  3119. if (!$this->isValidScydgyRowId($scydgyId)) {
  3120. return '';
  3121. }
  3122. try {
  3123. $log = Db::table('purchase_order_oper_log')
  3124. ->where('scydgy_id', $scydgyId)
  3125. ->where('action', 'mark_complete')
  3126. ->order('id', 'desc')
  3127. ->find();
  3128. if (is_array($log)) {
  3129. $ct = (int)($log['createtime'] ?? 0);
  3130. if ($ct > 946684800) {
  3131. return date('Y-m-d H:i:s', $ct);
  3132. }
  3133. }
  3134. } catch (\Throwable $e) {
  3135. }
  3136. return '';
  3137. }
  3138. /**
  3139. * 操作记录时间(取指定 action 最近一条)
  3140. *
  3141. * @param string|array<int, string> $actions
  3142. */
  3143. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  3144. {
  3145. if (!$this->isValidScydgyRowId($scydgyId)) {
  3146. return '';
  3147. }
  3148. $acts = is_array($actions) ? $actions : [$actions];
  3149. $acts = array_values(array_filter(array_map('strval', $acts)));
  3150. if ($acts === []) {
  3151. return '';
  3152. }
  3153. try {
  3154. $log = Db::table('purchase_order_oper_log')
  3155. ->where('scydgy_id', $scydgyId)
  3156. ->where('action', 'in', $acts)
  3157. ->order('id', 'desc')
  3158. ->find();
  3159. if (is_array($log)) {
  3160. $ct = (int)($log['createtime'] ?? 0);
  3161. if ($ct > 946684800) {
  3162. return date('Y-m-d H:i:s', $ct);
  3163. }
  3164. }
  3165. } catch (\Throwable $e) {
  3166. }
  3167. return '';
  3168. }
  3169. /**
  3170. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  3171. *
  3172. * @param array $main purchase_order 一行
  3173. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  3174. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  3175. */
  3176. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  3177. {
  3178. $issueCnt = count($details);
  3179. $acceptCnt = 0;
  3180. $pickedName = '';
  3181. $pickedTime = '';
  3182. foreach ($details as $dr) {
  3183. if (!is_array($dr)) {
  3184. continue;
  3185. }
  3186. if ($this->detailRowSupplierAccepted($dr)) {
  3187. $acceptCnt++;
  3188. }
  3189. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3190. if ($pickedName === '') {
  3191. $pickedName = trim((string)($dr['company_name'] ?? ''));
  3192. }
  3193. if ($pickedTime === '') {
  3194. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  3195. if ($pickedTime === '') {
  3196. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3197. }
  3198. }
  3199. }
  3200. }
  3201. $hasMain = $main !== [];
  3202. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  3203. if ($poTime === '') {
  3204. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  3205. }
  3206. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  3207. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  3208. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  3209. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  3210. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  3211. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  3212. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  3213. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  3214. $supplierTime = '';
  3215. if ($acceptCnt > 0) {
  3216. foreach ($details as $dr) {
  3217. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  3218. continue;
  3219. }
  3220. $t = $this->resolveDetailSupplierOperTime($dr);
  3221. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  3222. $supplierTime = $t;
  3223. }
  3224. }
  3225. }
  3226. $directComplete = ($mainCompleted && !$issued);
  3227. $doneTime = '';
  3228. if ($mainCompleted) {
  3229. if ($directComplete) {
  3230. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  3231. }
  3232. if ($doneTime === '') {
  3233. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3234. }
  3235. if ($doneTime === '') {
  3236. foreach ($details as $dr) {
  3237. if (!is_array($dr)) {
  3238. continue;
  3239. }
  3240. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  3241. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  3242. $doneTime = $t;
  3243. }
  3244. }
  3245. }
  3246. if ($doneTime === '') {
  3247. $doneTime = $poTime;
  3248. }
  3249. if ($confirmApproveTime !== '') {
  3250. $doneTime = $confirmApproveTime;
  3251. }
  3252. }
  3253. if ($directComplete) {
  3254. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  3255. $step1Done = $hasMain;
  3256. $step2Done = false;
  3257. $step3Done = false;
  3258. $step4Done = false;
  3259. $step5Done = false;
  3260. $step6Done = true;
  3261. } else {
  3262. $step1Done = $issued;
  3263. $step2Done = $issued;
  3264. $step3Done = $acceptCnt > 0;
  3265. $step4Done = $wflowPendingApproval;
  3266. if (!$step4Done) {
  3267. foreach ($details as $dr) {
  3268. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3269. $step4Done = true;
  3270. break;
  3271. }
  3272. }
  3273. }
  3274. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  3275. $step6Done = $mainCompleted;
  3276. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  3277. if ($mainCompleted && $issued) {
  3278. $step3Done = true;
  3279. $step4Done = true;
  3280. $step5Done = true;
  3281. if ($supplierTime === '') {
  3282. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3283. if ($fillT !== '') {
  3284. $supplierTime = $fillT;
  3285. }
  3286. }
  3287. if ($pickedTime === '') {
  3288. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3289. if ($fillT !== '') {
  3290. $pickedTime = $fillT;
  3291. }
  3292. }
  3293. if ($auditSelectTime === '') {
  3294. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3295. if ($fillT !== '') {
  3296. $auditSelectTime = $fillT;
  3297. }
  3298. }
  3299. if ($confirmApproveTime === '') {
  3300. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3301. if ($fillT !== '') {
  3302. $confirmApproveTime = $fillT;
  3303. }
  3304. }
  3305. }
  3306. }
  3307. $steps = [
  3308. [
  3309. 'title' => '未发',
  3310. 'subtitle' => '',
  3311. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  3312. 'done' => $step1Done,
  3313. ],
  3314. [
  3315. 'title' => '下发',
  3316. 'subtitle' => '',
  3317. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  3318. 'done' => $step2Done,
  3319. ],
  3320. [
  3321. 'title' => '供应商接单',
  3322. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  3323. 'time' => $step3Done ? $supplierTime : '',
  3324. 'done' => $step3Done,
  3325. ],
  3326. [
  3327. 'title' => '待确认',
  3328. 'subtitle' => $step4Done
  3329. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  3330. : ($issued ? '待选供应商' : ''),
  3331. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  3332. 'done' => $step4Done,
  3333. ],
  3334. [
  3335. 'title' => '待审批',
  3336. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  3337. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  3338. 'done' => $step5Done,
  3339. ],
  3340. [
  3341. 'title' => '已完结',
  3342. 'subtitle' => '',
  3343. 'time' => $step6Done ? $doneTime : '',
  3344. 'done' => $step6Done,
  3345. ],
  3346. ];
  3347. $currentIdx = count($steps) - 1;
  3348. if (!$directComplete) {
  3349. foreach ($steps as $i => $s) {
  3350. if (!$s['done']) {
  3351. $currentIdx = $i;
  3352. break;
  3353. }
  3354. }
  3355. }
  3356. $nSteps = count($steps);
  3357. foreach ($steps as $idx => &$s) {
  3358. $s['current'] = ($idx === $currentIdx);
  3359. if ($idx === 0) {
  3360. $s['pdf_left_bg'] = '';
  3361. } else {
  3362. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  3363. }
  3364. if ($idx >= $nSteps - 1) {
  3365. $s['pdf_right_bg'] = '';
  3366. } else {
  3367. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  3368. }
  3369. }
  3370. unset($s);
  3371. $labelMap = [
  3372. 'CCYDH' => '订单号',
  3373. 'CYJMC' => '印件名称',
  3374. 'CCLBMMC' => '承揽部门',
  3375. 'CGYMC' => '工序名称',
  3376. 'CDW' => '单位',
  3377. 'NGZL' => '工作量',
  3378. 'CDF' => '单价',
  3379. 'cGzzxMc' => '工作中心',
  3380. 'MBZ' => '备注',
  3381. 'This_quantity' => '本次数量',
  3382. 'ceilingPrice' => '最高限价',
  3383. ];
  3384. $orderSummary = [];
  3385. foreach ($labelMap as $key => $lab) {
  3386. if (!array_key_exists($key, $main)) {
  3387. continue;
  3388. }
  3389. $val = $main[$key];
  3390. if ($val === null) {
  3391. $val = '';
  3392. } elseif (!is_scalar($val)) {
  3393. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  3394. } else {
  3395. $val = (string)$val;
  3396. }
  3397. $orderSummary[] = ['label' => $lab, 'value' => $val];
  3398. }
  3399. $orderSummaryGrid = [];
  3400. $n = count($orderSummary);
  3401. for ($i = 0; $i < $n; $i += 2) {
  3402. $left = $orderSummary[$i];
  3403. $hasRight = ($i + 1) < $n;
  3404. $orderSummaryGrid[] = [
  3405. 'l1' => $left['label'],
  3406. 'v1' => $left['value'],
  3407. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  3408. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  3409. ];
  3410. }
  3411. return [
  3412. 'steps' => $steps,
  3413. 'orderSummary' => $orderSummary,
  3414. 'orderSummaryGrid' => $orderSummaryGrid,
  3415. 'detailRows' => $details,
  3416. ];
  3417. }
  3418. /**
  3419. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  3420. *
  3421. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  3422. */
  3423. protected function prepareProcuremenDetailsView(string $ids): array
  3424. {
  3425. $main = [];
  3426. try {
  3427. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3428. $main = is_array($one) ? $one : [];
  3429. } catch (\Throwable $e) {
  3430. $main = [];
  3431. }
  3432. $details = [];
  3433. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  3434. if ($mergeRows === []) {
  3435. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  3436. if ($mergeRows === [] && $main !== []) {
  3437. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  3438. }
  3439. }
  3440. $detailSidList = [];
  3441. $anchorSid = (int)$ids;
  3442. if ($anchorSid !== 0) {
  3443. $detailSidList[$anchorSid] = true;
  3444. }
  3445. foreach ($mergeRows as $mr) {
  3446. if (!is_array($mr)) {
  3447. continue;
  3448. }
  3449. $sid = $this->extractScydgyRowId($mr);
  3450. if ($sid !== 0) {
  3451. $detailSidList[$sid] = true;
  3452. }
  3453. }
  3454. try {
  3455. if ($detailSidList !== []) {
  3456. $details = Db::table('purchase_order_detail')
  3457. ->where('scydgy_id', 'in', array_keys($detailSidList))
  3458. ->order('id', 'asc')
  3459. ->select();
  3460. }
  3461. } catch (\Throwable $e) {
  3462. $details = [];
  3463. }
  3464. if (!is_array($details)) {
  3465. $details = [];
  3466. }
  3467. foreach ($details as &$r) {
  3468. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  3469. $r['id'] = $r['ID'];
  3470. }
  3471. if (isset($r['createtime'])) {
  3472. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  3473. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  3474. } else {
  3475. $r['createtime_text'] = (string)$r['createtime'];
  3476. }
  3477. } else {
  3478. $r['createtime_text'] = '';
  3479. }
  3480. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  3481. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  3482. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  3483. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  3484. }
  3485. unset($r);
  3486. $activeDetails = [];
  3487. foreach ($details as $r) {
  3488. if (is_array($r) && empty($r['is_void'])) {
  3489. $activeDetails[] = $r;
  3490. }
  3491. }
  3492. $operLogs = [];
  3493. try {
  3494. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  3495. } catch (\Throwable $e) {
  3496. $operLogs = [];
  3497. }
  3498. if (!is_array($operLogs)) {
  3499. $operLogs = [];
  3500. }
  3501. foreach ($operLogs as &$lg) {
  3502. if (!is_array($lg)) {
  3503. continue;
  3504. }
  3505. $ct = isset($lg['createtime']) ? (int)$lg['createtime'] : 0;
  3506. $lg['createtime_text'] = $ct > 946684800 ? date('Y-m-d H:i:s', $ct) : '';
  3507. }
  3508. unset($lg);
  3509. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  3510. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  3511. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  3512. if ($ccydh === '') {
  3513. foreach ($details as $r) {
  3514. if (!is_array($r)) {
  3515. continue;
  3516. }
  3517. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  3518. if ($ccydh !== '') {
  3519. break;
  3520. }
  3521. }
  3522. }
  3523. $this->view->assign('ccydh', $ccydh);
  3524. $this->view->assign('steps', $bundle['steps']);
  3525. $this->view->assign('orderSummary', $bundle['orderSummary']);
  3526. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  3527. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  3528. $this->view->assign('processCount', count($mergeRows));
  3529. $this->view->assign('detailRows', $details);
  3530. $this->view->assign('supplierQuoteGroups', $quoteView['supplier_groups']);
  3531. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  3532. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  3533. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  3534. $this->view->assign('operLogs', $operLogs);
  3535. return [
  3536. 'ok' => $main !== [] || $details !== [],
  3537. 'ccydh' => $ccydh,
  3538. ];
  3539. }
  3540. /**
  3541. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  3542. */
  3543. public function details()
  3544. {
  3545. $ids = $this->request->param('ids', $this->request->param('id', ''));
  3546. if (is_array($ids)) {
  3547. $ids = isset($ids[0]) ? $ids[0] : '';
  3548. }
  3549. $ids = trim((string)$ids);
  3550. if ($ids === '') {
  3551. $this->error(__('Invalid parameters'));
  3552. }
  3553. $this->assertManualOrderDetailsViewable((int)$ids);
  3554. $this->prepareProcuremenDetailsView($ids);
  3555. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  3556. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  3557. $this->view->engine->layout(false);
  3558. try {
  3559. return $this->view->fetch('procuremen/details_dialog_shell');
  3560. } finally {
  3561. if ($restoreLayout) {
  3562. $this->view->engine->layout($restoreLayout);
  3563. }
  3564. }
  3565. }
  3566. /**
  3567. * 解析合并审核工序行(订单号须一致,且均未协助)
  3568. *
  3569. * @return array<int, array<string, mixed>>
  3570. */
  3571. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  3572. {
  3573. $primary = json_decode($rowJson, true);
  3574. if (!is_array($primary)) {
  3575. $this->error(__('Invalid parameters'));
  3576. }
  3577. $merge = json_decode($mergeRowsJson, true);
  3578. if (!is_array($merge) || $merge === []) {
  3579. $merge = [$primary];
  3580. }
  3581. $seen = [];
  3582. $out = [];
  3583. foreach ($merge as $r) {
  3584. if (!is_array($r)) {
  3585. continue;
  3586. }
  3587. $id = $this->extractScydgyRowId($r);
  3588. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  3589. continue;
  3590. }
  3591. $seen[$id] = true;
  3592. $out[] = $r;
  3593. }
  3594. if ($out === []) {
  3595. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  3596. }
  3597. $ccydh = null;
  3598. foreach ($out as $r) {
  3599. $dh = trim((string)($r['CCYDH'] ?? ''));
  3600. if ($ccydh === null) {
  3601. $ccydh = $dh;
  3602. } elseif ($dh !== $ccydh) {
  3603. $this->error('合并审核要求所选行的订单号一致');
  3604. }
  3605. }
  3606. $ids = [];
  3607. foreach ($out as $r) {
  3608. $id = $this->extractScydgyRowId($r);
  3609. if ($this->isValidScydgyRowId($id)) {
  3610. $ids[$id] = true;
  3611. }
  3612. }
  3613. $poBySid = [];
  3614. $detCntBySid = [];
  3615. if ($ids !== []) {
  3616. $idList = array_keys($ids);
  3617. try {
  3618. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  3619. if (is_array($poList)) {
  3620. foreach ($poList as $po) {
  3621. if (!is_array($po)) {
  3622. continue;
  3623. }
  3624. $sid = (int)($po['scydgy_id'] ?? 0);
  3625. if ($this->isValidScydgyRowId($sid)) {
  3626. $poBySid[$sid] = $po;
  3627. }
  3628. }
  3629. }
  3630. } catch (\Throwable $e) {
  3631. }
  3632. try {
  3633. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  3634. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  3635. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  3636. if (is_array($detRows)) {
  3637. foreach ($detRows as $dr) {
  3638. if (!is_array($dr)) {
  3639. continue;
  3640. }
  3641. $sid = (int)($dr['scydgy_id'] ?? 0);
  3642. if ($this->isValidScydgyRowId($sid)) {
  3643. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  3644. }
  3645. }
  3646. }
  3647. } catch (\Throwable $e) {
  3648. }
  3649. }
  3650. foreach ($out as $r) {
  3651. $id = $this->extractScydgyRowId($r);
  3652. if (!$this->isValidScydgyRowId($id)) {
  3653. continue;
  3654. }
  3655. $po = $poBySid[$id] ?? null;
  3656. if (!is_array($po)) {
  3657. continue;
  3658. }
  3659. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  3660. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3661. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  3662. }
  3663. $detCnt = (int)($detCntBySid[$id] ?? 0);
  3664. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  3665. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3666. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  3667. }
  3668. }
  3669. return $out;
  3670. }
  3671. /**
  3672. * 规范化下发/确认时勾选的供应商
  3673. *
  3674. * @param array<int, mixed> $companies
  3675. * @return array<int, array<string, string>>
  3676. */
  3677. protected function normalizePickCompanies(array $companies): array
  3678. {
  3679. $out = [];
  3680. foreach ($companies as $c) {
  3681. if (!is_array($c)) {
  3682. continue;
  3683. }
  3684. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  3685. if ($name === '') {
  3686. continue;
  3687. }
  3688. $out[] = [
  3689. 'name' => $name,
  3690. 'company_name' => $name,
  3691. 'username' => trim((string)($c['username'] ?? '')),
  3692. 'email' => trim((string)($c['email'] ?? '')),
  3693. 'phone' => trim((string)($c['phone'] ?? '')),
  3694. 'company_type' => trim((string)($c['company_type'] ?? $c['category'] ?? '')),
  3695. ];
  3696. }
  3697. return $out;
  3698. }
  3699. /**
  3700. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  3701. *
  3702. * @param array<int, array<string, mixed>> $pool
  3703. * @return array<int, array<string, mixed>>
  3704. */
  3705. protected function collapseProcuremenPoolByOrder(array $pool): array
  3706. {
  3707. if ($pool === []) {
  3708. return [];
  3709. }
  3710. $groups = [];
  3711. foreach ($pool as $row) {
  3712. if (!is_array($row)) {
  3713. continue;
  3714. }
  3715. $dh = trim((string)($row['CCYDH'] ?? ''));
  3716. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  3717. if (!isset($groups[$key])) {
  3718. $groups[$key] = [];
  3719. }
  3720. $groups[$key][] = $row;
  3721. }
  3722. $out = [];
  3723. foreach ($groups as $ccydh => $rows) {
  3724. if ($rows === []) {
  3725. continue;
  3726. }
  3727. usort($rows, function ($a, $b) {
  3728. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  3729. });
  3730. $head = $rows[0];
  3731. $gymcList = [];
  3732. foreach ($rows as $r) {
  3733. $g = trim((string)($r['CGYMC'] ?? ''));
  3734. if ($g !== '' && !in_array($g, $gymcList, true)) {
  3735. $gymcList[] = $g;
  3736. }
  3737. }
  3738. $merged = $head;
  3739. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  3740. $merged['process_count'] = count($rows);
  3741. $merged['_order_merge_rows'] = $rows;
  3742. if (count($rows) > 1) {
  3743. $merged['CGYMC'] = implode('、', $gymcList);
  3744. }
  3745. $mergedPickTime = '';
  3746. foreach ($rows as $r) {
  3747. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  3748. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  3749. $mergedPickTime = $t;
  3750. }
  3751. }
  3752. if ($mergedPickTime !== '') {
  3753. $merged['pick_time'] = $mergedPickTime;
  3754. }
  3755. $out[] = $merged;
  3756. }
  3757. usort($out, function ($a, $b) {
  3758. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  3759. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  3760. if ($ta === $tb) {
  3761. $ida = (int)($a['purchase_order_id'] ?? 0);
  3762. $idb = (int)($b['purchase_order_id'] ?? 0);
  3763. if ($ida !== $idb) {
  3764. return $idb <=> $ida;
  3765. }
  3766. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  3767. }
  3768. if ($ta === '') {
  3769. return 1;
  3770. }
  3771. if ($tb === '') {
  3772. return -1;
  3773. }
  3774. return strcmp($tb, $ta);
  3775. });
  3776. return $out;
  3777. }
  3778. /**
  3779. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  3780. *
  3781. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3782. */
  3783. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  3784. {
  3785. $scydgyId = trim($scydgyId);
  3786. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3787. if ($scydgyId === '') {
  3788. return $empty;
  3789. }
  3790. try {
  3791. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3792. } catch (\Throwable $e) {
  3793. $anchor = null;
  3794. }
  3795. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  3796. return $empty;
  3797. }
  3798. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3799. if ($ccydh === '') {
  3800. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  3801. }
  3802. try {
  3803. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  3804. } catch (\Throwable $e) {
  3805. $pos = [$anchor];
  3806. }
  3807. if (!is_array($pos) || $pos === []) {
  3808. $pos = [$anchor];
  3809. }
  3810. return [
  3811. 'ccydh' => $ccydh,
  3812. 'pos' => $pos,
  3813. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3814. ];
  3815. }
  3816. /**
  3817. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  3818. */
  3819. protected function purchaseOrderRowInConfirmStage(array $po): bool
  3820. {
  3821. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  3822. return false;
  3823. }
  3824. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  3825. return true;
  3826. }
  3827. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  3828. $sid = (int)($po['scydgy_id'] ?? 0);
  3829. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  3830. }
  3831. return false;
  3832. }
  3833. /**
  3834. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  3835. *
  3836. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3837. */
  3838. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  3839. {
  3840. $scydgyId = trim($scydgyId);
  3841. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3842. if ($scydgyId === '') {
  3843. return $empty;
  3844. }
  3845. try {
  3846. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3847. } catch (\Throwable $e) {
  3848. $anchor = null;
  3849. }
  3850. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  3851. return $empty;
  3852. }
  3853. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3854. if ($ccydh === '') {
  3855. return [
  3856. 'ccydh' => '',
  3857. 'pos' => [$anchor],
  3858. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  3859. ];
  3860. }
  3861. try {
  3862. $pos = Db::table('purchase_order')
  3863. ->where('CCYDH', $ccydh)
  3864. ->whereRaw(ProcuremenStatus::sqlPoInProgress('status'))
  3865. ->where(function ($q) {
  3866. $q->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  3867. ->whereOr(function ($q2) {
  3868. $q2->whereIn('wflow_status', ProcuremenStatus::wflowPendingIssueValues())
  3869. ->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  3870. });
  3871. })
  3872. ->order('scydgy_id', 'asc')
  3873. ->select();
  3874. } catch (\Throwable $e) {
  3875. $pos = [$anchor];
  3876. }
  3877. if (!is_array($pos) || $pos === []) {
  3878. $pos = [$anchor];
  3879. }
  3880. $pos = array_values(array_filter($pos, function ($po) {
  3881. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  3882. }));
  3883. if ($pos === []) {
  3884. $pos = [$anchor];
  3885. }
  3886. return [
  3887. 'ccydh' => $ccydh,
  3888. 'pos' => $pos,
  3889. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3890. ];
  3891. }
  3892. /**
  3893. * @param array<int, array<string, mixed>> $purchaseOrders
  3894. * @return array<int, array<string, mixed>>
  3895. */
  3896. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  3897. {
  3898. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  3899. $byId = [];
  3900. foreach ($pool as $r) {
  3901. if (!is_array($r)) {
  3902. continue;
  3903. }
  3904. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  3905. if ($this->isValidScydgyRowId($sid)) {
  3906. $byId[$sid] = $r;
  3907. }
  3908. }
  3909. $out = [];
  3910. foreach ($purchaseOrders as $po) {
  3911. if (!is_array($po)) {
  3912. continue;
  3913. }
  3914. $sid = (int)($po['scydgy_id'] ?? 0);
  3915. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  3916. $out[] = $byId[$sid];
  3917. }
  3918. }
  3919. return $out;
  3920. }
  3921. /**
  3922. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  3923. *
  3924. * @return array<int, array<string, mixed>>
  3925. */
  3926. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  3927. {
  3928. $scydgyId = trim($scydgyId);
  3929. if ($scydgyId === '') {
  3930. return [];
  3931. }
  3932. try {
  3933. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3934. } catch (\Throwable $e) {
  3935. $anchor = null;
  3936. }
  3937. if (!is_array($anchor)) {
  3938. return [];
  3939. }
  3940. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  3941. return [];
  3942. }
  3943. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3944. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  3945. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  3946. try {
  3947. $q = Db::table('purchase_order');
  3948. if ($ccydh !== '') {
  3949. $q->where('CCYDH', $ccydh);
  3950. } else {
  3951. $q->where('scydgy_id', $scydgyId);
  3952. }
  3953. if ($isValidPick) {
  3954. $q->where('pick_time', $pickTime);
  3955. }
  3956. $pos = $q->order('scydgy_id', 'asc')->select();
  3957. } catch (\Throwable $e) {
  3958. $pos = [$anchor];
  3959. }
  3960. if (!is_array($pos) || $pos === []) {
  3961. $pos = [$anchor];
  3962. }
  3963. $pos = array_values(array_filter($pos, function ($po) {
  3964. if (!is_array($po)) {
  3965. return false;
  3966. }
  3967. $mr = $po['mod_rq'] ?? null;
  3968. if ($mr === null || $mr === '') {
  3969. return true;
  3970. }
  3971. $mrs = trim((string)$mr);
  3972. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  3973. }));
  3974. if ($pos === []) {
  3975. $pos = [$anchor];
  3976. }
  3977. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  3978. if ($rows === []) {
  3979. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  3980. }
  3981. return $rows;
  3982. }
  3983. /**
  3984. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  3985. *
  3986. * @param array<int, array<string, mixed>> $mergeRows
  3987. * @return array<int, array<string, mixed>>
  3988. */
  3989. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  3990. {
  3991. $list = array_values($mergeRows);
  3992. $n = count($list);
  3993. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  3994. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  3995. $mergeSame = $n > 1 && $orderKey0 !== '';
  3996. if ($mergeSame) {
  3997. foreach ($list as $rr) {
  3998. if (!is_array($rr)) {
  3999. $mergeSame = false;
  4000. break;
  4001. }
  4002. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  4003. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  4004. $mergeSame = false;
  4005. break;
  4006. }
  4007. }
  4008. }
  4009. $out = [];
  4010. foreach ($list as $idx => $r) {
  4011. if (!is_array($r)) {
  4012. continue;
  4013. }
  4014. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  4015. if (is_scalar($qty)) {
  4016. $qty = trim((string)$qty);
  4017. } else {
  4018. $qty = '';
  4019. }
  4020. if ($qty === '') {
  4021. $gzl = $r['NGZL'] ?? '';
  4022. if (is_scalar($gzl)) {
  4023. $qty = trim((string)$gzl);
  4024. }
  4025. }
  4026. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  4027. $sid = $this->extractScydgyRowId($r);
  4028. $out[] = [
  4029. 'seq' => $idx + 1,
  4030. 'scydgy_id' => $sid,
  4031. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  4032. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  4033. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  4034. 'CDW' => trim((string)($r['CDW'] ?? '')),
  4035. 'NGZL' => $r['NGZL'] ?? '',
  4036. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  4037. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  4038. 'CDF' => trim((string)($r['CDF'] ?? '')),
  4039. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  4040. 'show_order_cells' => !$mergeSame || $idx === 0,
  4041. 'order_rowspan' => $mergeSame ? $n : 1,
  4042. ];
  4043. }
  4044. return $out;
  4045. }
  4046. /**
  4047. * 解析金额/数量(去千分位等非数字字符)
  4048. */
  4049. protected function parseProcuremenMoneyNumber($value): ?float
  4050. {
  4051. if ($value === null || $value === '') {
  4052. return null;
  4053. }
  4054. if (is_numeric($value)) {
  4055. return (float)$value;
  4056. }
  4057. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  4058. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  4059. }
  4060. protected function formatProcuremenMoneyDisplay(?float $amount): string
  4061. {
  4062. if ($amount === null) {
  4063. return '';
  4064. }
  4065. return (string)(int)round($amount);
  4066. }
  4067. /**
  4068. * 列表/详情展示:工作量为 0 时显示空
  4069. */
  4070. protected function formatProcuremenWorkloadDisplay($value): string
  4071. {
  4072. if ($value === null || $value === '') {
  4073. return '';
  4074. }
  4075. $s = trim((string)$value);
  4076. if ($s === '') {
  4077. return '';
  4078. }
  4079. if (is_numeric($s) && (float)$s == 0) {
  4080. return '';
  4081. }
  4082. return $s;
  4083. }
  4084. /**
  4085. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  4086. */
  4087. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  4088. {
  4089. foreach ($details as $d) {
  4090. if (!is_array($d)) {
  4091. continue;
  4092. }
  4093. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  4094. $cn = trim((string)($d['company_name'] ?? ''));
  4095. if ($cn !== '') {
  4096. return $cn;
  4097. }
  4098. }
  4099. }
  4100. return trim((string)($main['pick_company_name'] ?? ''));
  4101. }
  4102. /**
  4103. * 详情报价小计:单价 × 本工序本次数量
  4104. */
  4105. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  4106. {
  4107. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  4108. if ($unit === null) {
  4109. return null;
  4110. }
  4111. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  4112. if ($qty === null || $qty <= 0) {
  4113. return null;
  4114. }
  4115. return $unit * $qty;
  4116. }
  4117. /**
  4118. * 详情页:工序小计 + 供应商分组报价与总计
  4119. *
  4120. * @param array<int, array<string, mixed>> $mergeRows
  4121. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  4122. * @return array{
  4123. * process_rows: array,
  4124. * supplier_groups: array,
  4125. * order_total_text: string,
  4126. * order_total_has: bool,
  4127. * selected_company: string
  4128. * }
  4129. */
  4130. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  4131. {
  4132. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  4133. $qtyBySid = [];
  4134. $gymcBySid = [];
  4135. $orderedSids = [];
  4136. foreach ($mergeRows as $mr) {
  4137. if (!is_array($mr)) {
  4138. continue;
  4139. }
  4140. $sid = $this->extractScydgyRowId($mr);
  4141. if ($sid > 0) {
  4142. $orderedSids[] = $sid;
  4143. }
  4144. $qty = trim((string)($mr['This_quantity'] ?? ''));
  4145. if ($qty === '') {
  4146. $qty = trim((string)($mr['NGZL'] ?? ''));
  4147. }
  4148. $qtyBySid[$sid] = $qty;
  4149. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  4150. }
  4151. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  4152. $detailByCompanySid = [];
  4153. foreach ($details as $d) {
  4154. if (!is_array($d)) {
  4155. continue;
  4156. }
  4157. $cn = trim((string)($d['company_name'] ?? ''));
  4158. $sid = (int)($d['scydgy_id'] ?? 0);
  4159. if ($cn === '' || $sid === 0) {
  4160. continue;
  4161. }
  4162. if (!isset($detailByCompanySid[$cn])) {
  4163. $detailByCompanySid[$cn] = [];
  4164. }
  4165. $detailByCompanySid[$cn][$sid] = $d;
  4166. }
  4167. $supplierGroups = [];
  4168. foreach ($detailByCompanySid as $cn => $bySid) {
  4169. $lines = [];
  4170. $groupTotal = 0.0;
  4171. $groupHas = false;
  4172. $groupVoid = true;
  4173. $usedSids = [];
  4174. $appendLine = function (int $sid, array $d) use (
  4175. &$lines,
  4176. &$groupTotal,
  4177. &$groupHas,
  4178. &$groupVoid,
  4179. $qtyBySid,
  4180. $gymcBySid
  4181. ) {
  4182. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  4183. if (!$isVoid) {
  4184. $groupVoid = false;
  4185. }
  4186. $qtyStr = $qtyBySid[$sid] ?? '';
  4187. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4188. $sub = null;
  4189. if (!$isVoid && $amountNum !== null) {
  4190. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  4191. if ($sub !== null) {
  4192. $groupTotal += $sub;
  4193. $groupHas = true;
  4194. }
  4195. }
  4196. $ct = $this->resolveDetailSupplierOperTime($d);
  4197. $lines[] = [
  4198. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  4199. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : trim((string)($d['amount'] ?? '')),
  4200. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  4201. 'delivery_ymd' => $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null),
  4202. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  4203. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  4204. 'is_void' => $isVoid,
  4205. 'oper_time_text' => $ct,
  4206. ];
  4207. };
  4208. foreach ($orderedSids as $sid) {
  4209. if (!isset($bySid[$sid])) {
  4210. continue;
  4211. }
  4212. $usedSids[$sid] = true;
  4213. $appendLine($sid, $bySid[$sid]);
  4214. }
  4215. foreach ($bySid as $sid => $d) {
  4216. if (isset($usedSids[$sid])) {
  4217. continue;
  4218. }
  4219. $appendLine((int)$sid, $d);
  4220. }
  4221. $firstDetail = null;
  4222. foreach ($bySid as $d) {
  4223. if (is_array($d)) {
  4224. $firstDetail = $d;
  4225. break;
  4226. }
  4227. }
  4228. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  4229. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  4230. if ($username === '' && $ph !== '') {
  4231. $username = $this->resolveCustomerContactName($ph, $cn);
  4232. }
  4233. $lineCount = count($lines);
  4234. $supplierGroups[] = [
  4235. 'company_name' => $cn,
  4236. 'username' => $username,
  4237. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  4238. 'phone' => $ph,
  4239. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  4240. 'is_void' => $groupVoid,
  4241. 'lines' => $lines,
  4242. 'line_count' => $lineCount,
  4243. 'display_rowspan'=> $lineCount + ($lineCount > 0 ? 1 : 0),
  4244. 'total_text' => $groupHas ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  4245. 'has_total' => $lineCount > 0,
  4246. ];
  4247. }
  4248. usort($supplierGroups, function ($a, $b) {
  4249. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  4250. return ($a['is_void'] ?? false) ? 1 : -1;
  4251. }
  4252. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  4253. return ($a['is_selected'] ?? false) ? -1 : 1;
  4254. }
  4255. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  4256. });
  4257. return [
  4258. 'process_rows' => $processRows,
  4259. 'supplier_groups' => $supplierGroups,
  4260. 'order_total_text' => '',
  4261. 'order_total_has' => false,
  4262. 'selected_company' => $selectedCompany,
  4263. ];
  4264. }
  4265. /**
  4266. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  4267. */
  4268. protected function buildProcessLinesPlain(array $mergeRows): string
  4269. {
  4270. $lines = [];
  4271. $i = 1;
  4272. foreach ($mergeRows as $r) {
  4273. if (!is_array($r)) {
  4274. continue;
  4275. }
  4276. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4277. $dw = trim((string)($r['CDW'] ?? ''));
  4278. $gzl = trim((string)($r['NGZL'] ?? ''));
  4279. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4280. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  4281. if ($dw !== '') {
  4282. $parts[] = '单位:' . $dw;
  4283. }
  4284. if ($gzl !== '') {
  4285. $parts[] = '工作量:' . $gzl;
  4286. }
  4287. if ($qty !== '') {
  4288. $parts[] = '本次数量:' . $qty;
  4289. }
  4290. $lines[] = implode(' ', $parts);
  4291. $i++;
  4292. }
  4293. return implode("\n", $lines);
  4294. }
  4295. /**
  4296. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  4297. *
  4298. * @return array<string, string>
  4299. */
  4300. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0): array
  4301. {
  4302. $po = null;
  4303. try {
  4304. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4305. } catch (\Throwable $e) {
  4306. $po = null;
  4307. }
  4308. $ccydh = is_array($po) ? trim((string)($po['CCYDH'] ?? '')) : '';
  4309. $cyjmc = is_array($po) ? trim((string)($po['CYJMC'] ?? '')) : '';
  4310. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0) {
  4311. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  4312. if (is_array($any)) {
  4313. if ($ccydh === '') {
  4314. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  4315. }
  4316. if ($cyjmc === '') {
  4317. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  4318. }
  4319. }
  4320. }
  4321. $mergeRows = is_array($po) && $po !== [] ? [$po] : [];
  4322. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  4323. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  4324. return [
  4325. 'ccydh' => $ccydh,
  4326. 'cyjmc' => $cyjmc,
  4327. 'cgymc' => is_array($po) ? trim((string)($po['CGYMC'] ?? '')) : '',
  4328. 'process_lines' => $processLines,
  4329. 'process_lines_html' => '',
  4330. ];
  4331. }
  4332. /**
  4333. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  4334. */
  4335. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  4336. {
  4337. $lines = [];
  4338. if ($ccydh !== '') {
  4339. $lines[] = '订单号:' . $ccydh;
  4340. }
  4341. if ($cyjmc !== '') {
  4342. $lines[] = '印件名称:' . $cyjmc;
  4343. }
  4344. if ($processPlain !== '') {
  4345. $lines[] = $processPlain;
  4346. }
  4347. return implode("\n", $lines);
  4348. }
  4349. /**
  4350. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  4351. *
  4352. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4353. */
  4354. protected function buildPlatformLinksPlain(array $detailLinks): string
  4355. {
  4356. $lines = [];
  4357. $i = 1;
  4358. foreach ($detailLinks as $lk) {
  4359. if (!is_array($lk)) {
  4360. continue;
  4361. }
  4362. $url = trim((string)($lk['url'] ?? ''));
  4363. if ($url === '') {
  4364. continue;
  4365. }
  4366. $label = trim((string)($lk['cgymc'] ?? ''));
  4367. if ($label === '') {
  4368. $label = '工序' . $i;
  4369. }
  4370. $lines[] = $label . ':' . $url;
  4371. $i++;
  4372. }
  4373. return implode("\n", $lines);
  4374. }
  4375. /**
  4376. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  4377. *
  4378. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4379. */
  4380. protected function buildPlatformLinksHtml(array $detailLinks): string
  4381. {
  4382. $parts = [];
  4383. $i = 1;
  4384. foreach ($detailLinks as $lk) {
  4385. if (!is_array($lk)) {
  4386. continue;
  4387. }
  4388. $url = trim((string)($lk['url'] ?? ''));
  4389. if ($url === '') {
  4390. continue;
  4391. }
  4392. $label = trim((string)($lk['cgymc'] ?? ''));
  4393. if ($label === '') {
  4394. $label = '工序' . $i;
  4395. }
  4396. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  4397. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  4398. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  4399. $i++;
  4400. }
  4401. return implode("<br>\n", $parts);
  4402. }
  4403. /**
  4404. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  4405. *
  4406. * @return array<string, mixed>
  4407. */
  4408. protected function loadMailerConfig(): array
  4409. {
  4410. try {
  4411. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  4412. } catch (\Throwable $e) {
  4413. $cfg = [];
  4414. }
  4415. return is_array($cfg) ? $cfg : [];
  4416. }
  4417. protected function loadNotifyTemplateRow(string $scene): ?array
  4418. {
  4419. try {
  4420. $row = Db::table('purchase_sms_template')
  4421. ->where('scene', $scene)
  4422. ->where(function ($q) {
  4423. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  4424. })
  4425. ->order('id', 'asc')
  4426. ->find();
  4427. } catch (\Throwable $e) {
  4428. return null;
  4429. }
  4430. if (!is_array($row) || $row === []) {
  4431. return null;
  4432. }
  4433. return [
  4434. 'title' => trim((string)($row['title'] ?? '')),
  4435. 'content' => trim((string)($row['content'] ?? '')),
  4436. ];
  4437. }
  4438. /**
  4439. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  4440. */
  4441. protected function buildProcessLinesHtml(array $mergeRows): string
  4442. {
  4443. if (count($mergeRows) <= 1) {
  4444. $r = $mergeRows[0] ?? [];
  4445. if (!is_array($r)) {
  4446. return '';
  4447. }
  4448. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4449. $dw = trim((string)($r['CDW'] ?? ''));
  4450. $gzl = trim((string)($r['NGZL'] ?? ''));
  4451. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4452. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  4453. if ($dw !== '') {
  4454. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  4455. }
  4456. if ($gzl !== '') {
  4457. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  4458. }
  4459. if ($qty !== '') {
  4460. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  4461. }
  4462. return $html;
  4463. }
  4464. $rows = '';
  4465. $i = 1;
  4466. foreach ($mergeRows as $r) {
  4467. if (!is_array($r)) {
  4468. continue;
  4469. }
  4470. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  4471. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  4472. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  4473. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  4474. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  4475. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  4476. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  4477. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  4478. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  4479. $i++;
  4480. }
  4481. if ($rows === '') {
  4482. return '';
  4483. }
  4484. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  4485. . '<thead><tr style="background:#f5f5f5;">'
  4486. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  4487. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  4488. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  4489. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  4490. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  4491. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  4492. }
  4493. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  4494. {
  4495. $sysRq = trim($sysRq);
  4496. if ($sysRq === '') {
  4497. if ($required) {
  4498. $this->error('请选择截止时间');
  4499. }
  4500. return '';
  4501. }
  4502. $ts = strtotime($sysRq);
  4503. if ($ts === false || $ts <= 0) {
  4504. $this->error('截止时间格式无效');
  4505. }
  4506. return date('Y-m-d H:i:s', $ts);
  4507. }
  4508. protected function formatProcuremenSysRqForInput($sysRq): string
  4509. {
  4510. $sr = trim((string)$sysRq);
  4511. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  4512. return '';
  4513. }
  4514. $ts = strtotime($sr);
  4515. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  4516. }
  4517. /**
  4518. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  4519. * @return array{ccydh?:string,pos:array,merge_rows:array}
  4520. */
  4521. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  4522. {
  4523. $sysRqPost = trim($sysRqPost);
  4524. if ($sysRqPost === '') {
  4525. return $bundle;
  4526. }
  4527. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqPost, true);
  4528. $pos = $bundle['pos'] ?? [];
  4529. foreach ($pos as $poRow) {
  4530. if (!is_array($poRow)) {
  4531. continue;
  4532. }
  4533. $sid = (int)($poRow['scydgy_id'] ?? 0);
  4534. if (!$this->isValidScydgyRowId($sid)) {
  4535. continue;
  4536. }
  4537. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['sys_rq' => $sysRqDb]);
  4538. }
  4539. foreach ($pos as $i => $poRow) {
  4540. if (is_array($pos[$i])) {
  4541. $pos[$i]['sys_rq'] = $sysRqDb;
  4542. }
  4543. }
  4544. $bundle['pos'] = $pos;
  4545. return $bundle;
  4546. }
  4547. /**
  4548. * 写入/更新 purchase_order(单道工序行)
  4549. */
  4550. protected function upsertPurchaseOrderFromRow(
  4551. array $row,
  4552. string $sysRqDb,
  4553. ?int $wflowStatus = null,
  4554. ?string $pickTime = null,
  4555. ?array $exists = null
  4556. ): void {
  4557. $ids = $this->extractScydgyRowId($row);
  4558. if (!$this->isValidScydgyRowId($ids)) {
  4559. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  4560. }
  4561. if ($exists === null) {
  4562. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4563. }
  4564. $data = [
  4565. 'scydgy_id' => $ids,
  4566. 'CCYDH' => $row['CCYDH'] ?? null,
  4567. 'CYJMC' => $row['CYJMC'] ?? null,
  4568. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4569. 'CDXMC' => $row['CDXMC'] ?? null,
  4570. 'CGYBH' => $row['CGYBH'] ?? null,
  4571. 'CGYMC' => $row['CGYMC'] ?? null,
  4572. 'CDW' => $row['CDW'] ?? null,
  4573. 'NGZL' => $row['NGZL'] ?? null,
  4574. 'CDF' => $row['CDF'] ?? null,
  4575. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4576. 'MBZ' => $row['MBZ'] ?? null,
  4577. 'bwjg' => $row['bwjg'] ?? null,
  4578. 'iStatus' => $row['iStatus'] ?? null,
  4579. 'dStamp' => $row['dStamp'] ?? null,
  4580. 'dputrecord' => $row['dputrecord'] ?? null,
  4581. 'cywyxm' => $row['cywyxm'] ?? null,
  4582. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4583. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4584. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4585. 'sys_rq' => $sysRqDb,
  4586. ];
  4587. if ($wflowStatus !== null) {
  4588. $data['wflow_status'] = $wflowStatus;
  4589. }
  4590. if ($pickTime !== null && $pickTime !== '') {
  4591. $data['pick_time'] = $pickTime;
  4592. $data['pick_company_name'] = '';
  4593. }
  4594. if ($exists) {
  4595. $upd = $data;
  4596. unset($upd['scydgy_id']);
  4597. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4598. } else {
  4599. $data['createtime'] = date('Y-m-d H:i:s');
  4600. Db::table('purchase_order')->insert($data);
  4601. }
  4602. }
  4603. /**
  4604. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  4605. *
  4606. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  4607. */
  4608. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  4609. {
  4610. $toDb = function ($value) {
  4611. if ($value === null) {
  4612. return null;
  4613. }
  4614. if (is_scalar($value)) {
  4615. return $value;
  4616. }
  4617. return json_encode($value, JSON_UNESCAPED_UNICODE);
  4618. };
  4619. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4620. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4621. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4622. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  4623. if ($username === '') {
  4624. $username = $this->resolveCustomerContactName($phone, $companyName);
  4625. }
  4626. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  4627. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  4628. }
  4629. if ($phone === '') {
  4630. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  4631. }
  4632. $detailLinks = [];
  4633. foreach ($mergeRows as $row) {
  4634. if (!is_array($row)) {
  4635. continue;
  4636. }
  4637. $sid = $this->extractScydgyRowId($row);
  4638. $detailId = 0;
  4639. if ($skipExisting) {
  4640. try {
  4641. $existsQuery = Db::table('purchase_order_detail')
  4642. ->where('scydgy_id', $sid)
  4643. ->where('company_name', $companyName);
  4644. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  4645. $exists = $existsQuery->find();
  4646. } catch (\Throwable $e) {
  4647. $exists = null;
  4648. }
  4649. if (is_array($exists)) {
  4650. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  4651. }
  4652. }
  4653. if ($detailId <= 0) {
  4654. $one = [
  4655. 'scydgy_id' => $toDb($sid),
  4656. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  4657. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  4658. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  4659. 'username' => $username !== '' ? $username : null,
  4660. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  4661. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  4662. 'createtime' => date('Y-m-d H:i:s'),
  4663. 'status' => ProcuremenStatus::POD_UNPICKED,
  4664. 'status_name' => '未提交',
  4665. ];
  4666. Db::table('purchase_order_detail')->insert($one);
  4667. $detailId = (int)Db::getLastInsID();
  4668. }
  4669. $mprocUrl = '';
  4670. if ($buildMobileLinks && $detailId > 0) {
  4671. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  4672. }
  4673. $detailLinks[] = [
  4674. 'detail_id' => $detailId,
  4675. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  4676. 'url' => $mprocUrl,
  4677. ];
  4678. }
  4679. return $detailLinks;
  4680. }
  4681. /**
  4682. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  4683. * @return array<string, mixed>
  4684. */
  4685. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  4686. {
  4687. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4688. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4689. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4690. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  4691. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  4692. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  4693. $isMerge = !empty($ctx['is_merge']);
  4694. $contactName = trim((string)($c['username'] ?? ''));
  4695. if ($contactName === '') {
  4696. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  4697. }
  4698. $notifyVars = [
  4699. 'company_name' => $companyName,
  4700. 'contact_name' => $contactName,
  4701. 'phone' => $phone,
  4702. 'email' => $toEmail,
  4703. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  4704. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  4705. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  4706. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  4707. 'deadline' => (string)($ctx['deadline'] ?? ''),
  4708. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  4709. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  4710. 'platform_url' => $platformUrl,
  4711. 'platform_links' => $platformLinksPlain,
  4712. 'platform_links_html' => $platformLinksHtml,
  4713. ];
  4714. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  4715. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  4716. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  4717. return [
  4718. 'company_name' => $companyName,
  4719. 'phone' => $phone,
  4720. 'email' => $toEmail,
  4721. 'sms_content' => $smsContent,
  4722. 'mail_plain' => $mailPlain,
  4723. 'mail_body' => $mailBody,
  4724. 'notify_vars' => $notifyVars,
  4725. 'detail_links' => $detailLinks,
  4726. ];
  4727. }
  4728. /**
  4729. * 确认供应商 — 向选定一家发送短信/邮件(第二步)
  4730. *
  4731. * @param array<string, mixed> $chosen
  4732. * @param array<int, array<string, mixed>> $mergeRows
  4733. * @param array{ccydh:string, pos:array} $bundle
  4734. */
  4735. protected function sendAuditSupplierConfirmNotify(array $chosen, array $mergeRows, array $bundle): void
  4736. {
  4737. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, true, true);
  4738. }
  4739. /**
  4740. * @param array<string, mixed> $chosen
  4741. * @param array<int, array<string, mixed>> $mergeRows
  4742. * @param array{ccydh:string, pos:array} $bundle
  4743. */
  4744. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail): void
  4745. {
  4746. if (!$sendSms && !$sendEmail) {
  4747. return;
  4748. }
  4749. $companyName = trim((string)($chosen['name'] ?? ''));
  4750. $phone = trim((string)($chosen['phone'] ?? ''));
  4751. $toEmail = trim((string)($chosen['email'] ?? ''));
  4752. if ($companyName === '') {
  4753. throw new \Exception('供应商名称无效');
  4754. }
  4755. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  4756. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  4757. }
  4758. if ($sendSms && $phone === '') {
  4759. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  4760. }
  4761. $sids = [];
  4762. foreach ($mergeRows as $mr) {
  4763. if (!is_array($mr)) {
  4764. continue;
  4765. }
  4766. $sid = $this->extractScydgyRowId($mr);
  4767. if ($this->isValidScydgyRowId($sid)) {
  4768. $sids[$sid] = true;
  4769. }
  4770. }
  4771. if ($sids === []) {
  4772. throw new \Exception('未找到工序行,无法发送通知');
  4773. }
  4774. $sysRqNotify = '';
  4775. $pos = $bundle['pos'] ?? [];
  4776. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  4777. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  4778. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  4779. $ts = strtotime($sr);
  4780. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  4781. }
  4782. }
  4783. try {
  4784. $detailsQuery = Db::table('purchase_order_detail')
  4785. ->where('scydgy_id', 'in', array_keys($sids))
  4786. ->where('company_name', $companyName);
  4787. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4788. $details = $detailsQuery->order('id', 'asc')->select();
  4789. } catch (\Throwable $e) {
  4790. $details = [];
  4791. }
  4792. if (!is_array($details) || $details === []) {
  4793. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  4794. try {
  4795. $detailsQuery = Db::table('purchase_order_detail')
  4796. ->where('scydgy_id', 'in', array_keys($sids))
  4797. ->where('company_name', $companyName);
  4798. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4799. $details = $detailsQuery->order('id', 'asc')->select();
  4800. } catch (\Throwable $e) {
  4801. $details = [];
  4802. }
  4803. }
  4804. if (!is_array($details) || $details === []) {
  4805. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  4806. }
  4807. $detailLinks = [];
  4808. foreach ($details as $d) {
  4809. if (!is_array($d)) {
  4810. continue;
  4811. }
  4812. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  4813. if ($detailId <= 0) {
  4814. continue;
  4815. }
  4816. $sid = (int)($d['scydgy_id'] ?? 0);
  4817. $gymc = '';
  4818. foreach ($mergeRows as $mr) {
  4819. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  4820. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  4821. break;
  4822. }
  4823. }
  4824. $detailLinks[] = [
  4825. 'detail_id' => $detailId,
  4826. 'cgymc' => $gymc,
  4827. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  4828. ];
  4829. }
  4830. if ($detailLinks === []) {
  4831. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  4832. }
  4833. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  4834. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  4835. if ($sendEmail) {
  4836. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  4837. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  4838. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  4839. }
  4840. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  4841. $mailConfig = $this->loadMailerConfig();
  4842. if (!$this->isProcuremenNotifyDryRun()) {
  4843. if (empty($mailConfig['host'])) {
  4844. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  4845. }
  4846. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  4847. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  4848. }
  4849. }
  4850. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  4851. }
  4852. if ($sendSms) {
  4853. $this->issueSendSupplierSms($notifyBundle);
  4854. }
  4855. }
  4856. /**
  4857. * @param array<int, array<string, mixed>> $quoteGroups
  4858. * @return array<int, array<string, mixed>>
  4859. */
  4860. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  4861. {
  4862. $names = [];
  4863. if (is_string($companiesJson) && $companiesJson !== '') {
  4864. $decoded = json_decode($companiesJson, true);
  4865. if (is_array($decoded)) {
  4866. foreach ($decoded as $nm) {
  4867. $nm = trim((string)$nm);
  4868. if ($nm !== '') {
  4869. $names[] = $nm;
  4870. }
  4871. }
  4872. }
  4873. }
  4874. $names = array_values(array_unique($names));
  4875. if ($names === [] && $selectedCompany !== '') {
  4876. $names = [$selectedCompany];
  4877. }
  4878. if ($names === []) {
  4879. return $quoteGroups;
  4880. }
  4881. $targets = [];
  4882. foreach ($quoteGroups as $g) {
  4883. if (!is_array($g)) {
  4884. continue;
  4885. }
  4886. $cn = trim((string)($g['name'] ?? ''));
  4887. if ($cn !== '' && in_array($cn, $names, true)) {
  4888. $targets[] = $g;
  4889. }
  4890. }
  4891. return $targets;
  4892. }
  4893. /**
  4894. * @return array{pos:array, merge_rows:array, bundle:array}
  4895. */
  4896. protected function loadAuditResendBundle(string $scydgyId): array
  4897. {
  4898. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  4899. $pos = $bundle['pos'];
  4900. $mergeRows = $bundle['merge_rows'];
  4901. if ($pos === [] || $mergeRows === []) {
  4902. $this->error('该订单不在待确认供应商状态');
  4903. }
  4904. $sysRqDb = '';
  4905. if (isset($pos[0]) && is_array($pos[0])) {
  4906. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  4907. }
  4908. foreach ($pos as $i => $poRow) {
  4909. if (is_array($pos[$i]) && $sysRqDb !== '') {
  4910. $pos[$i]['sys_rq'] = $sysRqDb;
  4911. }
  4912. }
  4913. $bundle['pos'] = $pos;
  4914. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  4915. }
  4916. /**
  4917. * @param array<int, array<string, mixed>> $targets
  4918. */
  4919. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  4920. {
  4921. if ($targets === []) {
  4922. $this->error('未找到可通知的供应商');
  4923. }
  4924. $notifyErrors = [];
  4925. try {
  4926. $this->notifyDryRunPreview = [];
  4927. foreach ($targets as $g) {
  4928. if (!is_array($g)) {
  4929. continue;
  4930. }
  4931. $cname = trim((string)($g['name'] ?? ''));
  4932. if ($cname === '') {
  4933. continue;
  4934. }
  4935. $chosen = [
  4936. 'name' => $cname,
  4937. 'company_name' => $cname,
  4938. 'email' => trim((string)($g['email'] ?? '')),
  4939. 'phone' => trim((string)($g['phone'] ?? '')),
  4940. 'username' => trim((string)($g['username'] ?? '')),
  4941. ];
  4942. try {
  4943. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail);
  4944. } catch (\Throwable $e) {
  4945. $notifyErrors[] = $cname . ':' . $e->getMessage();
  4946. }
  4947. }
  4948. } catch (\Throwable $e) {
  4949. $this->error('通知发送失败:' . $e->getMessage());
  4950. }
  4951. if ($notifyErrors !== []) {
  4952. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  4953. }
  4954. if ($this->isProcuremenNotifyDryRun()) {
  4955. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  4956. 'notify_dry_run' => true,
  4957. 'notify_preview' => $this->notifyDryRunPreview,
  4958. ]);
  4959. }
  4960. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  4961. }
  4962. /**
  4963. * 协助下发 — 写入下发明细并拼好短信/邮件内容(供第二步发送)
  4964. *
  4965. * @return array<string, mixed>
  4966. */
  4967. protected function issueBuildSupplierNotifyBundle(array $c, array $mergeRows, array $ctx): array
  4968. {
  4969. $detailLinks = $this->issuePersistSupplierDetails($c, $mergeRows);
  4970. return $this->composeSupplierNotifyBundle($c, $ctx, $detailLinks);
  4971. }
  4972. /**
  4973. * 协助下发 — 发送短信(一家供应商)
  4974. *
  4975. * @param array<string, mixed> $bundle issueBuildSupplierNotifyBundle 返回值
  4976. */
  4977. protected function issueSendSupplierSms(array $bundle): void
  4978. {
  4979. $companyName = (string)($bundle['company_name'] ?? '');
  4980. $phone = (string)($bundle['phone'] ?? '');
  4981. $smsContent = (string)($bundle['sms_content'] ?? '');
  4982. $this->logIssueNotifyDebug('短信', [
  4983. 'company' => $companyName,
  4984. 'phone' => $phone,
  4985. 'sms_content' => $smsContent,
  4986. ]);
  4987. if ($this->isProcuremenNotifyDryRun()) {
  4988. $this->recordNotifyDryRunPreview([
  4989. 'scene' => 'issue_sms',
  4990. 'company_name' => $companyName,
  4991. 'phone' => $phone,
  4992. 'sms_content' => $smsContent,
  4993. ]);
  4994. return;
  4995. }
  4996. $this->smsbao($phone, $smsContent);
  4997. }
  4998. /**
  4999. * 协助下发 — 发送邮件(一家供应商)
  5000. *
  5001. * @param array<string, mixed> $bundle
  5002. * @param array<string, mixed> $mailConfig
  5003. */
  5004. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  5005. {
  5006. $companyName = (string)($bundle['company_name'] ?? '');
  5007. $toEmail = (string)($bundle['email'] ?? '');
  5008. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  5009. $mailBody = (string)($bundle['mail_body'] ?? '');
  5010. $this->logIssueNotifyDebug('邮件', [
  5011. 'company' => $companyName,
  5012. 'email' => $toEmail,
  5013. 'mail_subject' => $mailSubject,
  5014. 'mail_body' => $mailPlain,
  5015. ]);
  5016. if ($this->isProcuremenNotifyDryRun()) {
  5017. $this->recordNotifyDryRunPreview([
  5018. 'scene' => 'issue_email',
  5019. 'company_name' => $companyName,
  5020. 'email' => $toEmail,
  5021. 'mail_subject' => $mailSubject,
  5022. 'mail_body' => $mailPlain,
  5023. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  5024. 'notify_vars' => $bundle['notify_vars'] ?? [],
  5025. 'detail_links' => $bundle['detail_links'] ?? [],
  5026. ]);
  5027. return;
  5028. }
  5029. $mail = new PHPMailer(true);
  5030. $mail->isSMTP();
  5031. $mail->Host = $mailConfig['host'];
  5032. $mail->SMTPAuth = true;
  5033. $mail->Username = $mailConfig['addr'];
  5034. $mail->Password = $mailConfig['pass'];
  5035. $mail->SMTPSecure = $mailConfig['security'];
  5036. $mail->Port = $mailConfig['port'];
  5037. $mail->CharSet = $mailConfig['charset'];
  5038. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  5039. $mail->addAddress($toEmail, $companyName);
  5040. $mail->isHTML(true);
  5041. $mail->Subject = $mailSubject;
  5042. $mail->Body = $mailBody;
  5043. $mail->send();
  5044. }
  5045. /**
  5046. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  5047. *
  5048. * @param array<int, array<string, mixed>> $mergeRows
  5049. * @return array<string, mixed>
  5050. */
  5051. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  5052. {
  5053. $head = $mergeRows[0] ?? [];
  5054. $isMerge = count($mergeRows) > 1;
  5055. return [
  5056. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  5057. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  5058. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  5059. 'is_merge' => $isMerge,
  5060. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  5061. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  5062. 'deadline' => $sysRqNotify,
  5063. ];
  5064. }
  5065. /**
  5066. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  5067. *
  5068. * @param array<string, mixed> $data
  5069. */
  5070. protected function logIssueNotifyDebug(string $type, array $data): void
  5071. {
  5072. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  5073. return;
  5074. }
  5075. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  5076. }
  5077. /**
  5078. * 协助下发弹窗(选多家供应商并通知)
  5079. */
  5080. public function pickReview()
  5081. {
  5082. if ($this->request->isPost()) {
  5083. $this->error('请使用弹窗内「确认下发」提交');
  5084. }
  5085. $this->view->assign('pickMode', 1);
  5086. return $this->view->fetch('procuremen/review');
  5087. }
  5088. /**
  5089. * 协助新增(独立页面)
  5090. */
  5091. public function add()
  5092. {
  5093. if ($this->request->isPost()) {
  5094. $params = $this->request->post('row/a');
  5095. if (!is_array($params)) {
  5096. $this->error(__('Parameter %s can not be empty', ''));
  5097. }
  5098. [, $adminName] = $this->GetUseName();
  5099. $params['cywyxm'] = $adminName;
  5100. try {
  5101. $sid = $this->saveManualPickOrder($params);
  5102. } catch (\InvalidArgumentException $e) {
  5103. $this->error($e->getMessage());
  5104. } catch (\Throwable $e) {
  5105. $this->error($e->getMessage());
  5106. }
  5107. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5108. }
  5109. [, $adminName] = $this->GetUseName();
  5110. $this->view->assign('adminNickname', $adminName);
  5111. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  5112. return $this->view->fetch();
  5113. }
  5114. /**
  5115. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  5116. */
  5117. public function rfqlist()
  5118. {
  5119. $this->relationSearch = false;
  5120. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  5121. $this->request->filter(['strip_tags', 'trim']);
  5122. if ($this->request->isAjax()) {
  5123. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  5124. $limit = max(10, min(500, (int)$limit));
  5125. $applyFilters = function ($query) use ($where) {
  5126. $query->where('scydgy_id', '<', 0);
  5127. $query->whereRaw(
  5128. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  5129. );
  5130. if (!$this->auth->isSuperAdmin()) {
  5131. [, $adminName] = $this->GetUseName();
  5132. $query->where('cywyxm', $adminName);
  5133. }
  5134. if (!empty($where)) {
  5135. $query->where($where);
  5136. }
  5137. };
  5138. $countQuery = Db::table('purchase_order');
  5139. $applyFilters($countQuery);
  5140. $total = (int)$countQuery->count();
  5141. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  5142. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  5143. $listQuery = Db::table('purchase_order');
  5144. $applyFilters($listQuery);
  5145. $rows = $listQuery
  5146. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  5147. ->order($sortField, $orderDir)
  5148. ->limit($offset, $limit)
  5149. ->select();
  5150. if (!is_array($rows)) {
  5151. $rows = [];
  5152. }
  5153. $out = [];
  5154. foreach ($rows as $r) {
  5155. if (!is_array($r)) {
  5156. continue;
  5157. }
  5158. $sid = (int)($r['scydgy_id'] ?? 0);
  5159. if ($sid >= 0) {
  5160. continue;
  5161. }
  5162. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  5163. if ($createdText === '') {
  5164. $createdText = trim((string)($r['dStamp'] ?? ''));
  5165. }
  5166. $out[] = [
  5167. 'id' => (int)($r['id'] ?? 0),
  5168. 'scydgy_id' => $sid,
  5169. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5170. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5171. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  5172. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5173. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  5174. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  5175. 'createtime' => $r['createtime'] ?? null,
  5176. 'createtime_text' => $createdText,
  5177. ];
  5178. }
  5179. return json(['total' => $total, 'rows' => $out]);
  5180. }
  5181. [, $adminName] = $this->GetUseName();
  5182. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  5183. $this->view->assign('adminNickname', $adminName);
  5184. return $this->view->fetch('procuremen/rfqlist');
  5185. }
  5186. /**
  5187. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  5188. */
  5189. public function rfqlistDetails()
  5190. {
  5191. return $this->details();
  5192. }
  5193. /**
  5194. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  5195. */
  5196. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  5197. {
  5198. if ($scydgyId >= 0) {
  5199. return;
  5200. }
  5201. try {
  5202. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5203. } catch (\Throwable $e) {
  5204. $po = null;
  5205. }
  5206. if (!is_array($po)) {
  5207. $this->error('订单不存在');
  5208. }
  5209. $modRq = trim((string)($po['mod_rq'] ?? ''));
  5210. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  5211. $this->error('订单不存在');
  5212. }
  5213. if ($this->auth->isSuperAdmin()) {
  5214. return;
  5215. }
  5216. [, $adminName] = $this->GetUseName();
  5217. $cywy = trim((string)($po['cywyxm'] ?? ''));
  5218. if ($cywy !== '' && $cywy === $adminName) {
  5219. return;
  5220. }
  5221. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  5222. try {
  5223. if ($this->auth->check($rule)) {
  5224. return;
  5225. }
  5226. } catch (\Throwable $e) {
  5227. }
  5228. }
  5229. $this->error('无权查看该订单');
  5230. }
  5231. /**
  5232. * @deprecated 使用 {@see assertManualOrderDetailsViewable}
  5233. */
  5234. protected function assertRfqRowViewable(int $scydgyId): void
  5235. {
  5236. $this->assertManualOrderDetailsViewable($scydgyId);
  5237. }
  5238. /**
  5239. * 手工新增协助工序进度文案
  5240. */
  5241. protected function formatProcuremenRfqProgressText(array $row): string
  5242. {
  5243. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  5244. return ProcuremenStatus::PO_COMPLETED;
  5245. }
  5246. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  5247. return '待采购确认';
  5248. }
  5249. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  5250. return '待确认供应商';
  5251. }
  5252. $sid = (int)($row['scydgy_id'] ?? 0);
  5253. if ($sid < 0) {
  5254. try {
  5255. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  5256. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  5257. $detCnt = (int)$detCntQuery->count();
  5258. if ($detCnt > 0) {
  5259. return '已下发待确认';
  5260. }
  5261. } catch (\Throwable $e) {
  5262. }
  5263. }
  5264. return '待协助下发';
  5265. }
  5266. /**
  5267. * 协助初选列表 — 批量软删除
  5268. */
  5269. public function pickDelete()
  5270. {
  5271. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5272. $this->error(__('Invalid parameters'));
  5273. }
  5274. $rowsRaw = $this->request->post('rows_json', '[]');
  5275. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  5276. if (!is_array($rows) || $rows === []) {
  5277. $this->error('请至少勾选一条工序');
  5278. }
  5279. $done = 0;
  5280. Db::startTrans();
  5281. try {
  5282. foreach ($rows as $row) {
  5283. if (!is_array($row)) {
  5284. continue;
  5285. }
  5286. $this->softDeleteProcuremenPickRow($row);
  5287. $done++;
  5288. }
  5289. if ($done < 1) {
  5290. throw new \Exception('没有可删除的工序');
  5291. }
  5292. Db::commit();
  5293. } catch (\InvalidArgumentException $e) {
  5294. Db::rollback();
  5295. $this->error($e->getMessage());
  5296. } catch (\Throwable $e) {
  5297. Db::rollback();
  5298. $this->error($e->getMessage());
  5299. }
  5300. $this->success('已删除 ' . $done . ' 条工序');
  5301. }
  5302. /**
  5303. * 协助下发 — 手工新增工序(弹窗)
  5304. */
  5305. public function pickAdd()
  5306. {
  5307. if ($this->request->isPost()) {
  5308. $params = $this->request->post('row/a');
  5309. if (!is_array($params)) {
  5310. $this->error(__('Parameter %s can not be empty', ''));
  5311. }
  5312. try {
  5313. $sid = $this->saveManualPickOrder($params);
  5314. } catch (\InvalidArgumentException $e) {
  5315. $this->error($e->getMessage());
  5316. } catch (\Throwable $e) {
  5317. $this->error($e->getMessage());
  5318. }
  5319. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5320. }
  5321. return $this->view->fetch('procuremen/pick_add');
  5322. }
  5323. /**
  5324. * 协助下发提交 — 弹窗「确认下发」→ POST procuremen/picksubmit
  5325. */
  5326. public function pickSubmit()
  5327. {
  5328. if (!$this->request->isPost()) {
  5329. $this->error(__('Invalid parameters'));
  5330. }
  5331. // ---------- 接口订单数据 ----------
  5332. $rowJson = $this->request->post('row_json', '');
  5333. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  5334. $companiesJson = $this->request->post('companies_json', '[]');
  5335. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  5336. $companies = json_decode($companiesJson, true);
  5337. if (!is_array($companies)) {
  5338. $this->error('供应商数据无效');
  5339. }
  5340. $issueCompanies = $this->normalizePickCompanies($companies);
  5341. if ($issueCompanies === []) {
  5342. $this->error('请至少选择一家合作供应商');
  5343. }
  5344. $issueNameLabels = [];
  5345. foreach ($issueCompanies as $pc) {
  5346. $issueNameLabels[] = $pc['name'];
  5347. }
  5348. $issueNamesSummary = implode('、', $issueNameLabels);
  5349. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  5350. if ($sysRq === '') {
  5351. $this->error('请选择截止时间');
  5352. }
  5353. $sysRqTs = strtotime($sysRq);
  5354. if ($sysRqTs === false || $sysRqTs <= 0) {
  5355. $this->error('截止时间格式无效');
  5356. }
  5357. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  5358. $isMerge = count($mergeRows) > 1;
  5359. $logMsg = ($isMerge ? '合并协助初选(' . count($mergeRows) . ' 道工序)' : '协助初选')
  5360. . ',通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  5361. $issueTime = date('Y-m-d H:i:s');
  5362. $logSidList = [];
  5363. foreach ($mergeRows as $row) {
  5364. if (!is_array($row)) {
  5365. continue;
  5366. }
  5367. $sid = $this->extractScydgyRowId($row);
  5368. if ($this->isValidScydgyRowId($sid)) {
  5369. $logSidList[$sid] = true;
  5370. }
  5371. }
  5372. $existingBySid = [];
  5373. if ($logSidList !== []) {
  5374. try {
  5375. $existingRows = Db::table('purchase_order')
  5376. ->where('scydgy_id', 'in', array_keys($logSidList))
  5377. ->select();
  5378. if (is_array($existingRows)) {
  5379. foreach ($existingRows as $poRow) {
  5380. if (!is_array($poRow)) {
  5381. continue;
  5382. }
  5383. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5384. if ($this->isValidScydgyRowId($sid)) {
  5385. $existingBySid[$sid] = $poRow;
  5386. }
  5387. }
  5388. }
  5389. } catch (\Throwable $e) {
  5390. $existingBySid = [];
  5391. }
  5392. }
  5393. Db::startTrans();
  5394. try {
  5395. // ---------- 主表 wflow_status=1;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  5396. foreach ($mergeRows as $row) {
  5397. if (!is_array($row)) {
  5398. continue;
  5399. }
  5400. $sid = $this->extractScydgyRowId($row);
  5401. $this->upsertPurchaseOrderFromRow(
  5402. $row,
  5403. $sysRqDb,
  5404. 1,
  5405. $issueTime,
  5406. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  5407. );
  5408. }
  5409. foreach ($issueCompanies as $c) {
  5410. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  5411. }
  5412. Db::commit();
  5413. } catch (\Throwable $e) {
  5414. Db::rollback();
  5415. $this->error($e->getMessage());
  5416. }
  5417. $poIdBySid = [];
  5418. if ($logSidList !== []) {
  5419. try {
  5420. $poIdBySid = Db::table('purchase_order')
  5421. ->where('scydgy_id', 'in', array_keys($logSidList))
  5422. ->column('id', 'scydgy_id');
  5423. } catch (\Throwable $e) {
  5424. $poIdBySid = [];
  5425. }
  5426. }
  5427. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  5428. if ($logSidList !== []) {
  5429. list($adminId, $adminName) = $this->GetUseName();
  5430. $cut = function ($s, $max) {
  5431. if (function_exists('mb_substr')) {
  5432. return mb_substr($s, 0, $max, 'UTF-8');
  5433. }
  5434. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  5435. };
  5436. $logRows = [];
  5437. $seenLogSid = [];
  5438. foreach ($mergeRows as $row) {
  5439. if (!is_array($row)) {
  5440. continue;
  5441. }
  5442. $ids = $this->extractScydgyRowId($row);
  5443. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  5444. continue;
  5445. }
  5446. $seenLogSid[$ids] = true;
  5447. $poIdLog = null;
  5448. if (isset($poIdBySid[$ids])) {
  5449. $tid = (int)$poIdBySid[$ids];
  5450. $poIdLog = $tid > 0 ? $tid : null;
  5451. }
  5452. $logRows[] = [
  5453. 'scydgy_id' => $ids,
  5454. 'purchase_order_id' => $poIdLog,
  5455. 'admin_id' => $adminId,
  5456. 'admin_name' => $cut($adminName, 64),
  5457. 'action' => $cut('issue_submit', 64),
  5458. 'content' => $cut($logMsg, 1000),
  5459. 'createtime' => time(),
  5460. ];
  5461. }
  5462. if ($logRows !== []) {
  5463. try {
  5464. Db::table('purchase_order_oper_log')->insertAll($logRows);
  5465. } catch (\Throwable $e) {
  5466. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  5467. }
  5468. }
  5469. }
  5470. $notifyErrors = [];
  5471. $posNotify = [];
  5472. if ($logSidList !== []) {
  5473. try {
  5474. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  5475. } catch (\Throwable $e) {
  5476. $posNotify = [];
  5477. }
  5478. }
  5479. if (!is_array($posNotify)) {
  5480. $posNotify = [];
  5481. }
  5482. foreach ($posNotify as $i => $prow) {
  5483. if (is_array($posNotify[$i])) {
  5484. $posNotify[$i]['sys_rq'] = $sysRqDb;
  5485. }
  5486. }
  5487. $ccydhPick = '';
  5488. foreach ($mergeRows as $row) {
  5489. if (!is_array($row)) {
  5490. continue;
  5491. }
  5492. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  5493. if ($ccydhPick !== '') {
  5494. break;
  5495. }
  5496. }
  5497. $notifyBundleBase = [
  5498. 'ccydh' => $ccydhPick,
  5499. 'pos' => $posNotify,
  5500. 'merge_rows' => $mergeRows,
  5501. ];
  5502. try {
  5503. $this->notifyDryRunPreview = [];
  5504. foreach ($issueCompanies as $c) {
  5505. if (!is_array($c)) {
  5506. continue;
  5507. }
  5508. $cname = trim((string)($c['name'] ?? ''));
  5509. if ($cname === '') {
  5510. continue;
  5511. }
  5512. try {
  5513. $this->sendAuditSupplierConfirmNotify($c, $mergeRows, $notifyBundleBase);
  5514. } catch (\Throwable $e) {
  5515. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5516. }
  5517. }
  5518. } catch (\Throwable $e) {
  5519. $this->error('通知发送失败:' . $e->getMessage());
  5520. }
  5521. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  5522. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5523. }
  5524. if ($this->isProcuremenNotifyDryRun()) {
  5525. $this->success('【演练模式】已保存并生成通知预览', '', [
  5526. 'notify_dry_run' => true,
  5527. 'notify_preview' => $this->notifyDryRunPreview,
  5528. ]);
  5529. }
  5530. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  5531. }
  5532. /**
  5533. * 确认供应商弹窗
  5534. */
  5535. public function auditIssue()
  5536. {
  5537. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5538. if (is_array($ids)) {
  5539. $ids = isset($ids[0]) ? $ids[0] : '';
  5540. }
  5541. $ids = trim((string)$ids);
  5542. if ($ids === '') {
  5543. $this->error(__('Invalid parameters'));
  5544. }
  5545. if ($this->request->isPost()) {
  5546. $this->error('请使用弹窗内「确认」提交');
  5547. }
  5548. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  5549. $pos = $bundle['pos'];
  5550. if ($pos === []) {
  5551. $this->error('该订单不在待确认供应商状态');
  5552. }
  5553. $po = $pos[0];
  5554. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5555. if ($quoteGroups === []) {
  5556. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  5557. }
  5558. $pickedName = '';
  5559. foreach ($pos as $poRow) {
  5560. if (!is_array($poRow)) {
  5561. continue;
  5562. }
  5563. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  5564. if ($pn !== '') {
  5565. $pickedName = $pn;
  5566. break;
  5567. }
  5568. }
  5569. $this->view->assign('po', $po);
  5570. $this->view->assign('scydgyId', $ids);
  5571. $this->view->assign('orderCcydh', $bundle['ccydh']);
  5572. $mergeRows = $bundle['merge_rows'];
  5573. $this->view->assign('processRows', $mergeRows);
  5574. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  5575. $this->view->assign('processCount', count($mergeRows));
  5576. $this->view->assign('quoteGroups', $quoteGroups);
  5577. $this->view->assign('quoteGroupsJson', json_encode($quoteGroups, JSON_UNESCAPED_UNICODE));
  5578. $this->view->assign('pickedCompanyName', $pickedName);
  5579. $this->view->assign('sysRq', $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null));
  5580. return $this->view->fetch('procuremen/audit_issue');
  5581. }
  5582. /**
  5583. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  5584. */
  5585. public function auditSubmit()
  5586. {
  5587. if (!$this->request->isPost()) {
  5588. $this->error(__('Invalid parameters'));
  5589. }
  5590. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5591. if ($scydgyId === '') {
  5592. $this->error('参数无效');
  5593. }
  5594. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5595. $pos = $bundle['pos'];
  5596. $mergeRows = $bundle['merge_rows'];
  5597. if ($pos === [] || $mergeRows === []) {
  5598. $this->error('该订单不在待确认供应商状态');
  5599. }
  5600. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5601. if ($quoteGroups === []) {
  5602. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  5603. }
  5604. $companyName = trim((string)$this->request->post('selected_company', ''));
  5605. if ($companyName === '') {
  5606. $this->error('请选择一家供应商');
  5607. }
  5608. $matched = null;
  5609. foreach ($quoteGroups as $g) {
  5610. if (!is_array($g)) {
  5611. continue;
  5612. }
  5613. if (trim((string)($g['name'] ?? '')) === $companyName) {
  5614. $matched = $g;
  5615. break;
  5616. }
  5617. }
  5618. if ($matched === null) {
  5619. $this->error('所选供应商不在本单报价列表中');
  5620. }
  5621. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  5622. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5623. $procCnt = count($mergeRows);
  5624. $logMsg = '确认供应商(订单' . ($ccydhLog !== '' ? $ccydhLog : '')
  5625. . ($procCnt > 1 ? ',' . $procCnt . ' 道工序' : '')
  5626. . '),选定:' . $companyName;
  5627. Db::startTrans();
  5628. try {
  5629. foreach ($pos as $poRow) {
  5630. if (!is_array($poRow)) {
  5631. continue;
  5632. }
  5633. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5634. if (!$this->isValidScydgyRowId($sid)) {
  5635. continue;
  5636. }
  5637. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  5638. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  5639. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5640. 'pick_company_name' => $companyName,
  5641. 'sys_rq' => $sysRqDb,
  5642. ]);
  5643. }
  5644. Db::commit();
  5645. } catch (\Throwable $e) {
  5646. Db::rollback();
  5647. $this->error($e->getMessage());
  5648. }
  5649. foreach ($pos as $poRow) {
  5650. if (!is_array($poRow)) {
  5651. continue;
  5652. }
  5653. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5654. if (!$this->isValidScydgyRowId($sid)) {
  5655. continue;
  5656. }
  5657. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  5658. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  5659. }
  5660. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  5661. }
  5662. /**
  5663. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  5664. */
  5665. public function auditResendSms()
  5666. {
  5667. if (!$this->request->isPost()) {
  5668. $this->error(__('Invalid parameters'));
  5669. }
  5670. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5671. if ($scydgyId === '') {
  5672. $this->error('参数无效');
  5673. }
  5674. $loaded = $this->loadAuditResendBundle($scydgyId);
  5675. $mergeRows = $loaded['merge_rows'];
  5676. $bundle = $loaded['bundle'];
  5677. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5678. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5679. if ($quoteGroups === []) {
  5680. $this->error('暂无可通知的供应商');
  5681. }
  5682. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5683. $companiesJson = (string)$this->request->post('companies_json', '');
  5684. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5685. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  5686. }
  5687. /**
  5688. * 确认供应商 — 二次发送邮件(可选单家/批量)
  5689. */
  5690. public function auditResendEmail()
  5691. {
  5692. if (!$this->request->isPost()) {
  5693. $this->error(__('Invalid parameters'));
  5694. }
  5695. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5696. if ($scydgyId === '') {
  5697. $this->error('参数无效');
  5698. }
  5699. $loaded = $this->loadAuditResendBundle($scydgyId);
  5700. $mergeRows = $loaded['merge_rows'];
  5701. $bundle = $loaded['bundle'];
  5702. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5703. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5704. if ($quoteGroups === []) {
  5705. $this->error('暂无可通知的供应商');
  5706. }
  5707. $companiesJson = (string)$this->request->post('companies_json', '');
  5708. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5709. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5710. if ($companiesJson === '' && $selectedCompany === '') {
  5711. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  5712. }
  5713. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  5714. }
  5715. /**
  5716. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  5717. *
  5718. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  5719. * @return array<int, true> 已处理的 scydgy_id 集合
  5720. */
  5721. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  5722. {
  5723. $pos = $bundle['pos'] ?? [];
  5724. if (!is_array($pos) || $pos === []) {
  5725. return [];
  5726. }
  5727. $sids = [];
  5728. foreach ($pos as $poRow) {
  5729. if (!is_array($poRow)) {
  5730. continue;
  5731. }
  5732. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5733. if ($this->isValidScydgyRowId($sid)) {
  5734. $sids[$sid] = true;
  5735. }
  5736. }
  5737. if ($sids === []) {
  5738. return [];
  5739. }
  5740. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5741. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '') . $logSuffix;
  5742. Db::table('purchase_order')
  5743. ->where('scydgy_id', 'in', array_keys($sids))
  5744. ->update([
  5745. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  5746. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5747. 'pick_company_name' => '',
  5748. 'pick_time' => null,
  5749. 'sys_rq' => null,
  5750. 'mod_rq' => null,
  5751. ]);
  5752. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  5753. foreach (array_keys($sids) as $sid) {
  5754. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  5755. }
  5756. return $sids;
  5757. }
  5758. /**
  5759. * 废弃单个审批订单 bundle(退回协助初选,明细归档留痕)
  5760. *
  5761. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  5762. * @return array<int, true> 已处理的 scydgy_id 集合
  5763. */
  5764. protected function abandonAuditOrderBundle(array $bundle): array
  5765. {
  5766. return $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  5767. }
  5768. /**
  5769. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  5770. *
  5771. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5772. */
  5773. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  5774. {
  5775. $scydgyId = trim($scydgyId);
  5776. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5777. if ($scydgyId === '') {
  5778. return $empty;
  5779. }
  5780. try {
  5781. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5782. } catch (\Throwable $e) {
  5783. $anchor = null;
  5784. }
  5785. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  5786. return $empty;
  5787. }
  5788. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5789. if ($ccydh === '') {
  5790. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  5791. }
  5792. try {
  5793. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  5794. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  5795. $pos = $query->order('scydgy_id', 'asc')->select();
  5796. } catch (\Throwable $e) {
  5797. $pos = [$anchor];
  5798. }
  5799. if (!is_array($pos) || $pos === []) {
  5800. $pos = [$anchor];
  5801. }
  5802. return [
  5803. 'ccydh' => $ccydh,
  5804. 'pos' => $pos,
  5805. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5806. ];
  5807. }
  5808. protected function purchaseOrderRowIsCompleted(array $po): bool
  5809. {
  5810. $st = $po['status'] ?? null;
  5811. if ($st === 1 || $st === '1') {
  5812. return true;
  5813. }
  5814. if (is_string($st) && trim($st) === '1') {
  5815. return true;
  5816. }
  5817. return is_numeric($st) && (int)$st === 1;
  5818. }
  5819. /**
  5820. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  5821. */
  5822. public function auditAbandon()
  5823. {
  5824. if (!$this->request->isPost()) {
  5825. $this->error(__('Invalid parameters'));
  5826. }
  5827. $anchorIds = [];
  5828. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  5829. if ($batchRaw !== '') {
  5830. $decoded = json_decode($batchRaw, true);
  5831. if (is_array($decoded)) {
  5832. foreach ($decoded as $id) {
  5833. $s = trim((string)$id);
  5834. if ($s !== '') {
  5835. $anchorIds[] = $s;
  5836. }
  5837. }
  5838. }
  5839. }
  5840. if ($anchorIds === []) {
  5841. $single = trim((string)$this->request->post('scydgy_id', ''));
  5842. if ($single !== '') {
  5843. $anchorIds[] = $single;
  5844. }
  5845. }
  5846. if ($anchorIds === []) {
  5847. $this->error('请至少选择一条订单');
  5848. }
  5849. $processedCcydh = [];
  5850. $doneOrders = 0;
  5851. $allSids = [];
  5852. Db::startTrans();
  5853. try {
  5854. foreach ($anchorIds as $anchorId) {
  5855. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  5856. if (($bundle['pos'] ?? []) === []) {
  5857. continue;
  5858. }
  5859. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5860. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  5861. if (isset($processedCcydh[$dedupeKey])) {
  5862. continue;
  5863. }
  5864. $processedCcydh[$dedupeKey] = true;
  5865. $sids = $this->abandonAuditOrderBundle($bundle);
  5866. if ($sids === []) {
  5867. continue;
  5868. }
  5869. $doneOrders++;
  5870. foreach (array_keys($sids) as $sid) {
  5871. $allSids[(int)$sid] = true;
  5872. }
  5873. }
  5874. if ($doneOrders < 1) {
  5875. throw new \Exception('所选订单均不在待确认供应商状态');
  5876. }
  5877. Db::commit();
  5878. } catch (\Throwable $e) {
  5879. Db::rollback();
  5880. $this->error($e->getMessage());
  5881. }
  5882. $this->pickHiddenScydgySetCache = null;
  5883. $msg = $doneOrders > 1
  5884. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  5885. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  5886. $this->success($msg);
  5887. }
  5888. /**
  5889. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  5890. */
  5891. public function archiveAbandon()
  5892. {
  5893. if (!$this->request->isPost()) {
  5894. $this->error(__('Invalid parameters'));
  5895. }
  5896. $anchorIds = [];
  5897. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  5898. if ($batchRaw !== '') {
  5899. $decoded = json_decode($batchRaw, true);
  5900. if (is_array($decoded)) {
  5901. foreach ($decoded as $id) {
  5902. $s = trim((string)$id);
  5903. if ($s !== '') {
  5904. $anchorIds[] = $s;
  5905. }
  5906. }
  5907. }
  5908. }
  5909. if ($anchorIds === []) {
  5910. $single = trim((string)$this->request->post('scydgy_id', ''));
  5911. if ($single !== '') {
  5912. $anchorIds[] = $single;
  5913. }
  5914. }
  5915. if ($anchorIds === []) {
  5916. $this->error('请至少选择一条订单');
  5917. }
  5918. $processedCcydh = [];
  5919. $doneOrders = 0;
  5920. Db::startTrans();
  5921. try {
  5922. foreach ($anchorIds as $anchorId) {
  5923. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  5924. if (($bundle['pos'] ?? []) === []) {
  5925. continue;
  5926. }
  5927. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5928. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  5929. if (isset($processedCcydh[$dedupeKey])) {
  5930. continue;
  5931. }
  5932. $processedCcydh[$dedupeKey] = true;
  5933. $sids = $this->abandonOrderBundleToPick(
  5934. $bundle,
  5935. 'archive_abandon',
  5936. ',从历史存证退回协助初选'
  5937. );
  5938. if ($sids === []) {
  5939. continue;
  5940. }
  5941. $doneOrders++;
  5942. }
  5943. if ($doneOrders < 1) {
  5944. throw new \Exception('所选订单均不是已完结状态');
  5945. }
  5946. Db::commit();
  5947. } catch (\Throwable $e) {
  5948. Db::rollback();
  5949. $this->error($e->getMessage());
  5950. }
  5951. $this->pickHiddenScydgySetCache = null;
  5952. $msg = $doneOrders > 1
  5953. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  5954. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  5955. $this->success($msg);
  5956. }
  5957. /**
  5958. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  5959. */
  5960. public function purchaseApprovalReject()
  5961. {
  5962. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5963. $this->error(__('Invalid parameters'));
  5964. }
  5965. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  5966. $decoded = json_decode($batchRaw, true);
  5967. if (!is_array($decoded) || $decoded === []) {
  5968. $this->error('提交数据无效');
  5969. }
  5970. Db::startTrans();
  5971. try {
  5972. foreach ($decoded as $item) {
  5973. if (!is_array($item)) {
  5974. continue;
  5975. }
  5976. $sid = (int)($item['scydgy_id'] ?? 0);
  5977. if (!$this->isValidScydgyRowId($sid)) {
  5978. continue;
  5979. }
  5980. $this->runPurchaseApprovalRejectForSid($sid);
  5981. }
  5982. Db::commit();
  5983. } catch (\Throwable $e) {
  5984. Db::rollback();
  5985. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  5986. }
  5987. $this->success('已驳回并退回「协助审批下发」');
  5988. }
  5989. /**
  5990. * @throws \Exception
  5991. */
  5992. protected function runPurchaseApprovalRejectForSid(int $sid): void
  5993. {
  5994. $allIds = $this->purchaseOrderDetail($sid);
  5995. if ($allIds === []) {
  5996. throw new \Exception('未找到下发明细');
  5997. }
  5998. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  5999. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6000. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6001. 'pick_company_name' => '',
  6002. ]);
  6003. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  6004. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  6005. $poId = 0;
  6006. try {
  6007. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6008. if (is_array($po)) {
  6009. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6010. }
  6011. } catch (\Throwable $e) {
  6012. }
  6013. $this->addOrderLog($sid, 'purchase_reject', '采购终审驳回,退回协助审批下发', $poId > 0 ? $poId : null);
  6014. }
  6015. /**
  6016. * 审核弹窗(旧入口,POST 已关闭)
  6017. */
  6018. public function review()
  6019. {
  6020. if ($this->request->isPost()) {
  6021. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  6022. }
  6023. $this->view->assign('pickMode', 0);
  6024. return $this->view->fetch('procuremen/review');
  6025. }
  6026. /**
  6027. * 审核弹窗获取公司列表
  6028. */
  6029. public function reviewCompanies()
  6030. {
  6031. if (!$this->request->isAjax()) {
  6032. $this->error(__('Invalid parameters'));
  6033. }
  6034. $list = [];
  6035. try {
  6036. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  6037. $rows = Db::table('customer')
  6038. ->where(function ($q) {
  6039. $q->where('status', 1)
  6040. ->whereOr('status', '1')
  6041. ->whereOr('status', '')
  6042. ->whereNull('status');
  6043. })
  6044. ->order('id', 'desc')
  6045. ->select();
  6046. } catch (\Throwable $e) {
  6047. $this->success('', '', []);
  6048. return;
  6049. }
  6050. if (!is_array($rows)) {
  6051. $this->success('', '', []);
  6052. return;
  6053. }
  6054. $detailColCandidates = [
  6055. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  6056. 'company_detail', 'company_desc', 'address',
  6057. ];
  6058. foreach ($rows as $row) {
  6059. if (!is_array($row)) {
  6060. continue;
  6061. }
  6062. $norm = [];
  6063. foreach ($row as $k => $v) {
  6064. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6065. }
  6066. $row = $norm;
  6067. $st = $row['status'] ?? '';
  6068. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6069. continue;
  6070. }
  6071. $id = isset($row['id']) ? (string)$row['id'] : '';
  6072. $companyName = '';
  6073. foreach (['company_name', 'name'] as $nk) {
  6074. if (!empty($row[$nk])) {
  6075. $companyName = trim((string)$row[$nk]);
  6076. break;
  6077. }
  6078. }
  6079. $username = '';
  6080. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6081. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6082. $username = trim((string)$row[$uk]);
  6083. break;
  6084. }
  6085. }
  6086. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6087. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6088. if ($phone === '' && isset($row['account'])) {
  6089. $phone = trim((string)$row['account']);
  6090. }
  6091. if ($phone === '' && isset($row['mobile'])) {
  6092. $phone = trim((string)$row['mobile']);
  6093. }
  6094. /* 邮箱、手机号均为空则无法发短信/邮件,不在下发弹窗展示 */
  6095. if ($email === '' && $phone === '') {
  6096. continue;
  6097. }
  6098. $category = '';
  6099. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6100. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6101. $category = trim((string)$row[$ck]);
  6102. break;
  6103. }
  6104. }
  6105. $detail = '';
  6106. foreach ($detailColCandidates as $dk) {
  6107. if (!isset($row[$dk])) {
  6108. continue;
  6109. }
  6110. $dv = trim((string)$row[$dk]);
  6111. if ($dv !== '') {
  6112. $detail = $dv;
  6113. break;
  6114. }
  6115. }
  6116. $list[] = [
  6117. 'id' => $id,
  6118. 'name' => $companyName,
  6119. 'company_name' => $companyName,
  6120. 'username' => $username,
  6121. 'email' => $email,
  6122. 'phone' => $phone,
  6123. 'category' => $category,
  6124. 'company_type' => $category,
  6125. 'detail' => $detail,
  6126. ];
  6127. }
  6128. $this->success('', '', $list);
  6129. }
  6130. /**
  6131. * 采购确认-下发明细弹窗:
  6132. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  6133. */
  6134. public function outward_detail()
  6135. {
  6136. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6137. if (is_array($ids)) {
  6138. $ids = isset($ids[0]) ? $ids[0] : '';
  6139. }
  6140. $ids = trim((string)$ids);
  6141. if ($ids === '') {
  6142. $this->error(__('Invalid parameters'));
  6143. }
  6144. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  6145. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  6146. $wffTab = 'all';
  6147. }
  6148. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  6149. $purchaseOrderId = 0;
  6150. $po = null;
  6151. try {
  6152. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6153. if (is_array($po)) {
  6154. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6155. }
  6156. } catch (\Throwable $e) {
  6157. $purchaseOrderId = 0;
  6158. $po = null;
  6159. }
  6160. if (!$isPurchaseConfirm && is_array($po)) {
  6161. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  6162. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  6163. $isPurchaseConfirm = true;
  6164. }
  6165. }
  6166. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  6167. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6168. $confirmProcessCount = 1;
  6169. $confirmPickGroups = [];
  6170. $processDisplayRows = [];
  6171. $allDetailsBySid = [];
  6172. $requiredSidList = [];
  6173. $sidList = [$ids];
  6174. if ($isPurchaseConfirm) {
  6175. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  6176. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  6177. if ($mergeRows !== []) {
  6178. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6179. }
  6180. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  6181. if ($confirmBundle['pos'] !== []) {
  6182. $sidList = [];
  6183. foreach ($confirmBundle['pos'] as $poRow) {
  6184. if (!is_array($poRow)) {
  6185. continue;
  6186. }
  6187. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6188. if (!$this->isValidScydgyRowId($sid)) {
  6189. continue;
  6190. }
  6191. $sidList[] = (string)$sid;
  6192. $requiredSidList[] = $sid;
  6193. }
  6194. }
  6195. if ($sidList === []) {
  6196. $sidList = [$ids];
  6197. $requiredSidList = [(int)$ids];
  6198. }
  6199. $confirmProcessCount = max(1, count($requiredSidList));
  6200. if (is_array($po) && $purchaseOrderId <= 0) {
  6201. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6202. }
  6203. }
  6204. $rows = [];
  6205. try {
  6206. if (count($sidList) === 1) {
  6207. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  6208. } else {
  6209. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  6210. }
  6211. } catch (\Throwable $e) {
  6212. $rows = [];
  6213. }
  6214. if ($isPurchaseConfirm) {
  6215. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  6216. }
  6217. foreach ($rows as &$r) {
  6218. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  6219. $r['id'] = $r['ID'];
  6220. }
  6221. if (isset($r['createtime'])) {
  6222. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  6223. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  6224. } else {
  6225. $r['createtime_text'] = (string)$r['createtime'];
  6226. }
  6227. } else {
  6228. $r['createtime_text'] = '';
  6229. }
  6230. }
  6231. unset($r);
  6232. $pickedCompanyName = '';
  6233. if ($isPurchaseConfirm) {
  6234. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  6235. if (!is_array($poRow)) {
  6236. continue;
  6237. }
  6238. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6239. if ($pn !== '') {
  6240. $pickedCompanyName = $pn;
  6241. break;
  6242. }
  6243. }
  6244. }
  6245. $this->view->assign('rows', $rows ?: []);
  6246. $this->view->assign('rowCount', count($rows ?: []));
  6247. $this->view->assign('scydgyId', $ids);
  6248. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  6249. $this->view->assign('headTitle', $headTitle);
  6250. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  6251. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  6252. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  6253. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  6254. $this->view->assign('processDisplayRows', $processDisplayRows);
  6255. $this->view->assign('confirmPickGroups', $confirmPickGroups);
  6256. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  6257. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  6258. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  6259. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  6260. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  6261. if ($isPurchaseConfirm) {
  6262. return $this->view->fetch();
  6263. }
  6264. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6265. $this->view->engine->layout(false);
  6266. try {
  6267. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  6268. $this->view->assign('dialogBody', $bodyHtml);
  6269. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  6270. } finally {
  6271. if ($restoreLayout) {
  6272. $this->view->engine->layout($restoreLayout);
  6273. }
  6274. }
  6275. }
  6276. /**
  6277. * 月度导出记录表(不存在时自动创建)
  6278. */
  6279. protected function ensurePurchaseMonthExportLogTable(): void
  6280. {
  6281. try {
  6282. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  6283. } catch (\Throwable $e) {
  6284. Db::execute(
  6285. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  6286. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  6287. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  6288. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  6289. `admin_name` varchar(64) NOT NULL DEFAULT '',
  6290. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  6291. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  6292. `createtime` int(10) unsigned DEFAULT NULL,
  6293. PRIMARY KEY (`id`),
  6294. KEY `idx_ym` (`ym`),
  6295. KEY `idx_ct` (`createtime`)
  6296. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  6297. );
  6298. }
  6299. }
  6300. /**
  6301. * 已完结订单归属月份(与历史存证、月度列表一致)
  6302. *
  6303. * @param array<string, mixed> $row purchase_order 行
  6304. */
  6305. protected function resolveCompletedPurchaseOrderYm(array $row, array $completeTsMap = []): string
  6306. {
  6307. $sid = (int)($row['scydgy_id'] ?? 0);
  6308. if ($sid > 0 && isset($completeTsMap[$sid]) && (int)$completeTsMap[$sid] > 946684800) {
  6309. return date('Y-m', (int)$completeTsMap[$sid]);
  6310. }
  6311. if ($sid > 0) {
  6312. $logTs = $this->resolveProcuremenOperLogTime($sid, ['purchase_confirm', 'mark_complete']);
  6313. if ($logTs !== '' && preg_match('/^(\d{4}-\d{2})/', $logTs, $m)) {
  6314. return $m[1];
  6315. }
  6316. }
  6317. foreach (['updatetime', 'createtime', 'dStamp'] as $key) {
  6318. $raw = $row[$key] ?? null;
  6319. if ($raw === null || $raw === '') {
  6320. continue;
  6321. }
  6322. if (is_numeric($raw) && (int)$raw > 946684800) {
  6323. return date('Y-m', (int)$raw);
  6324. }
  6325. $t = trim((string)$raw);
  6326. if ($t !== '' && preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  6327. return $m[1];
  6328. }
  6329. }
  6330. return '';
  6331. }
  6332. /**
  6333. * @param array<int, string> $actions
  6334. * @return array<int, int>
  6335. */
  6336. protected function loadProcuremenOperLogTimestampMap(array $scydgyIds, array $actions): array
  6337. {
  6338. $out = [];
  6339. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  6340. $actions = array_values(array_filter(array_map('strval', $actions)));
  6341. if ($scydgyIds === [] || $actions === []) {
  6342. return $out;
  6343. }
  6344. try {
  6345. $logs = Db::table('purchase_order_oper_log')
  6346. ->where('scydgy_id', 'in', $scydgyIds)
  6347. ->where('action', 'in', $actions)
  6348. ->field('scydgy_id,createtime')
  6349. ->order('id', 'asc')
  6350. ->select();
  6351. } catch (\Throwable $e) {
  6352. $logs = [];
  6353. }
  6354. if (!is_array($logs)) {
  6355. return $out;
  6356. }
  6357. foreach ($logs as $log) {
  6358. if (!is_array($log)) {
  6359. continue;
  6360. }
  6361. $sid = (int)($log['scydgy_id'] ?? 0);
  6362. $ct = (int)($log['createtime'] ?? 0);
  6363. if ($sid > 0 && $ct > 946684800) {
  6364. $out[$sid] = isset($out[$sid]) ? max($out[$sid], $ct) : $ct;
  6365. }
  6366. }
  6367. return $out;
  6368. }
  6369. /**
  6370. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  6371. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  6372. */
  6373. public function export_month_outward()
  6374. {
  6375. $this->request->filter(['strip_tags', 'trim']);
  6376. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  6377. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  6378. $ym = date('Y-m');
  6379. }
  6380. $dbRows = [];
  6381. try {
  6382. $query = Db::table('purchase_order');
  6383. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  6384. $dbRows = $query->select();
  6385. } catch (\Throwable $e) {
  6386. $dbRows = [];
  6387. }
  6388. if (!is_array($dbRows)) {
  6389. $dbRows = [];
  6390. }
  6391. $completeTsMap = [];
  6392. $sidList = [];
  6393. foreach ($dbRows as $dbRow) {
  6394. if (!is_array($dbRow)) {
  6395. continue;
  6396. }
  6397. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  6398. if ($sid > 0) {
  6399. $sidList[$sid] = true;
  6400. }
  6401. }
  6402. if ($sidList !== []) {
  6403. $completeTsMap = $this->loadProcuremenOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  6404. }
  6405. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  6406. if (!is_array($dbRow)) {
  6407. return false;
  6408. }
  6409. return $this->resolveCompletedPurchaseOrderYm($dbRow, $completeTsMap) === $ym;
  6410. }));
  6411. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  6412. $filtered = $pool;
  6413. $mainBySid = [];
  6414. foreach ($filtered as $rw) {
  6415. if (!is_array($rw)) {
  6416. continue;
  6417. }
  6418. $rid = (int)($rw['ID'] ?? 0);
  6419. if ($rid > 0) {
  6420. $mainBySid[$rid] = $rw;
  6421. }
  6422. }
  6423. if ($mainBySid === []) {
  6424. $detailRows = [];
  6425. } else {
  6426. try {
  6427. $detailRows = Db::table('purchase_order_detail')
  6428. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6429. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  6430. ->order('status', 'desc')
  6431. ->order('CCYDH', 'asc')
  6432. ->order('company_name', 'asc')
  6433. ->order('id', 'asc')
  6434. ->select();
  6435. } catch (\Throwable $e) {
  6436. try {
  6437. $detailRows = Db::table('purchase_order_detail')
  6438. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6439. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  6440. ->order('status', 'desc')
  6441. ->order('CCYDH', 'asc')
  6442. ->order('company_name', 'asc')
  6443. ->order('ID', 'asc')
  6444. ->select();
  6445. } catch (\Throwable $e2) {
  6446. $detailRows = [];
  6447. }
  6448. }
  6449. }
  6450. if (!is_array($detailRows)) {
  6451. $detailRows = [];
  6452. }
  6453. $exportLines = [];
  6454. $detailSidSeen = [];
  6455. foreach ($detailRows as $dr) {
  6456. if (!is_array($dr)) {
  6457. continue;
  6458. }
  6459. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6460. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  6461. continue;
  6462. }
  6463. if (isset($detailSidSeen[$sid])) {
  6464. continue;
  6465. }
  6466. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6467. continue;
  6468. }
  6469. $detailSidSeen[$sid] = true;
  6470. $m = $mainBySid[$sid];
  6471. $exportLines[] = [
  6472. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6473. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6474. 'company_name' => (string)($dr['company_name'] ?? ''),
  6475. 'CDF' => (string)($m['CDF'] ?? ''),
  6476. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6477. 'gx' => $this->procuremenExportGxText($m),
  6478. 'detail' => $dr,
  6479. ];
  6480. }
  6481. foreach ($detailRows as $dr) {
  6482. if (!is_array($dr)) {
  6483. continue;
  6484. }
  6485. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6486. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  6487. continue;
  6488. }
  6489. $detailSidSeen[$sid] = true;
  6490. $m = $mainBySid[$sid];
  6491. $exportLines[] = [
  6492. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6493. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6494. 'company_name' => (string)($dr['company_name'] ?? ''),
  6495. 'CDF' => (string)($m['CDF'] ?? ''),
  6496. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6497. 'gx' => $this->procuremenExportGxText($m),
  6498. 'detail' => $dr,
  6499. ];
  6500. }
  6501. foreach ($mainBySid as $sid => $m) {
  6502. if (isset($detailSidSeen[$sid])) {
  6503. continue;
  6504. }
  6505. $company = trim((string)($m['pick_company_name'] ?? ''));
  6506. $exportLines[] = [
  6507. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  6508. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  6509. 'company_name' => $company,
  6510. 'CDF' => (string)($m['CDF'] ?? ''),
  6511. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6512. 'gx' => $this->procuremenExportGxText($m),
  6513. 'detail' => [],
  6514. ];
  6515. }
  6516. $groups = [];
  6517. foreach ($exportLines as $line) {
  6518. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  6519. if (!isset($groups[$k])) {
  6520. $groups[$k] = [];
  6521. }
  6522. $groups[$k][] = $line;
  6523. }
  6524. ksort($groups, SORT_STRING);
  6525. $spreadsheet = new Spreadsheet();
  6526. $sheet = $spreadsheet->getActiveSheet();
  6527. $sheet->setTitle('协助明细');
  6528. $mon = (int)substr($ym, 5, 2);
  6529. $sheet->mergeCells('A1:H1');
  6530. $sheet->setCellValue('A1', $mon . '月协助明细');
  6531. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  6532. $sheet->getStyle('A1')->getAlignment()
  6533. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  6534. ->setVertical(Alignment::VERTICAL_CENTER);
  6535. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  6536. $col = 'A';
  6537. foreach ($headers as $h) {
  6538. $sheet->setCellValue($col . '2', $h);
  6539. $col++;
  6540. }
  6541. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  6542. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6543. $rowNum = 3;
  6544. $sumSubtotalCounts = 0;
  6545. $grandAmount = 0.0;
  6546. if ($groups === []) {
  6547. $sheet->mergeCells('A3:H3');
  6548. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  6549. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6550. $rowNum = 4;
  6551. } else {
  6552. foreach ($groups as $items) {
  6553. if ($items === []) {
  6554. continue;
  6555. }
  6556. $groupLineCount = count($items);
  6557. $subAmount = 0.0;
  6558. $i = 0;
  6559. foreach ($items as $line) {
  6560. $i++;
  6561. $dr = $line['detail'];
  6562. $amt = $this->procuremenExportAmount($dr);
  6563. $subAmount += $amt;
  6564. $sheet->setCellValue('A' . $rowNum, $i);
  6565. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  6566. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  6567. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  6568. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  6569. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  6570. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  6571. $sheet->setCellValue('H' . $rowNum, $amt);
  6572. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  6573. $rowNum++;
  6574. }
  6575. $sumSubtotalCounts += $groupLineCount;
  6576. $grandAmount += $subAmount;
  6577. $sheet->setCellValue('A' . $rowNum, $groupLineCount);
  6578. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6579. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  6580. $sheet->getStyle('G' . $rowNum)->getAlignment()
  6581. ->setHorizontal(Alignment::HORIZONTAL_RIGHT)
  6582. ->setVertical(Alignment::VERTICAL_CENTER);
  6583. $rowNum++;
  6584. }
  6585. }
  6586. $sheet->setCellValue('A' . $rowNum, '总计');
  6587. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  6588. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6589. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  6590. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  6591. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  6592. $lastRow = $rowNum;
  6593. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  6594. 'borders' => [
  6595. 'allBorders' => [
  6596. 'borderStyle' => Border::BORDER_THIN,
  6597. 'color' => ['rgb' => '000000'],
  6598. ],
  6599. ],
  6600. ]);
  6601. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  6602. if ($lastRow >= 3) {
  6603. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6604. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6605. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6606. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6607. }
  6608. $sheet->getColumnDimension('A')->setWidth(7);
  6609. $sheet->getColumnDimension('B')->setWidth(16);
  6610. $sheet->getColumnDimension('C')->setWidth(52);
  6611. $sheet->getColumnDimension('D')->setWidth(32);
  6612. $sheet->getColumnDimension('E')->setWidth(12);
  6613. $sheet->getColumnDimension('F')->setWidth(44);
  6614. $sheet->getColumnDimension('G')->setWidth(26);
  6615. $sheet->getColumnDimension('H')->setWidth(13);
  6616. $sheet->getRowDimension(1)->setRowHeight(28);
  6617. $fileBase = '协助明细_' . str_replace('-', '', $ym);
  6618. $filename = $fileBase . '.xlsx';
  6619. try {
  6620. $this->ensurePurchaseMonthExportLogTable();
  6621. list($adminId, $adminName) = $this->GetUseName();
  6622. Db::table('purchase_month_export_log')->insert([
  6623. 'ym' => $ym,
  6624. 'admin_id' => (int)$adminId,
  6625. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  6626. 'row_count' => count($exportLines),
  6627. 'total_amount' => round($grandAmount, 2),
  6628. 'createtime' => time(),
  6629. ]);
  6630. } catch (\Throwable $e) {
  6631. Log::write('month export log: ' . $e->getMessage(), 'error');
  6632. }
  6633. if (ob_get_length()) {
  6634. ob_end_clean();
  6635. }
  6636. $asciiName = 'outward_' . str_replace('-', '', $ym) . '.xlsx';
  6637. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  6638. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  6639. header('Cache-Control: max-age=0');
  6640. $writer = new Xlsx($spreadsheet);
  6641. $writer->save('php://output');
  6642. $spreadsheet->disconnectWorksheets();
  6643. unset($spreadsheet);
  6644. exit;
  6645. }
  6646. /**
  6647. * 导出用:工序列文案
  6648. */
  6649. protected function procuremenExportGxText(array $r)
  6650. {
  6651. $a = trim((string)($r['CDXMC'] ?? ''));
  6652. $b = trim((string)($r['CGYMC'] ?? ''));
  6653. if ($a !== '' && $b !== '') {
  6654. return $a . ':' . $b;
  6655. }
  6656. return $a !== '' ? $a : $b;
  6657. }
  6658. /**
  6659. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  6660. */
  6661. protected function procuremenExportAmount(array $r)
  6662. {
  6663. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  6664. if (!array_key_exists($k, $r)) {
  6665. continue;
  6666. }
  6667. $v = $r[$k];
  6668. if ($v === null || $v === '') {
  6669. continue;
  6670. }
  6671. if (is_numeric($v)) {
  6672. return (float)$v;
  6673. }
  6674. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  6675. if ($v !== '' && is_numeric($v)) {
  6676. return (float)$v;
  6677. }
  6678. }
  6679. return 0.0;
  6680. }
  6681. /**
  6682. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  6683. */
  6684. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  6685. {
  6686. $s = trim($ccydh);
  6687. if ($s === '') {
  6688. return 'ORDER';
  6689. }
  6690. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  6691. $s = trim($s, '._-');
  6692. if ($s === '') {
  6693. return 'ORDER';
  6694. }
  6695. if (function_exists('mb_substr')) {
  6696. return mb_substr($s, 0, 80, 'UTF-8');
  6697. }
  6698. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  6699. }
  6700. /**
  6701. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  6702. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  6703. *
  6704. * @return array{objectKey: string, webPath: string}
  6705. */
  6706. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  6707. {
  6708. $sid = (int)$scydgyId;
  6709. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  6710. $y = date('Y');
  6711. $m = date('m');
  6712. $d = date('d');
  6713. $basename = $safeOrder . '_' . $sid . '.pdf';
  6714. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  6715. return [
  6716. 'objectKey' => $objectKey,
  6717. 'webPath' => '/' . $objectKey,
  6718. ];
  6719. }
  6720. /**
  6721. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  6722. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  6723. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  6724. *
  6725. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  6726. */
  6727. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  6728. {
  6729. if (!$this->isValidScydgyRowId($scydgyId)) {
  6730. return '';
  6731. }
  6732. $ids = trim((string)$scydgyId);
  6733. $prep = $this->prepareProcuremenDetailsView($ids);
  6734. if (!$prep['ok']) {
  6735. return '';
  6736. }
  6737. $ccydh = $prep['ccydh'];
  6738. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  6739. $objectKey = $paths['objectKey'];
  6740. $webPath = $paths['webPath'];
  6741. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  6742. $this->view->assign([
  6743. 'pdf_export' => 1,
  6744. 'pdfMetaLine' => $meta,
  6745. ]);
  6746. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  6747. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6748. $this->view->engine->layout(false);
  6749. try {
  6750. $html = $this->view->fetch('procuremen/details_pdf_shell');
  6751. } catch (\Throwable $e) {
  6752. if ($restoreLayout) {
  6753. $this->view->engine->layout($restoreLayout);
  6754. }
  6755. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  6756. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  6757. return '';
  6758. }
  6759. if ($restoreLayout) {
  6760. $this->view->engine->layout($restoreLayout);
  6761. }
  6762. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  6763. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  6764. if (!is_dir($tempDir)) {
  6765. @mkdir($tempDir, 0755, true);
  6766. }
  6767. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  6768. try {
  6769. $mpdf = new \Mpdf\Mpdf([
  6770. 'mode' => 'utf-8',
  6771. 'format' => 'A4',
  6772. 'margin_left' => 12,
  6773. 'margin_right' => 12,
  6774. 'margin_top' => 14,
  6775. 'margin_bottom' => 14,
  6776. 'tempDir' => $tempDir,
  6777. 'autoScriptToLang' => true,
  6778. 'autoLangToFont' => true,
  6779. ]);
  6780. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  6781. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  6782. $mpdf->SetBasePath('http://127.0.0.1/');
  6783. $mpdf->WriteHTML($html);
  6784. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  6785. } catch (\Throwable $e) {
  6786. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  6787. if (is_file($tempPdf)) {
  6788. @unlink($tempPdf);
  6789. }
  6790. return '';
  6791. }
  6792. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  6793. if ($ossUrl !== '') {
  6794. @unlink($tempPdf);
  6795. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  6796. return $ossUrl;
  6797. }
  6798. $pi = pathinfo($objectKey);
  6799. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  6800. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  6801. if ($baseFile === '') {
  6802. @unlink($tempPdf);
  6803. return '';
  6804. }
  6805. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  6806. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  6807. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  6808. @unlink($tempPdf);
  6809. return '';
  6810. }
  6811. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  6812. if (!@copy($tempPdf, $fullPath)) {
  6813. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  6814. @unlink($tempPdf);
  6815. return '';
  6816. }
  6817. @unlink($tempPdf);
  6818. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  6819. return $webPath;
  6820. }
  6821. /**
  6822. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  6823. */
  6824. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  6825. {
  6826. if ($scydgyId <= 0 || $webPath === '') {
  6827. return;
  6828. }
  6829. try {
  6830. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  6831. } catch (\Throwable $e) {
  6832. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  6833. }
  6834. }
  6835. /**
  6836. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  6837. *
  6838. * @param array<string, string> $vars
  6839. * @return array<string, string>
  6840. */
  6841. protected function normalizeSmsTemplateVars(array $vars): array
  6842. {
  6843. $out = [];
  6844. foreach ($vars as $k => $v) {
  6845. $out[(string)$k] = trim((string)$v);
  6846. }
  6847. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  6848. $out['contact_name'] = $out['company_name'];
  6849. }
  6850. return $out;
  6851. }
  6852. /**
  6853. * 按手机号或公司名称查 customer 表联系人姓名
  6854. */
  6855. protected function resolveCustomerContactName(string $phone, string $companyName): string
  6856. {
  6857. $phone = trim($phone);
  6858. $companyName = trim($companyName);
  6859. try {
  6860. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  6861. $row = Db::table('customer')
  6862. ->where(function ($q) use ($phone) {
  6863. $q->where('phone', $phone)->whereOr('account', $phone);
  6864. })
  6865. ->order('id', 'asc')
  6866. ->find();
  6867. if (is_array($row)) {
  6868. $nm = trim((string)($row['username'] ?? ''));
  6869. if ($nm !== '') {
  6870. return $nm;
  6871. }
  6872. }
  6873. }
  6874. if ($companyName !== '') {
  6875. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  6876. if (is_array($row)) {
  6877. return trim((string)($row['username'] ?? ''));
  6878. }
  6879. }
  6880. } catch (\Throwable $e) {
  6881. }
  6882. return '';
  6883. }
  6884. /**
  6885. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  6886. */
  6887. protected function plainTextToHtmlEmailBody(string $text): string
  6888. {
  6889. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  6890. $parts = explode("\n", $text);
  6891. $out = [];
  6892. foreach ($parts as $line) {
  6893. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  6894. $out[] = $line;
  6895. } else {
  6896. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  6897. }
  6898. }
  6899. return implode("<br>\n", $out);
  6900. }
  6901. /**
  6902. * 短信场景:去掉链接类变量,避免误填 URL
  6903. *
  6904. * @param array<string, string> $vars
  6905. * @return array<string, string>
  6906. */
  6907. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  6908. {
  6909. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  6910. return $vars;
  6911. }
  6912. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  6913. $vars[$k] = '';
  6914. }
  6915. return $vars;
  6916. }
  6917. /**
  6918. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  6919. *
  6920. * @param array<string, string> $vars
  6921. */
  6922. protected function renderNotifyTemplate(string $scene, array $vars): string
  6923. {
  6924. $vars = $this->normalizeSmsTemplateVars($vars);
  6925. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  6926. $row = $this->loadNotifyTemplateRow($scene);
  6927. if ($row === null) {
  6928. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  6929. }
  6930. $tpl = trim((string)($row['content'] ?? ''));
  6931. if ($tpl === '') {
  6932. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  6933. }
  6934. foreach ($vars as $k => $v) {
  6935. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  6936. }
  6937. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  6938. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  6939. return $tpl;
  6940. }
  6941. protected function resolveProcuremenEmailSubject(string $scene): string
  6942. {
  6943. $map = [
  6944. 'review_email' => '您有新的协助加工订单',
  6945. ];
  6946. $subject = trim((string)($map[$scene] ?? ''));
  6947. if ($subject === '') {
  6948. $this->error('未配置邮件主题:' . $scene);
  6949. }
  6950. return $subject;
  6951. }
  6952. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  6953. {
  6954. $map = [
  6955. 'review_email' => '协助下发-邮箱',
  6956. 'review_sms' => '协助下发-短信',
  6957. 'confirm_ok' => '采购确认-通过',
  6958. 'confirm_fail' => '采购确认-未通过',
  6959. ];
  6960. $label = $map[$scene] ?? $scene;
  6961. if ($titleRequired) {
  6962. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  6963. }
  6964. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  6965. }
  6966. /** @deprecated 使用 renderNotifyTemplate */
  6967. protected function renderSmsTemplate(string $scene, array $vars): string
  6968. {
  6969. return $this->renderNotifyTemplate($scene, $vars);
  6970. }
  6971. /**
  6972. * 是否开启协助通知演练(不发真实短信/邮件)
  6973. */
  6974. protected function isProcuremenNotifyDryRun(): bool
  6975. {
  6976. return (bool)Config::get('procuremen_notify_dry_run');
  6977. }
  6978. /**
  6979. * @param array<string, mixed> $payload
  6980. */
  6981. protected function recordNotifyDryRunPreview(array $payload): void
  6982. {
  6983. $this->notifyDryRunPreview[] = $payload;
  6984. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6985. }
  6986. /**
  6987. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  6988. * @throws \Exception
  6989. */
  6990. protected function smsbao($phone, $content)
  6991. {
  6992. if ($this->isProcuremenNotifyDryRun()) {
  6993. $this->recordNotifyDryRunPreview([
  6994. 'scene' => 'sms_only',
  6995. 'phone' => $phone,
  6996. 'sms_content' => $content,
  6997. ]);
  6998. return;
  6999. }
  7000. $statusStr = [
  7001. '0' => '短信发送成功',
  7002. '-1' => '参数不全',
  7003. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  7004. '30' => '密码错误',
  7005. '40' => '账号不存在',
  7006. '41' => '余额不足',
  7007. '42' => '帐户已过期',
  7008. '43' => 'IP地址限制',
  7009. '50' => '内容含有敏感词',
  7010. ];
  7011. $smsapi = 'http://api.smsbao.com/';
  7012. $user = 'zhuwei123';
  7013. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  7014. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  7015. $result = @file_get_contents($sendurl);
  7016. if ($result === false) {
  7017. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  7018. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  7019. }
  7020. $result = trim((string)$result);
  7021. if ($result !== '0') {
  7022. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  7023. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  7024. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  7025. }
  7026. }
  7027. }