Procuremen.php 289 KB

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