Procuremen.php 251 KB

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