Procuremen.php 260 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114
  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', 'archiveabandon', '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. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  2501. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  2502. if ($manageTransaction) {
  2503. Db::commit();
  2504. }
  2505. } catch (\Throwable $e) {
  2506. if ($manageTransaction) {
  2507. Db::rollback();
  2508. }
  2509. throw $e;
  2510. }
  2511. $poIdFinal = $purchaseOrderId;
  2512. if ($poIdFinal <= 0) {
  2513. try {
  2514. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2515. if (is_array($rpo)) {
  2516. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  2517. }
  2518. } catch (\Throwable $e) {
  2519. $poIdFinal = 0;
  2520. }
  2521. }
  2522. $pickNames = [];
  2523. foreach ($selectedIds as $pid) {
  2524. $dr = $this->purchaseOrderDetai($sid, $pid);
  2525. $nm = trim((string)($dr['company_name'] ?? ''));
  2526. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  2527. }
  2528. $this->addOrderLog(
  2529. $sid,
  2530. 'purchase_confirm',
  2531. '采购确认:已选中供应商「' . implode('、', $pickNames) . '」;',
  2532. $poIdFinal > 0 ? $poIdFinal : null
  2533. );
  2534. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars($sid, $selectedIds[0] ?? 0);
  2535. $sendSmsSafe = function ($phone, $content) {
  2536. $phone = trim((string)$phone);
  2537. if ($phone === '') {
  2538. return;
  2539. }
  2540. try {
  2541. $this->smsbao($phone, $content);
  2542. } catch (\Throwable $e) {
  2543. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  2544. }
  2545. };
  2546. foreach ($selectedIds as $pid) {
  2547. $dr = $this->purchaseOrderDetai($sid, $pid);
  2548. if (!is_array($dr)) {
  2549. continue;
  2550. }
  2551. $cname = trim((string)($dr['company_name'] ?? ''));
  2552. $ph = trim((string)($dr['phone'] ?? ''));
  2553. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  2554. 'company_name' => $cname,
  2555. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  2556. 'phone' => $ph,
  2557. ]));
  2558. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  2559. }
  2560. foreach ($unselectedIds as $pid) {
  2561. $dr = $this->purchaseOrderDetai($sid, $pid);
  2562. if (!is_array($dr)) {
  2563. continue;
  2564. }
  2565. $cname = trim((string)($dr['company_name'] ?? ''));
  2566. $ph = trim((string)($dr['phone'] ?? ''));
  2567. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  2568. 'company_name' => $cname,
  2569. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  2570. 'phone' => $ph,
  2571. ]));
  2572. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  2573. }
  2574. Log::write(sprintf(
  2575. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  2576. $scydgyId,
  2577. $purchaseOrderId,
  2578. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  2579. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  2580. ), 'notice');
  2581. $pdfPublicPath = '';
  2582. try {
  2583. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  2584. } catch (\Throwable $e) {
  2585. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  2586. }
  2587. return [
  2588. 'scydgy_id' => $scydgyId,
  2589. 'purchase_order_id' => $purchaseOrderId,
  2590. 'selected_ids' => $selectedIds,
  2591. 'unselected_ids' => $unselectedIds,
  2592. 'purchase_confirm_pdf' => $pdfPublicPath,
  2593. ];
  2594. }
  2595. /**
  2596. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  2597. *
  2598. * @param int[] $detailIds
  2599. */
  2600. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  2601. {
  2602. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  2603. if ($detailIds === []) {
  2604. return;
  2605. }
  2606. $payload = ['status_name' => $statusName];
  2607. try {
  2608. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  2609. } catch (\Throwable $e) {
  2610. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  2611. }
  2612. }
  2613. /**
  2614. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  2615. */
  2616. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  2617. {
  2618. try {
  2619. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  2620. } catch (\Throwable $e) {
  2621. return;
  2622. }
  2623. if (!is_array($rows)) {
  2624. return;
  2625. }
  2626. foreach ($rows as $dr) {
  2627. if (!is_array($dr)) {
  2628. continue;
  2629. }
  2630. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  2631. if ($id <= 0) {
  2632. continue;
  2633. }
  2634. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  2635. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  2636. try {
  2637. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  2638. } catch (\Throwable $e) {
  2639. }
  2640. }
  2641. }
  2642. /**
  2643. * @param array<string, mixed> $detailRow
  2644. */
  2645. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  2646. {
  2647. $am = $detailRow['amount'] ?? null;
  2648. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  2649. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2650. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2651. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  2652. }
  2653. /**
  2654. * @return int[]
  2655. */
  2656. protected function purchaseOrderDetail(int $scydgyId): array
  2657. {
  2658. if (!$this->isValidScydgyRowId($scydgyId)) {
  2659. return [];
  2660. }
  2661. try {
  2662. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  2663. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  2664. $list = $listQuery->select();
  2665. } catch (\Throwable $e) {
  2666. return [];
  2667. }
  2668. if (!is_array($list)) {
  2669. return [];
  2670. }
  2671. $ids = [];
  2672. foreach ($list as $r) {
  2673. if (!is_array($r)) {
  2674. continue;
  2675. }
  2676. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  2677. if ($pk > 0) {
  2678. $ids[] = $pk;
  2679. }
  2680. }
  2681. return array_values(array_unique($ids));
  2682. }
  2683. /**
  2684. * 获取当前登录用户信息 [id, 展示名]
  2685. */
  2686. protected function GetUseName(): array
  2687. {
  2688. $id = 0;
  2689. $name = '';
  2690. try {
  2691. if ($this->auth && $this->auth->isLogin()) {
  2692. $u = $this->auth->getUserInfo();
  2693. if (is_array($u)) {
  2694. $id = (int)($u['id'] ?? 0);
  2695. $name = trim((string)($u['nickname'] ?? ''));
  2696. if ($name === '') {
  2697. $name = trim((string)($u['username'] ?? ''));
  2698. }
  2699. }
  2700. }
  2701. } catch (\Throwable $e) {
  2702. }
  2703. if ($name === '') {
  2704. $name = '未知用户';
  2705. }
  2706. return [$id, $name];
  2707. }
  2708. /**
  2709. * 外发采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  2710. */
  2711. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  2712. {
  2713. if (!$this->isValidScydgyRowId($scydgyId) || $content === '') {
  2714. return;
  2715. }
  2716. list($adminId, $adminName) = $this->GetUseName();
  2717. $cut = function ($s, $max) {
  2718. if (function_exists('mb_substr')) {
  2719. return mb_substr($s, 0, $max, 'UTF-8');
  2720. }
  2721. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  2722. };
  2723. try {
  2724. Db::table('purchase_order_oper_log')->insert([
  2725. 'scydgy_id' => $scydgyId,
  2726. 'purchase_order_id' => $purchaseOrderId,
  2727. 'admin_id' => $adminId,
  2728. 'admin_name' => $cut($adminName, 64),
  2729. 'action' => $cut((string)$action, 64),
  2730. 'content' => $cut($content, 1000),
  2731. // 表结构 createtime 为 int Unix 时间戳;日期字符串会导致插入失败或时间为 0,详情「操作记录」为空
  2732. 'createtime' => time(),
  2733. ]);
  2734. } catch (\Throwable $e) {
  2735. Log::write('procuremen addOrderLog: ' . $e->getMessage(), 'error');
  2736. }
  2737. }
  2738. /**
  2739. * 按主键取一条
  2740. */
  2741. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  2742. {
  2743. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  2744. return [];
  2745. }
  2746. try {
  2747. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  2748. if (is_array($one)) {
  2749. return $one;
  2750. }
  2751. } catch (\Throwable $e) {
  2752. }
  2753. try {
  2754. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  2755. if (is_array($one)) {
  2756. return $one;
  2757. }
  2758. } catch (\Throwable $e) {
  2759. }
  2760. return [];
  2761. }
  2762. /**
  2763. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  2764. */
  2765. protected function formatProcuremenDetailTime($v): string
  2766. {
  2767. if ($v === null || $v === '') {
  2768. return '';
  2769. }
  2770. if (is_numeric($v) && (int)$v > 946684800) {
  2771. return date('Y-m-d H:i:s', (int)$v);
  2772. }
  2773. $s = trim((string)$v);
  2774. if ($s !== '' && stripos($s, '0000-00-00') !== 0) {
  2775. return $s;
  2776. }
  2777. return '';
  2778. }
  2779. /**
  2780. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  2781. */
  2782. protected function formatDeliveryYmd($v): string
  2783. {
  2784. if ($v === null || $v === '') {
  2785. return '';
  2786. }
  2787. $s = trim((string)$v);
  2788. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  2789. return '';
  2790. }
  2791. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  2792. return $m[1];
  2793. }
  2794. $ts = strtotime($s);
  2795. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  2796. }
  2797. /**
  2798. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  2799. */
  2800. protected function detailRowSupplierAccepted(array $r): bool
  2801. {
  2802. $am = $r['amount'] ?? null;
  2803. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  2804. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  2805. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  2806. return $okAmt && $okDel;
  2807. }
  2808. /**
  2809. * 是否已向外发/供应商下发(有下发明细、已进入审批流或记录下发时间)
  2810. */
  2811. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  2812. {
  2813. if ($detailCount > 0) {
  2814. return true;
  2815. }
  2816. $wf = (int)($main['wflow_status'] ?? 0);
  2817. if ($wf >= 1) {
  2818. return true;
  2819. }
  2820. $pickTime = trim((string)($main['pick_time'] ?? ''));
  2821. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  2822. return true;
  2823. }
  2824. return false;
  2825. }
  2826. /**
  2827. * 下发时间:优先 pick_time,其次首条下发明细时间
  2828. */
  2829. protected function resolveProcuremenIssueTime(array $main, array $details): string
  2830. {
  2831. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  2832. if ($issueTime !== '') {
  2833. return $issueTime;
  2834. }
  2835. foreach ($details as $dr) {
  2836. if (!is_array($dr)) {
  2837. continue;
  2838. }
  2839. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  2840. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  2841. $issueTime = $t;
  2842. }
  2843. }
  2844. if ($issueTime !== '') {
  2845. return $issueTime;
  2846. }
  2847. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  2848. }
  2849. /**
  2850. * 直接点「完结」时间:优先操作记录 mark_complete
  2851. */
  2852. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  2853. {
  2854. if (!$this->isValidScydgyRowId($scydgyId)) {
  2855. return '';
  2856. }
  2857. try {
  2858. $log = Db::table('purchase_order_oper_log')
  2859. ->where('scydgy_id', $scydgyId)
  2860. ->where('action', 'mark_complete')
  2861. ->order('id', 'desc')
  2862. ->find();
  2863. if (is_array($log)) {
  2864. $ct = (int)($log['createtime'] ?? 0);
  2865. if ($ct > 946684800) {
  2866. return date('Y-m-d H:i:s', $ct);
  2867. }
  2868. }
  2869. } catch (\Throwable $e) {
  2870. }
  2871. return '';
  2872. }
  2873. /**
  2874. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  2875. *
  2876. * @param array $main purchase_order 一行
  2877. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  2878. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  2879. */
  2880. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  2881. {
  2882. $issueCnt = count($details);
  2883. $acceptCnt = 0;
  2884. $pickedName = '';
  2885. $pickedTime = '';
  2886. foreach ($details as $dr) {
  2887. if (!is_array($dr)) {
  2888. continue;
  2889. }
  2890. if ($this->detailRowSupplierAccepted($dr)) {
  2891. $acceptCnt++;
  2892. }
  2893. if ((int)($dr['status'] ?? 0) === 1) {
  2894. if ($pickedName === '') {
  2895. $pickedName = trim((string)($dr['company_name'] ?? ''));
  2896. }
  2897. if ($pickedTime === '') {
  2898. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  2899. if ($pickedTime === '') {
  2900. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  2901. }
  2902. }
  2903. }
  2904. }
  2905. $hasMain = $main !== [];
  2906. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  2907. if ($poTime === '') {
  2908. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  2909. }
  2910. $mainStatus = isset($main['status']) ? (int)$main['status'] : 0;
  2911. $wflowStatus = (int)($main['wflow_status'] ?? 0);
  2912. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  2913. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  2914. $auditNotifyTime = '';
  2915. if ($wflowStatus >= 2 || ($wflowStatus === 0 && $issueCnt > 0)) {
  2916. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  2917. if ($this->isValidScydgyRowId($scydgyId)) {
  2918. try {
  2919. $auditLog = Db::table('purchase_order_oper_log')
  2920. ->where('scydgy_id', $scydgyId)
  2921. ->where('action', 'audit_confirm')
  2922. ->order('id', 'desc')
  2923. ->find();
  2924. if (is_array($auditLog)) {
  2925. $ct = (int)($auditLog['createtime'] ?? 0);
  2926. if ($ct > 946684800) {
  2927. $auditNotifyTime = date('Y-m-d H:i:s', $ct);
  2928. }
  2929. }
  2930. } catch (\Throwable $e) {
  2931. }
  2932. }
  2933. if ($auditNotifyTime === '' && $issueTime !== '') {
  2934. $auditNotifyTime = $issueTime;
  2935. }
  2936. }
  2937. $supplierTime = '';
  2938. if ($acceptCnt > 0) {
  2939. foreach ($details as $dr) {
  2940. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  2941. continue;
  2942. }
  2943. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  2944. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  2945. $supplierTime = $t;
  2946. }
  2947. }
  2948. }
  2949. $directComplete = ($mainStatus === 1 && !$issued);
  2950. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  2951. $doneTime = '';
  2952. if ($mainStatus === 1) {
  2953. if ($directComplete) {
  2954. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  2955. }
  2956. if ($doneTime === '') {
  2957. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  2958. }
  2959. if ($doneTime === '') {
  2960. foreach ($details as $dr) {
  2961. if (!is_array($dr)) {
  2962. continue;
  2963. }
  2964. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  2965. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  2966. $doneTime = $t;
  2967. }
  2968. }
  2969. }
  2970. if ($doneTime === '') {
  2971. $doneTime = $poTime;
  2972. }
  2973. }
  2974. if ($directComplete) {
  2975. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  2976. $step1Done = $hasMain;
  2977. $step2Done = false;
  2978. $step3Done = false;
  2979. $step4Done = false;
  2980. $step5Done = false;
  2981. $step6Done = true;
  2982. } else {
  2983. $step1Done = $issued;
  2984. $step2Done = $issued;
  2985. // wflow=1:初选已下发、待审批确认通知;wflow>=2 或旧数据(有明细且 wf=0)视为已通知
  2986. $step3Done = $wflowStatus >= 2 || ($wflowStatus === 0 && $issueCnt > 0);
  2987. $step4Done = $acceptCnt > 0;
  2988. $step5Done = false;
  2989. foreach ($details as $dr) {
  2990. if (is_array($dr) && (int)($dr['status'] ?? 0) === 1) {
  2991. $step5Done = true;
  2992. break;
  2993. }
  2994. }
  2995. $step6Done = $mainStatus === 1;
  2996. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  2997. if ($mainStatus === 1 && $issued) {
  2998. $step3Done = true;
  2999. $step4Done = true;
  3000. $step5Done = true;
  3001. if ($supplierTime === '') {
  3002. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3003. if ($fillT !== '') {
  3004. $supplierTime = $fillT;
  3005. }
  3006. }
  3007. if ($pickedTime === '') {
  3008. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3009. if ($fillT !== '') {
  3010. $pickedTime = $fillT;
  3011. }
  3012. }
  3013. if ($auditNotifyTime === '') {
  3014. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3015. if ($fillT !== '') {
  3016. $auditNotifyTime = $fillT;
  3017. }
  3018. }
  3019. }
  3020. }
  3021. $auditPendingSubtitle = '待确认通知';
  3022. $steps = [
  3023. [
  3024. 'title' => '未发',
  3025. 'subtitle' => '',
  3026. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  3027. 'done' => $step1Done,
  3028. ],
  3029. [
  3030. 'title' => '初选下发',
  3031. 'subtitle' => '',
  3032. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  3033. 'done' => $step2Done,
  3034. ],
  3035. [
  3036. 'title' => '待审批',
  3037. 'subtitle' => $step3Done ? '' : $auditPendingSubtitle,
  3038. 'time' => $step3Done ? $auditNotifyTime : '',
  3039. 'done' => $step3Done,
  3040. ],
  3041. [
  3042. 'title' => '供应商接单',
  3043. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  3044. 'time' => $step4Done ? $supplierTime : '',
  3045. 'done' => $step4Done,
  3046. ],
  3047. [
  3048. 'title' => '采购确认',
  3049. 'subtitle' => $pickedName !== '' ? ('选中供应商:' . $pickedName) : '',
  3050. 'time' => $step5Done ? ($pickedTime !== '' ? $pickedTime : '') : '',
  3051. 'done' => $step5Done,
  3052. ],
  3053. [
  3054. 'title' => '已完结',
  3055. 'subtitle' => '',
  3056. 'time' => $step6Done ? $doneTime : '',
  3057. 'done' => $step6Done,
  3058. ],
  3059. ];
  3060. $currentIdx = count($steps) - 1;
  3061. if (!$directComplete) {
  3062. foreach ($steps as $i => $s) {
  3063. if (!$s['done']) {
  3064. $currentIdx = $i;
  3065. break;
  3066. }
  3067. }
  3068. }
  3069. $nSteps = count($steps);
  3070. foreach ($steps as $idx => &$s) {
  3071. $s['current'] = ($idx === $currentIdx);
  3072. if ($idx === 0) {
  3073. $s['pdf_left_bg'] = '';
  3074. } else {
  3075. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  3076. }
  3077. if ($idx >= $nSteps - 1) {
  3078. $s['pdf_right_bg'] = '';
  3079. } else {
  3080. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  3081. }
  3082. }
  3083. unset($s);
  3084. $labelMap = [
  3085. 'CCYDH' => '订单号',
  3086. 'CYJMC' => '印件名称',
  3087. 'CCLBMMC' => '承揽部门',
  3088. 'CGYMC' => '工序名称',
  3089. 'CDW' => '单位',
  3090. 'NGZL' => '工作量',
  3091. 'CDF' => '单价',
  3092. 'cGzzxMc' => '工作中心',
  3093. 'MBZ' => '备注',
  3094. 'This_quantity' => '本次数量',
  3095. 'ceilingPrice' => '最高限价',
  3096. ];
  3097. $orderSummary = [];
  3098. foreach ($labelMap as $key => $lab) {
  3099. if (!array_key_exists($key, $main)) {
  3100. continue;
  3101. }
  3102. $val = $main[$key];
  3103. if ($val === null) {
  3104. $val = '';
  3105. } elseif (!is_scalar($val)) {
  3106. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  3107. } else {
  3108. $val = (string)$val;
  3109. }
  3110. $orderSummary[] = ['label' => $lab, 'value' => $val];
  3111. }
  3112. $orderSummaryGrid = [];
  3113. $n = count($orderSummary);
  3114. for ($i = 0; $i < $n; $i += 2) {
  3115. $left = $orderSummary[$i];
  3116. $hasRight = ($i + 1) < $n;
  3117. $orderSummaryGrid[] = [
  3118. 'l1' => $left['label'],
  3119. 'v1' => $left['value'],
  3120. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  3121. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  3122. ];
  3123. }
  3124. return [
  3125. 'steps' => $steps,
  3126. 'orderSummary' => $orderSummary,
  3127. 'orderSummaryGrid' => $orderSummaryGrid,
  3128. 'detailRows' => $details,
  3129. ];
  3130. }
  3131. /**
  3132. * 加载并 assign 外发采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  3133. *
  3134. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  3135. */
  3136. protected function prepareProcuremenDetailsView(string $ids): array
  3137. {
  3138. $main = [];
  3139. try {
  3140. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3141. $main = is_array($one) ? $one : [];
  3142. } catch (\Throwable $e) {
  3143. $main = [];
  3144. }
  3145. $details = [];
  3146. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  3147. if ($mergeRows === []) {
  3148. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  3149. if ($mergeRows === [] && $main !== []) {
  3150. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  3151. }
  3152. }
  3153. $detailSidList = [];
  3154. $anchorSid = (int)$ids;
  3155. if ($anchorSid !== 0) {
  3156. $detailSidList[$anchorSid] = true;
  3157. }
  3158. foreach ($mergeRows as $mr) {
  3159. if (!is_array($mr)) {
  3160. continue;
  3161. }
  3162. $sid = $this->extractScydgyRowId($mr);
  3163. if ($sid !== 0) {
  3164. $detailSidList[$sid] = true;
  3165. }
  3166. }
  3167. try {
  3168. if ($detailSidList !== []) {
  3169. $details = Db::table('purchase_order_detail')
  3170. ->where('scydgy_id', 'in', array_keys($detailSidList))
  3171. ->order('id', 'asc')
  3172. ->select();
  3173. }
  3174. } catch (\Throwable $e) {
  3175. $details = [];
  3176. }
  3177. if (!is_array($details)) {
  3178. $details = [];
  3179. }
  3180. foreach ($details as &$r) {
  3181. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  3182. $r['id'] = $r['ID'];
  3183. }
  3184. if (isset($r['createtime'])) {
  3185. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  3186. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  3187. } else {
  3188. $r['createtime_text'] = (string)$r['createtime'];
  3189. }
  3190. } else {
  3191. $r['createtime_text'] = '';
  3192. }
  3193. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  3194. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  3195. }
  3196. unset($r);
  3197. $activeDetails = [];
  3198. foreach ($details as $r) {
  3199. if (is_array($r) && empty($r['is_void'])) {
  3200. $activeDetails[] = $r;
  3201. }
  3202. }
  3203. $operLogs = [];
  3204. try {
  3205. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  3206. } catch (\Throwable $e) {
  3207. $operLogs = [];
  3208. }
  3209. if (!is_array($operLogs)) {
  3210. $operLogs = [];
  3211. }
  3212. foreach ($operLogs as &$lg) {
  3213. if (!is_array($lg)) {
  3214. continue;
  3215. }
  3216. $ct = isset($lg['createtime']) ? (int)$lg['createtime'] : 0;
  3217. $lg['createtime_text'] = $ct > 946684800 ? date('Y-m-d H:i:s', $ct) : '';
  3218. }
  3219. unset($lg);
  3220. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  3221. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  3222. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  3223. if ($ccydh === '') {
  3224. foreach ($details as $r) {
  3225. if (!is_array($r)) {
  3226. continue;
  3227. }
  3228. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  3229. if ($ccydh !== '') {
  3230. break;
  3231. }
  3232. }
  3233. }
  3234. $this->view->assign('ccydh', $ccydh);
  3235. $this->view->assign('steps', $bundle['steps']);
  3236. $this->view->assign('orderSummary', $bundle['orderSummary']);
  3237. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  3238. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  3239. $this->view->assign('processCount', count($mergeRows));
  3240. $this->view->assign('detailRows', $details);
  3241. $this->view->assign('supplierQuoteGroups', $quoteView['supplier_groups']);
  3242. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  3243. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  3244. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  3245. $this->view->assign('operLogs', $operLogs);
  3246. return [
  3247. 'ok' => $main !== [] || $details !== [],
  3248. 'ccydh' => $ccydh,
  3249. ];
  3250. }
  3251. /**
  3252. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  3253. */
  3254. public function details()
  3255. {
  3256. $ids = $this->request->param('ids', $this->request->param('id', ''));
  3257. if (is_array($ids)) {
  3258. $ids = isset($ids[0]) ? $ids[0] : '';
  3259. }
  3260. $ids = trim((string)$ids);
  3261. if ($ids === '') {
  3262. $this->error(__('Invalid parameters'));
  3263. }
  3264. $this->assertManualOrderDetailsViewable((int)$ids);
  3265. $this->prepareProcuremenDetailsView($ids);
  3266. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  3267. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  3268. $this->view->engine->layout(false);
  3269. try {
  3270. return $this->view->fetch('procuremen/details_dialog_shell');
  3271. } finally {
  3272. if ($restoreLayout) {
  3273. $this->view->engine->layout($restoreLayout);
  3274. }
  3275. }
  3276. }
  3277. /**
  3278. * 解析合并审核工序行(订单号须一致,且均未外发)
  3279. *
  3280. * @return array<int, array<string, mixed>>
  3281. */
  3282. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  3283. {
  3284. $primary = json_decode($rowJson, true);
  3285. if (!is_array($primary)) {
  3286. $this->error(__('Invalid parameters'));
  3287. }
  3288. $merge = json_decode($mergeRowsJson, true);
  3289. if (!is_array($merge) || $merge === []) {
  3290. $merge = [$primary];
  3291. }
  3292. $seen = [];
  3293. $out = [];
  3294. foreach ($merge as $r) {
  3295. if (!is_array($r)) {
  3296. continue;
  3297. }
  3298. $id = $this->extractScydgyRowId($r);
  3299. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  3300. continue;
  3301. }
  3302. $seen[$id] = true;
  3303. $out[] = $r;
  3304. }
  3305. if ($out === []) {
  3306. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  3307. }
  3308. $ccydh = null;
  3309. foreach ($out as $r) {
  3310. $dh = trim((string)($r['CCYDH'] ?? ''));
  3311. if ($ccydh === null) {
  3312. $ccydh = $dh;
  3313. } elseif ($dh !== $ccydh) {
  3314. $this->error('合并审核要求所选行的订单号一致');
  3315. }
  3316. }
  3317. $ids = [];
  3318. foreach ($out as $r) {
  3319. $id = $this->extractScydgyRowId($r);
  3320. if ($this->isValidScydgyRowId($id)) {
  3321. $ids[$id] = true;
  3322. }
  3323. }
  3324. $poBySid = [];
  3325. $detCntBySid = [];
  3326. if ($ids !== []) {
  3327. $idList = array_keys($ids);
  3328. try {
  3329. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  3330. if (is_array($poList)) {
  3331. foreach ($poList as $po) {
  3332. if (!is_array($po)) {
  3333. continue;
  3334. }
  3335. $sid = (int)($po['scydgy_id'] ?? 0);
  3336. if ($this->isValidScydgyRowId($sid)) {
  3337. $poBySid[$sid] = $po;
  3338. }
  3339. }
  3340. }
  3341. } catch (\Throwable $e) {
  3342. }
  3343. try {
  3344. $detRows = Db::table('purchase_order_detail')
  3345. ->where('scydgy_id', 'in', $idList)
  3346. ->field('scydgy_id, COUNT(*) AS cnt')
  3347. ->group('scydgy_id')
  3348. ->select();
  3349. if (is_array($detRows)) {
  3350. foreach ($detRows as $dr) {
  3351. if (!is_array($dr)) {
  3352. continue;
  3353. }
  3354. $sid = (int)($dr['scydgy_id'] ?? 0);
  3355. if ($this->isValidScydgyRowId($sid)) {
  3356. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  3357. }
  3358. }
  3359. }
  3360. } catch (\Throwable $e) {
  3361. }
  3362. }
  3363. foreach ($out as $r) {
  3364. $id = $this->extractScydgyRowId($r);
  3365. if (!$this->isValidScydgyRowId($id)) {
  3366. continue;
  3367. }
  3368. $po = $poBySid[$id] ?? null;
  3369. if (!is_array($po)) {
  3370. continue;
  3371. }
  3372. $wf = (int)($po['wflow_status'] ?? 0);
  3373. $st = $po['status'] ?? null;
  3374. if ($wf >= 1 || $st === 1 || $st === '1') {
  3375. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3376. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  3377. }
  3378. $detCnt = (int)($detCntBySid[$id] ?? 0);
  3379. if ($detCnt > 0 && $wf < 1) {
  3380. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3381. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  3382. }
  3383. }
  3384. return $out;
  3385. }
  3386. /**
  3387. * 规范化下发/确认时勾选的供应商
  3388. *
  3389. * @param array<int, mixed> $companies
  3390. * @return array<int, array<string, string>>
  3391. */
  3392. protected function normalizePickCompanies(array $companies): array
  3393. {
  3394. $out = [];
  3395. foreach ($companies as $c) {
  3396. if (!is_array($c)) {
  3397. continue;
  3398. }
  3399. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  3400. if ($name === '') {
  3401. continue;
  3402. }
  3403. $out[] = [
  3404. 'name' => $name,
  3405. 'company_name' => $name,
  3406. 'username' => trim((string)($c['username'] ?? '')),
  3407. 'email' => trim((string)($c['email'] ?? '')),
  3408. 'phone' => trim((string)($c['phone'] ?? '')),
  3409. 'company_type' => trim((string)($c['company_type'] ?? $c['category'] ?? '')),
  3410. ];
  3411. }
  3412. return $out;
  3413. }
  3414. /**
  3415. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  3416. *
  3417. * @param array<int, array<string, mixed>> $pool
  3418. * @return array<int, array<string, mixed>>
  3419. */
  3420. protected function collapseProcuremenPoolByOrder(array $pool): array
  3421. {
  3422. if ($pool === []) {
  3423. return [];
  3424. }
  3425. $groups = [];
  3426. foreach ($pool as $row) {
  3427. if (!is_array($row)) {
  3428. continue;
  3429. }
  3430. $dh = trim((string)($row['CCYDH'] ?? ''));
  3431. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  3432. if (!isset($groups[$key])) {
  3433. $groups[$key] = [];
  3434. }
  3435. $groups[$key][] = $row;
  3436. }
  3437. $out = [];
  3438. foreach ($groups as $ccydh => $rows) {
  3439. if ($rows === []) {
  3440. continue;
  3441. }
  3442. usort($rows, function ($a, $b) {
  3443. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  3444. });
  3445. $head = $rows[0];
  3446. $gymcList = [];
  3447. foreach ($rows as $r) {
  3448. $g = trim((string)($r['CGYMC'] ?? ''));
  3449. if ($g !== '' && !in_array($g, $gymcList, true)) {
  3450. $gymcList[] = $g;
  3451. }
  3452. }
  3453. $merged = $head;
  3454. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  3455. $merged['process_count'] = count($rows);
  3456. $merged['_order_merge_rows'] = $rows;
  3457. if (count($rows) > 1) {
  3458. $merged['CGYMC'] = implode('、', $gymcList);
  3459. }
  3460. $mergedPickTime = '';
  3461. foreach ($rows as $r) {
  3462. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  3463. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  3464. $mergedPickTime = $t;
  3465. }
  3466. }
  3467. if ($mergedPickTime !== '') {
  3468. $merged['pick_time'] = $mergedPickTime;
  3469. }
  3470. $out[] = $merged;
  3471. }
  3472. usort($out, function ($a, $b) {
  3473. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  3474. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  3475. if ($ta === $tb) {
  3476. $ida = (int)($a['purchase_order_id'] ?? 0);
  3477. $idb = (int)($b['purchase_order_id'] ?? 0);
  3478. if ($ida !== $idb) {
  3479. return $idb <=> $ida;
  3480. }
  3481. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  3482. }
  3483. if ($ta === '') {
  3484. return 1;
  3485. }
  3486. if ($tb === '') {
  3487. return -1;
  3488. }
  3489. return strcmp($tb, $ta);
  3490. });
  3491. return $out;
  3492. }
  3493. /**
  3494. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  3495. *
  3496. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3497. */
  3498. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  3499. {
  3500. $scydgyId = trim($scydgyId);
  3501. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3502. if ($scydgyId === '') {
  3503. return $empty;
  3504. }
  3505. try {
  3506. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3507. } catch (\Throwable $e) {
  3508. $anchor = null;
  3509. }
  3510. if (!is_array($anchor) || (int)($anchor['wflow_status'] ?? 0) !== 1) {
  3511. return $empty;
  3512. }
  3513. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3514. if ($ccydh === '') {
  3515. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  3516. }
  3517. try {
  3518. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('wflow_status', 1)->order('scydgy_id', 'asc')->select();
  3519. } catch (\Throwable $e) {
  3520. $pos = [$anchor];
  3521. }
  3522. if (!is_array($pos) || $pos === []) {
  3523. $pos = [$anchor];
  3524. }
  3525. return [
  3526. 'ccydh' => $ccydh,
  3527. 'pos' => $pos,
  3528. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3529. ];
  3530. }
  3531. /**
  3532. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  3533. */
  3534. protected function purchaseOrderRowInConfirmStage(array $po): bool
  3535. {
  3536. $st = $po['status'] ?? null;
  3537. if ($st === 1 || $st === '1') {
  3538. return false;
  3539. }
  3540. $wf = (int)($po['wflow_status'] ?? 0);
  3541. if ($wf === 2) {
  3542. return true;
  3543. }
  3544. if ($wf === 0) {
  3545. $sid = (int)($po['scydgy_id'] ?? 0);
  3546. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  3547. }
  3548. return false;
  3549. }
  3550. /**
  3551. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  3552. *
  3553. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3554. */
  3555. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  3556. {
  3557. $scydgyId = trim($scydgyId);
  3558. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3559. if ($scydgyId === '') {
  3560. return $empty;
  3561. }
  3562. try {
  3563. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3564. } catch (\Throwable $e) {
  3565. $anchor = null;
  3566. }
  3567. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  3568. return $empty;
  3569. }
  3570. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3571. if ($ccydh === '') {
  3572. return [
  3573. 'ccydh' => '',
  3574. 'pos' => [$anchor],
  3575. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  3576. ];
  3577. }
  3578. try {
  3579. $pos = Db::table('purchase_order')
  3580. ->where('CCYDH', $ccydh)
  3581. ->where('status', 0)
  3582. ->where(function ($q) {
  3583. $q->where('wflow_status', 2)
  3584. ->whereOr(function ($q2) {
  3585. $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  3586. });
  3587. })
  3588. ->order('scydgy_id', 'asc')
  3589. ->select();
  3590. } catch (\Throwable $e) {
  3591. $pos = [$anchor];
  3592. }
  3593. if (!is_array($pos) || $pos === []) {
  3594. $pos = [$anchor];
  3595. }
  3596. $pos = array_values(array_filter($pos, function ($po) {
  3597. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  3598. }));
  3599. if ($pos === []) {
  3600. $pos = [$anchor];
  3601. }
  3602. return [
  3603. 'ccydh' => $ccydh,
  3604. 'pos' => $pos,
  3605. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3606. ];
  3607. }
  3608. /**
  3609. * @param array<int, array<string, mixed>> $purchaseOrders
  3610. * @return array<int, array<string, mixed>>
  3611. */
  3612. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  3613. {
  3614. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  3615. $byId = [];
  3616. foreach ($pool as $r) {
  3617. if (!is_array($r)) {
  3618. continue;
  3619. }
  3620. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  3621. if ($this->isValidScydgyRowId($sid)) {
  3622. $byId[$sid] = $r;
  3623. }
  3624. }
  3625. $out = [];
  3626. foreach ($purchaseOrders as $po) {
  3627. if (!is_array($po)) {
  3628. continue;
  3629. }
  3630. $sid = (int)($po['scydgy_id'] ?? 0);
  3631. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  3632. $out[] = $byId[$sid];
  3633. }
  3634. }
  3635. return $out;
  3636. }
  3637. /**
  3638. * 详情 / PDF:同一外发批次下的全部工序行(与确认供应商弹窗一致)
  3639. *
  3640. * @return array<int, array<string, mixed>>
  3641. */
  3642. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  3643. {
  3644. $scydgyId = trim($scydgyId);
  3645. if ($scydgyId === '') {
  3646. return [];
  3647. }
  3648. try {
  3649. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3650. } catch (\Throwable $e) {
  3651. $anchor = null;
  3652. }
  3653. if (!is_array($anchor)) {
  3654. return [];
  3655. }
  3656. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  3657. return [];
  3658. }
  3659. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3660. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  3661. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  3662. try {
  3663. $q = Db::table('purchase_order');
  3664. if ($ccydh !== '') {
  3665. $q->where('CCYDH', $ccydh);
  3666. } else {
  3667. $q->where('scydgy_id', $scydgyId);
  3668. }
  3669. if ($isValidPick) {
  3670. $q->where('pick_time', $pickTime);
  3671. }
  3672. $pos = $q->order('scydgy_id', 'asc')->select();
  3673. } catch (\Throwable $e) {
  3674. $pos = [$anchor];
  3675. }
  3676. if (!is_array($pos) || $pos === []) {
  3677. $pos = [$anchor];
  3678. }
  3679. $pos = array_values(array_filter($pos, function ($po) {
  3680. if (!is_array($po)) {
  3681. return false;
  3682. }
  3683. $mr = $po['mod_rq'] ?? null;
  3684. if ($mr === null || $mr === '') {
  3685. return true;
  3686. }
  3687. $mrs = trim((string)$mr);
  3688. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  3689. }));
  3690. if ($pos === []) {
  3691. $pos = [$anchor];
  3692. }
  3693. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  3694. if ($rows === []) {
  3695. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  3696. }
  3697. return $rows;
  3698. }
  3699. /**
  3700. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  3701. *
  3702. * @param array<int, array<string, mixed>> $mergeRows
  3703. * @return array<int, array<string, mixed>>
  3704. */
  3705. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  3706. {
  3707. $list = array_values($mergeRows);
  3708. $n = count($list);
  3709. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  3710. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  3711. $mergeSame = $n > 1 && $orderKey0 !== '';
  3712. if ($mergeSame) {
  3713. foreach ($list as $rr) {
  3714. if (!is_array($rr)) {
  3715. $mergeSame = false;
  3716. break;
  3717. }
  3718. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  3719. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  3720. $mergeSame = false;
  3721. break;
  3722. }
  3723. }
  3724. }
  3725. $out = [];
  3726. foreach ($list as $idx => $r) {
  3727. if (!is_array($r)) {
  3728. continue;
  3729. }
  3730. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  3731. if (is_scalar($qty)) {
  3732. $qty = trim((string)$qty);
  3733. } else {
  3734. $qty = '';
  3735. }
  3736. if ($qty === '') {
  3737. $gzl = $r['NGZL'] ?? '';
  3738. if (is_scalar($gzl)) {
  3739. $qty = trim((string)$gzl);
  3740. }
  3741. }
  3742. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  3743. $sid = $this->extractScydgyRowId($r);
  3744. $out[] = [
  3745. 'seq' => $idx + 1,
  3746. 'scydgy_id' => $sid,
  3747. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  3748. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  3749. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  3750. 'CDW' => trim((string)($r['CDW'] ?? '')),
  3751. 'NGZL' => $r['NGZL'] ?? '',
  3752. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  3753. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  3754. 'CDF' => trim((string)($r['CDF'] ?? '')),
  3755. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  3756. 'show_order_cells' => !$mergeSame || $idx === 0,
  3757. 'order_rowspan' => $mergeSame ? $n : 1,
  3758. ];
  3759. }
  3760. return $out;
  3761. }
  3762. /**
  3763. * 解析金额/数量(去千分位等非数字字符)
  3764. */
  3765. protected function parseProcuremenMoneyNumber($value): ?float
  3766. {
  3767. if ($value === null || $value === '') {
  3768. return null;
  3769. }
  3770. if (is_numeric($value)) {
  3771. return (float)$value;
  3772. }
  3773. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  3774. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  3775. }
  3776. protected function formatProcuremenMoneyDisplay(?float $amount): string
  3777. {
  3778. if ($amount === null) {
  3779. return '';
  3780. }
  3781. return (string)(int)round($amount);
  3782. }
  3783. /**
  3784. * 列表/详情展示:工作量为 0 时显示空
  3785. */
  3786. protected function formatProcuremenWorkloadDisplay($value): string
  3787. {
  3788. if ($value === null || $value === '') {
  3789. return '';
  3790. }
  3791. $s = trim((string)$value);
  3792. if ($s === '') {
  3793. return '';
  3794. }
  3795. if (is_numeric($s) && (float)$s == 0) {
  3796. return '';
  3797. }
  3798. return $s;
  3799. }
  3800. /**
  3801. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  3802. */
  3803. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  3804. {
  3805. foreach ($details as $d) {
  3806. if (!is_array($d)) {
  3807. continue;
  3808. }
  3809. if (!$this->isPurchaseOrderDetailVoid($d) && (int)($d['status'] ?? 0) === 1) {
  3810. $cn = trim((string)($d['company_name'] ?? ''));
  3811. if ($cn !== '') {
  3812. return $cn;
  3813. }
  3814. }
  3815. }
  3816. return trim((string)($main['pick_company_name'] ?? ''));
  3817. }
  3818. /**
  3819. * 详情报价小计:单价 × 本工序本次数量
  3820. */
  3821. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  3822. {
  3823. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  3824. if ($unit === null) {
  3825. return null;
  3826. }
  3827. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  3828. if ($qty === null || $qty <= 0) {
  3829. return null;
  3830. }
  3831. return $unit * $qty;
  3832. }
  3833. /**
  3834. * 详情页:工序小计 + 供应商分组报价与总计
  3835. *
  3836. * @param array<int, array<string, mixed>> $mergeRows
  3837. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  3838. * @return array{
  3839. * process_rows: array,
  3840. * supplier_groups: array,
  3841. * order_total_text: string,
  3842. * order_total_has: bool,
  3843. * selected_company: string
  3844. * }
  3845. */
  3846. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  3847. {
  3848. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  3849. $qtyBySid = [];
  3850. $gymcBySid = [];
  3851. $orderedSids = [];
  3852. foreach ($mergeRows as $mr) {
  3853. if (!is_array($mr)) {
  3854. continue;
  3855. }
  3856. $sid = $this->extractScydgyRowId($mr);
  3857. if ($sid > 0) {
  3858. $orderedSids[] = $sid;
  3859. }
  3860. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3861. if ($qty === '') {
  3862. $qty = trim((string)($mr['NGZL'] ?? ''));
  3863. }
  3864. $qtyBySid[$sid] = $qty;
  3865. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  3866. }
  3867. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  3868. $detailByCompanySid = [];
  3869. foreach ($details as $d) {
  3870. if (!is_array($d)) {
  3871. continue;
  3872. }
  3873. $cn = trim((string)($d['company_name'] ?? ''));
  3874. $sid = (int)($d['scydgy_id'] ?? 0);
  3875. if ($cn === '' || $sid === 0) {
  3876. continue;
  3877. }
  3878. if (!isset($detailByCompanySid[$cn])) {
  3879. $detailByCompanySid[$cn] = [];
  3880. }
  3881. $detailByCompanySid[$cn][$sid] = $d;
  3882. }
  3883. $supplierGroups = [];
  3884. foreach ($detailByCompanySid as $cn => $bySid) {
  3885. $lines = [];
  3886. $groupTotal = 0.0;
  3887. $groupHas = false;
  3888. $groupVoid = true;
  3889. $usedSids = [];
  3890. $appendLine = function (int $sid, array $d) use (
  3891. &$lines,
  3892. &$groupTotal,
  3893. &$groupHas,
  3894. &$groupVoid,
  3895. $qtyBySid,
  3896. $gymcBySid
  3897. ) {
  3898. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  3899. if (!$isVoid) {
  3900. $groupVoid = false;
  3901. }
  3902. $qtyStr = $qtyBySid[$sid] ?? '';
  3903. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3904. $sub = null;
  3905. if (!$isVoid && $amountNum !== null) {
  3906. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  3907. if ($sub !== null) {
  3908. $groupTotal += $sub;
  3909. $groupHas = true;
  3910. }
  3911. }
  3912. $ct = $d['createtime_text'] ?? '';
  3913. if ($ct === '' && isset($d['createtime'])) {
  3914. $ct = $this->formatProcuremenDetailTime($d['createtime'] ?? null);
  3915. }
  3916. $lines[] = [
  3917. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  3918. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : trim((string)($d['amount'] ?? '')),
  3919. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  3920. 'delivery_ymd' => $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null),
  3921. 'status' => (int)($d['status'] ?? 0),
  3922. 'is_void' => $isVoid,
  3923. 'createtime_text' => $ct,
  3924. ];
  3925. };
  3926. foreach ($orderedSids as $sid) {
  3927. if (!isset($bySid[$sid])) {
  3928. continue;
  3929. }
  3930. $usedSids[$sid] = true;
  3931. $appendLine($sid, $bySid[$sid]);
  3932. }
  3933. foreach ($bySid as $sid => $d) {
  3934. if (isset($usedSids[$sid])) {
  3935. continue;
  3936. }
  3937. $appendLine((int)$sid, $d);
  3938. }
  3939. $supplierGroups[] = [
  3940. 'company_name' => $cn,
  3941. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  3942. 'is_void' => $groupVoid,
  3943. 'lines' => $lines,
  3944. 'line_count' => count($lines),
  3945. 'total_text' => $groupHas ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  3946. 'has_total' => $groupHas,
  3947. ];
  3948. }
  3949. usort($supplierGroups, function ($a, $b) {
  3950. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  3951. return ($a['is_void'] ?? false) ? 1 : -1;
  3952. }
  3953. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  3954. return ($a['is_selected'] ?? false) ? -1 : 1;
  3955. }
  3956. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  3957. });
  3958. return [
  3959. 'process_rows' => $processRows,
  3960. 'supplier_groups' => $supplierGroups,
  3961. 'order_total_text' => '',
  3962. 'order_total_has' => false,
  3963. 'selected_company' => $selectedCompany,
  3964. ];
  3965. }
  3966. /**
  3967. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  3968. */
  3969. protected function buildProcessLinesPlain(array $mergeRows): string
  3970. {
  3971. $lines = [];
  3972. $i = 1;
  3973. foreach ($mergeRows as $r) {
  3974. if (!is_array($r)) {
  3975. continue;
  3976. }
  3977. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3978. $dw = trim((string)($r['CDW'] ?? ''));
  3979. $gzl = trim((string)($r['NGZL'] ?? ''));
  3980. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  3981. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  3982. if ($dw !== '') {
  3983. $parts[] = '单位:' . $dw;
  3984. }
  3985. if ($gzl !== '') {
  3986. $parts[] = '工作量:' . $gzl;
  3987. }
  3988. if ($qty !== '') {
  3989. $parts[] = '本次数量:' . $qty;
  3990. }
  3991. $lines[] = implode(' ', $parts);
  3992. $i++;
  3993. }
  3994. return implode("\n", $lines);
  3995. }
  3996. /**
  3997. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  3998. *
  3999. * @return array<string, string>
  4000. */
  4001. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0): array
  4002. {
  4003. $po = null;
  4004. try {
  4005. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4006. } catch (\Throwable $e) {
  4007. $po = null;
  4008. }
  4009. $ccydh = is_array($po) ? trim((string)($po['CCYDH'] ?? '')) : '';
  4010. $cyjmc = is_array($po) ? trim((string)($po['CYJMC'] ?? '')) : '';
  4011. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0) {
  4012. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  4013. if (is_array($any)) {
  4014. if ($ccydh === '') {
  4015. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  4016. }
  4017. if ($cyjmc === '') {
  4018. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  4019. }
  4020. }
  4021. }
  4022. $mergeRows = is_array($po) && $po !== [] ? [$po] : [];
  4023. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  4024. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  4025. return [
  4026. 'ccydh' => $ccydh,
  4027. 'cyjmc' => $cyjmc,
  4028. 'cgymc' => is_array($po) ? trim((string)($po['CGYMC'] ?? '')) : '',
  4029. 'process_lines' => $processLines,
  4030. 'process_lines_html' => '',
  4031. ];
  4032. }
  4033. /**
  4034. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  4035. */
  4036. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  4037. {
  4038. $lines = [];
  4039. if ($ccydh !== '') {
  4040. $lines[] = '订单号:' . $ccydh;
  4041. }
  4042. if ($cyjmc !== '') {
  4043. $lines[] = '印件名称:' . $cyjmc;
  4044. }
  4045. if ($processPlain !== '') {
  4046. $lines[] = $processPlain;
  4047. }
  4048. return implode("\n", $lines);
  4049. }
  4050. /**
  4051. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  4052. *
  4053. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4054. */
  4055. protected function buildPlatformLinksPlain(array $detailLinks): string
  4056. {
  4057. $lines = [];
  4058. $i = 1;
  4059. foreach ($detailLinks as $lk) {
  4060. if (!is_array($lk)) {
  4061. continue;
  4062. }
  4063. $url = trim((string)($lk['url'] ?? ''));
  4064. if ($url === '') {
  4065. continue;
  4066. }
  4067. $label = trim((string)($lk['cgymc'] ?? ''));
  4068. if ($label === '') {
  4069. $label = '工序' . $i;
  4070. }
  4071. $lines[] = $label . ':' . $url;
  4072. $i++;
  4073. }
  4074. return implode("\n", $lines);
  4075. }
  4076. /**
  4077. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  4078. *
  4079. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4080. */
  4081. protected function buildPlatformLinksHtml(array $detailLinks): string
  4082. {
  4083. $parts = [];
  4084. $i = 1;
  4085. foreach ($detailLinks as $lk) {
  4086. if (!is_array($lk)) {
  4087. continue;
  4088. }
  4089. $url = trim((string)($lk['url'] ?? ''));
  4090. if ($url === '') {
  4091. continue;
  4092. }
  4093. $label = trim((string)($lk['cgymc'] ?? ''));
  4094. if ($label === '') {
  4095. $label = '工序' . $i;
  4096. }
  4097. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  4098. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  4099. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  4100. $i++;
  4101. }
  4102. return implode("<br>\n", $parts);
  4103. }
  4104. /**
  4105. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  4106. *
  4107. * @return array<string, mixed>
  4108. */
  4109. protected function loadMailerConfig(): array
  4110. {
  4111. try {
  4112. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  4113. } catch (\Throwable $e) {
  4114. $cfg = [];
  4115. }
  4116. return is_array($cfg) ? $cfg : [];
  4117. }
  4118. protected function loadNotifyTemplateRow(string $scene): ?array
  4119. {
  4120. try {
  4121. $row = Db::table('purchase_sms_template')
  4122. ->where('scene', $scene)
  4123. ->where(function ($q) {
  4124. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  4125. })
  4126. ->order('id', 'asc')
  4127. ->find();
  4128. } catch (\Throwable $e) {
  4129. return null;
  4130. }
  4131. if (!is_array($row) || $row === []) {
  4132. return null;
  4133. }
  4134. return [
  4135. 'title' => trim((string)($row['title'] ?? '')),
  4136. 'content' => trim((string)($row['content'] ?? '')),
  4137. ];
  4138. }
  4139. /**
  4140. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  4141. */
  4142. protected function buildProcessLinesHtml(array $mergeRows): string
  4143. {
  4144. if (count($mergeRows) <= 1) {
  4145. $r = $mergeRows[0] ?? [];
  4146. if (!is_array($r)) {
  4147. return '';
  4148. }
  4149. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4150. $dw = trim((string)($r['CDW'] ?? ''));
  4151. $gzl = trim((string)($r['NGZL'] ?? ''));
  4152. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4153. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  4154. if ($dw !== '') {
  4155. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  4156. }
  4157. if ($gzl !== '') {
  4158. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  4159. }
  4160. if ($qty !== '') {
  4161. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  4162. }
  4163. return $html;
  4164. }
  4165. $rows = '';
  4166. $i = 1;
  4167. foreach ($mergeRows as $r) {
  4168. if (!is_array($r)) {
  4169. continue;
  4170. }
  4171. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  4172. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  4173. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  4174. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  4175. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  4176. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  4177. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  4178. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  4179. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  4180. $i++;
  4181. }
  4182. if ($rows === '') {
  4183. return '';
  4184. }
  4185. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  4186. . '<thead><tr style="background:#f5f5f5;">'
  4187. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  4188. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  4189. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  4190. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  4191. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  4192. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  4193. }
  4194. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  4195. {
  4196. $sysRq = trim($sysRq);
  4197. if ($sysRq === '') {
  4198. if ($required) {
  4199. $this->error('请选择截止时间');
  4200. }
  4201. return '';
  4202. }
  4203. $ts = strtotime($sysRq);
  4204. if ($ts === false || $ts <= 0) {
  4205. $this->error('截止时间格式无效');
  4206. }
  4207. return date('Y-m-d H:i:s', $ts);
  4208. }
  4209. protected function formatProcuremenSysRqForInput($sysRq): string
  4210. {
  4211. $sr = trim((string)$sysRq);
  4212. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  4213. return '';
  4214. }
  4215. $ts = strtotime($sr);
  4216. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  4217. }
  4218. /**
  4219. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  4220. * @return array{ccydh?:string,pos:array,merge_rows:array}
  4221. */
  4222. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  4223. {
  4224. $sysRqPost = trim($sysRqPost);
  4225. if ($sysRqPost === '') {
  4226. return $bundle;
  4227. }
  4228. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqPost, true);
  4229. $pos = $bundle['pos'] ?? [];
  4230. foreach ($pos as $poRow) {
  4231. if (!is_array($poRow)) {
  4232. continue;
  4233. }
  4234. $sid = (int)($poRow['scydgy_id'] ?? 0);
  4235. if (!$this->isValidScydgyRowId($sid)) {
  4236. continue;
  4237. }
  4238. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['sys_rq' => $sysRqDb]);
  4239. }
  4240. foreach ($pos as $i => $poRow) {
  4241. if (is_array($pos[$i])) {
  4242. $pos[$i]['sys_rq'] = $sysRqDb;
  4243. }
  4244. }
  4245. $bundle['pos'] = $pos;
  4246. return $bundle;
  4247. }
  4248. /**
  4249. * 写入/更新 purchase_order(单道工序行)
  4250. */
  4251. protected function upsertPurchaseOrderFromRow(
  4252. array $row,
  4253. string $sysRqDb,
  4254. ?int $wflowStatus = null,
  4255. ?string $pickTime = null,
  4256. ?array $exists = null
  4257. ): void {
  4258. $ids = $this->extractScydgyRowId($row);
  4259. if (!$this->isValidScydgyRowId($ids)) {
  4260. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  4261. }
  4262. if ($exists === null) {
  4263. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4264. }
  4265. $data = [
  4266. 'scydgy_id' => $ids,
  4267. 'CCYDH' => $row['CCYDH'] ?? null,
  4268. 'CYJMC' => $row['CYJMC'] ?? null,
  4269. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4270. 'CDXMC' => $row['CDXMC'] ?? null,
  4271. 'CGYBH' => $row['CGYBH'] ?? null,
  4272. 'CGYMC' => $row['CGYMC'] ?? null,
  4273. 'CDW' => $row['CDW'] ?? null,
  4274. 'NGZL' => $row['NGZL'] ?? null,
  4275. 'CDF' => $row['CDF'] ?? null,
  4276. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4277. 'MBZ' => $row['MBZ'] ?? null,
  4278. 'bwjg' => $row['bwjg'] ?? null,
  4279. 'iStatus' => $row['iStatus'] ?? null,
  4280. 'dStamp' => $row['dStamp'] ?? null,
  4281. 'dputrecord' => $row['dputrecord'] ?? null,
  4282. 'cywyxm' => $row['cywyxm'] ?? null,
  4283. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4284. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4285. 'status' => 0,
  4286. 'sys_rq' => $sysRqDb,
  4287. ];
  4288. if ($wflowStatus !== null) {
  4289. $data['wflow_status'] = $wflowStatus;
  4290. }
  4291. if ($pickTime !== null && $pickTime !== '') {
  4292. $data['pick_time'] = $pickTime;
  4293. $data['pick_company_name'] = '';
  4294. }
  4295. if ($exists) {
  4296. $upd = $data;
  4297. unset($upd['scydgy_id']);
  4298. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4299. } else {
  4300. $data['createtime'] = date('Y-m-d H:i:s');
  4301. Db::table('purchase_order')->insert($data);
  4302. }
  4303. }
  4304. /**
  4305. * 外发下发 — 仅写入 purchase_order_detail(第一步不发通知)
  4306. *
  4307. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  4308. */
  4309. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  4310. {
  4311. $toDb = function ($value) {
  4312. if ($value === null) {
  4313. return null;
  4314. }
  4315. if (is_scalar($value)) {
  4316. return $value;
  4317. }
  4318. return json_encode($value, JSON_UNESCAPED_UNICODE);
  4319. };
  4320. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4321. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4322. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4323. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  4324. if ($username === '') {
  4325. $username = $this->resolveCustomerContactName($phone, $companyName);
  4326. }
  4327. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  4328. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  4329. }
  4330. if ($phone === '') {
  4331. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  4332. }
  4333. $detailLinks = [];
  4334. foreach ($mergeRows as $row) {
  4335. if (!is_array($row)) {
  4336. continue;
  4337. }
  4338. $sid = $this->extractScydgyRowId($row);
  4339. $detailId = 0;
  4340. if ($skipExisting) {
  4341. try {
  4342. $existsQuery = Db::table('purchase_order_detail')
  4343. ->where('scydgy_id', $sid)
  4344. ->where('company_name', $companyName);
  4345. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  4346. $exists = $existsQuery->find();
  4347. } catch (\Throwable $e) {
  4348. $exists = null;
  4349. }
  4350. if (is_array($exists)) {
  4351. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  4352. }
  4353. }
  4354. if ($detailId <= 0) {
  4355. $one = [
  4356. 'scydgy_id' => $toDb($sid),
  4357. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  4358. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  4359. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  4360. 'username' => $username !== '' ? $username : null,
  4361. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  4362. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  4363. 'createtime' => date('Y-m-d H:i:s'),
  4364. 'status' => 0,
  4365. 'status_name' => '未提交',
  4366. ];
  4367. Db::table('purchase_order_detail')->insert($one);
  4368. $detailId = (int)Db::getLastInsID();
  4369. }
  4370. $mprocUrl = '';
  4371. if ($buildMobileLinks && $detailId > 0) {
  4372. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  4373. }
  4374. $detailLinks[] = [
  4375. 'detail_id' => $detailId,
  4376. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  4377. 'url' => $mprocUrl,
  4378. ];
  4379. }
  4380. return $detailLinks;
  4381. }
  4382. /**
  4383. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  4384. * @return array<string, mixed>
  4385. */
  4386. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  4387. {
  4388. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4389. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4390. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4391. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  4392. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  4393. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  4394. $isMerge = !empty($ctx['is_merge']);
  4395. $contactName = trim((string)($c['username'] ?? ''));
  4396. if ($contactName === '') {
  4397. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  4398. }
  4399. $notifyVars = [
  4400. 'company_name' => $companyName,
  4401. 'contact_name' => $contactName,
  4402. 'phone' => $phone,
  4403. 'email' => $toEmail,
  4404. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  4405. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  4406. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  4407. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  4408. 'deadline' => (string)($ctx['deadline'] ?? ''),
  4409. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  4410. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  4411. 'platform_url' => $platformUrl,
  4412. 'platform_links' => $platformLinksPlain,
  4413. 'platform_links_html' => $platformLinksHtml,
  4414. ];
  4415. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  4416. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  4417. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  4418. return [
  4419. 'company_name' => $companyName,
  4420. 'phone' => $phone,
  4421. 'email' => $toEmail,
  4422. 'sms_content' => $smsContent,
  4423. 'mail_plain' => $mailPlain,
  4424. 'mail_body' => $mailBody,
  4425. 'notify_vars' => $notifyVars,
  4426. 'detail_links' => $detailLinks,
  4427. ];
  4428. }
  4429. /**
  4430. * 确认供应商 — 向选定一家发送短信/邮件(第二步)
  4431. *
  4432. * @param array<string, mixed> $chosen
  4433. * @param array<int, array<string, mixed>> $mergeRows
  4434. * @param array{ccydh:string, pos:array} $bundle
  4435. */
  4436. protected function sendAuditSupplierConfirmNotify(array $chosen, array $mergeRows, array $bundle): void
  4437. {
  4438. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, true, true);
  4439. }
  4440. /**
  4441. * @param array<string, mixed> $chosen
  4442. * @param array<int, array<string, mixed>> $mergeRows
  4443. * @param array{ccydh:string, pos:array} $bundle
  4444. */
  4445. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail): void
  4446. {
  4447. if (!$sendSms && !$sendEmail) {
  4448. return;
  4449. }
  4450. $companyName = trim((string)($chosen['name'] ?? ''));
  4451. $phone = trim((string)($chosen['phone'] ?? ''));
  4452. $toEmail = trim((string)($chosen['email'] ?? ''));
  4453. if ($companyName === '') {
  4454. throw new \Exception('供应商名称无效');
  4455. }
  4456. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  4457. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  4458. }
  4459. if ($sendSms && $phone === '') {
  4460. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  4461. }
  4462. $sids = [];
  4463. foreach ($mergeRows as $mr) {
  4464. if (!is_array($mr)) {
  4465. continue;
  4466. }
  4467. $sid = $this->extractScydgyRowId($mr);
  4468. if ($this->isValidScydgyRowId($sid)) {
  4469. $sids[$sid] = true;
  4470. }
  4471. }
  4472. if ($sids === []) {
  4473. throw new \Exception('未找到工序行,无法发送通知');
  4474. }
  4475. $sysRqNotify = '';
  4476. $pos = $bundle['pos'] ?? [];
  4477. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  4478. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  4479. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  4480. $ts = strtotime($sr);
  4481. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  4482. }
  4483. }
  4484. try {
  4485. $detailsQuery = Db::table('purchase_order_detail')
  4486. ->where('scydgy_id', 'in', array_keys($sids))
  4487. ->where('company_name', $companyName);
  4488. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4489. $details = $detailsQuery->order('id', 'asc')->select();
  4490. } catch (\Throwable $e) {
  4491. $details = [];
  4492. }
  4493. if (!is_array($details) || $details === []) {
  4494. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  4495. try {
  4496. $detailsQuery = Db::table('purchase_order_detail')
  4497. ->where('scydgy_id', 'in', array_keys($sids))
  4498. ->where('company_name', $companyName);
  4499. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4500. $details = $detailsQuery->order('id', 'asc')->select();
  4501. } catch (\Throwable $e) {
  4502. $details = [];
  4503. }
  4504. }
  4505. if (!is_array($details) || $details === []) {
  4506. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  4507. }
  4508. $detailLinks = [];
  4509. foreach ($details as $d) {
  4510. if (!is_array($d)) {
  4511. continue;
  4512. }
  4513. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  4514. if ($detailId <= 0) {
  4515. continue;
  4516. }
  4517. $sid = (int)($d['scydgy_id'] ?? 0);
  4518. $gymc = '';
  4519. foreach ($mergeRows as $mr) {
  4520. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  4521. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  4522. break;
  4523. }
  4524. }
  4525. $detailLinks[] = [
  4526. 'detail_id' => $detailId,
  4527. 'cgymc' => $gymc,
  4528. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  4529. ];
  4530. }
  4531. if ($detailLinks === []) {
  4532. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  4533. }
  4534. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  4535. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  4536. if ($sendEmail) {
  4537. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  4538. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  4539. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  4540. }
  4541. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  4542. $mailConfig = $this->loadMailerConfig();
  4543. if (!$this->isProcuremenNotifyDryRun()) {
  4544. if (empty($mailConfig['host'])) {
  4545. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  4546. }
  4547. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  4548. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  4549. }
  4550. }
  4551. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  4552. }
  4553. if ($sendSms) {
  4554. $this->issueSendSupplierSms($notifyBundle);
  4555. }
  4556. }
  4557. /**
  4558. * @param array<int, array<string, mixed>> $quoteGroups
  4559. * @return array<int, array<string, mixed>>
  4560. */
  4561. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  4562. {
  4563. $names = [];
  4564. if (is_string($companiesJson) && $companiesJson !== '') {
  4565. $decoded = json_decode($companiesJson, true);
  4566. if (is_array($decoded)) {
  4567. foreach ($decoded as $nm) {
  4568. $nm = trim((string)$nm);
  4569. if ($nm !== '') {
  4570. $names[] = $nm;
  4571. }
  4572. }
  4573. }
  4574. }
  4575. $names = array_values(array_unique($names));
  4576. if ($names === [] && $selectedCompany !== '') {
  4577. $names = [$selectedCompany];
  4578. }
  4579. if ($names === []) {
  4580. return $quoteGroups;
  4581. }
  4582. $targets = [];
  4583. foreach ($quoteGroups as $g) {
  4584. if (!is_array($g)) {
  4585. continue;
  4586. }
  4587. $cn = trim((string)($g['name'] ?? ''));
  4588. if ($cn !== '' && in_array($cn, $names, true)) {
  4589. $targets[] = $g;
  4590. }
  4591. }
  4592. return $targets;
  4593. }
  4594. /**
  4595. * @return array{pos:array, merge_rows:array, bundle:array}
  4596. */
  4597. protected function loadAuditResendBundle(string $scydgyId): array
  4598. {
  4599. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  4600. $pos = $bundle['pos'];
  4601. $mergeRows = $bundle['merge_rows'];
  4602. if ($pos === [] || $mergeRows === []) {
  4603. $this->error('该订单不在待确认供应商状态');
  4604. }
  4605. $sysRqDb = '';
  4606. if (isset($pos[0]) && is_array($pos[0])) {
  4607. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  4608. }
  4609. foreach ($pos as $i => $poRow) {
  4610. if (is_array($pos[$i]) && $sysRqDb !== '') {
  4611. $pos[$i]['sys_rq'] = $sysRqDb;
  4612. }
  4613. }
  4614. $bundle['pos'] = $pos;
  4615. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  4616. }
  4617. /**
  4618. * @param array<int, array<string, mixed>> $targets
  4619. */
  4620. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  4621. {
  4622. if ($targets === []) {
  4623. $this->error('未找到可通知的供应商');
  4624. }
  4625. $notifyErrors = [];
  4626. try {
  4627. $this->notifyDryRunPreview = [];
  4628. foreach ($targets as $g) {
  4629. if (!is_array($g)) {
  4630. continue;
  4631. }
  4632. $cname = trim((string)($g['name'] ?? ''));
  4633. if ($cname === '') {
  4634. continue;
  4635. }
  4636. $chosen = [
  4637. 'name' => $cname,
  4638. 'company_name' => $cname,
  4639. 'email' => trim((string)($g['email'] ?? '')),
  4640. 'phone' => trim((string)($g['phone'] ?? '')),
  4641. 'username' => trim((string)($g['username'] ?? '')),
  4642. ];
  4643. try {
  4644. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail);
  4645. } catch (\Throwable $e) {
  4646. $notifyErrors[] = $cname . ':' . $e->getMessage();
  4647. }
  4648. }
  4649. } catch (\Throwable $e) {
  4650. $this->error('通知发送失败:' . $e->getMessage());
  4651. }
  4652. if ($notifyErrors !== []) {
  4653. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  4654. }
  4655. if ($this->isProcuremenNotifyDryRun()) {
  4656. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  4657. 'notify_dry_run' => true,
  4658. 'notify_preview' => $this->notifyDryRunPreview,
  4659. ]);
  4660. }
  4661. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  4662. }
  4663. /**
  4664. * 外发下发 — 写入下发明细并拼好短信/邮件内容(供第二步发送)
  4665. *
  4666. * @return array<string, mixed>
  4667. */
  4668. protected function issueBuildSupplierNotifyBundle(array $c, array $mergeRows, array $ctx): array
  4669. {
  4670. $detailLinks = $this->issuePersistSupplierDetails($c, $mergeRows);
  4671. return $this->composeSupplierNotifyBundle($c, $ctx, $detailLinks);
  4672. }
  4673. /**
  4674. * 外发下发 — 发送短信(一家供应商)
  4675. *
  4676. * @param array<string, mixed> $bundle issueBuildSupplierNotifyBundle 返回值
  4677. */
  4678. protected function issueSendSupplierSms(array $bundle): void
  4679. {
  4680. $companyName = (string)($bundle['company_name'] ?? '');
  4681. $phone = (string)($bundle['phone'] ?? '');
  4682. $smsContent = (string)($bundle['sms_content'] ?? '');
  4683. $this->logIssueNotifyDebug('短信', [
  4684. 'company' => $companyName,
  4685. 'phone' => $phone,
  4686. 'sms_content' => $smsContent,
  4687. ]);
  4688. if ($this->isProcuremenNotifyDryRun()) {
  4689. $this->recordNotifyDryRunPreview([
  4690. 'scene' => 'issue_sms',
  4691. 'company_name' => $companyName,
  4692. 'phone' => $phone,
  4693. 'sms_content' => $smsContent,
  4694. ]);
  4695. return;
  4696. }
  4697. $this->smsbao($phone, $smsContent);
  4698. }
  4699. /**
  4700. * 外发下发 — 发送邮件(一家供应商)
  4701. *
  4702. * @param array<string, mixed> $bundle
  4703. * @param array<string, mixed> $mailConfig
  4704. */
  4705. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  4706. {
  4707. $companyName = (string)($bundle['company_name'] ?? '');
  4708. $toEmail = (string)($bundle['email'] ?? '');
  4709. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  4710. $mailBody = (string)($bundle['mail_body'] ?? '');
  4711. $this->logIssueNotifyDebug('邮件', [
  4712. 'company' => $companyName,
  4713. 'email' => $toEmail,
  4714. 'mail_subject' => $mailSubject,
  4715. 'mail_body' => $mailPlain,
  4716. ]);
  4717. if ($this->isProcuremenNotifyDryRun()) {
  4718. $this->recordNotifyDryRunPreview([
  4719. 'scene' => 'issue_email',
  4720. 'company_name' => $companyName,
  4721. 'email' => $toEmail,
  4722. 'mail_subject' => $mailSubject,
  4723. 'mail_body' => $mailPlain,
  4724. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  4725. 'notify_vars' => $bundle['notify_vars'] ?? [],
  4726. 'detail_links' => $bundle['detail_links'] ?? [],
  4727. ]);
  4728. return;
  4729. }
  4730. $mail = new PHPMailer(true);
  4731. $mail->isSMTP();
  4732. $mail->Host = $mailConfig['host'];
  4733. $mail->SMTPAuth = true;
  4734. $mail->Username = $mailConfig['addr'];
  4735. $mail->Password = $mailConfig['pass'];
  4736. $mail->SMTPSecure = $mailConfig['security'];
  4737. $mail->Port = $mailConfig['port'];
  4738. $mail->CharSet = $mailConfig['charset'];
  4739. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  4740. $mail->addAddress($toEmail, $companyName);
  4741. $mail->isHTML(true);
  4742. $mail->Subject = $mailSubject;
  4743. $mail->Body = $mailBody;
  4744. $mail->send();
  4745. }
  4746. /**
  4747. * 外发下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  4748. *
  4749. * @param array<int, array<string, mixed>> $mergeRows
  4750. * @return array<string, mixed>
  4751. */
  4752. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  4753. {
  4754. $head = $mergeRows[0] ?? [];
  4755. $isMerge = count($mergeRows) > 1;
  4756. return [
  4757. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  4758. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  4759. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  4760. 'is_merge' => $isMerge,
  4761. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  4762. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  4763. 'deadline' => $sysRqNotify,
  4764. ];
  4765. }
  4766. /**
  4767. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  4768. *
  4769. * @param array<string, mixed> $data
  4770. */
  4771. protected function logIssueNotifyDebug(string $type, array $data): void
  4772. {
  4773. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  4774. return;
  4775. }
  4776. Log::write('[外发下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  4777. }
  4778. /**
  4779. * 外发下发弹窗(选多家供应商并通知)
  4780. */
  4781. public function pickReview()
  4782. {
  4783. if ($this->request->isPost()) {
  4784. $this->error('请使用弹窗内「确认下发」提交');
  4785. }
  4786. $this->view->assign('pickMode', 1);
  4787. return $this->view->fetch('procuremen/review');
  4788. }
  4789. /**
  4790. * 外发新增(独立页面)
  4791. */
  4792. public function add()
  4793. {
  4794. if ($this->request->isPost()) {
  4795. $params = $this->request->post('row/a');
  4796. if (!is_array($params)) {
  4797. $this->error(__('Parameter %s can not be empty', ''));
  4798. }
  4799. [, $adminName] = $this->GetUseName();
  4800. $params['cywyxm'] = $adminName;
  4801. try {
  4802. $sid = $this->saveManualPickOrder($params);
  4803. } catch (\InvalidArgumentException $e) {
  4804. $this->error($e->getMessage());
  4805. } catch (\Throwable $e) {
  4806. $this->error($e->getMessage());
  4807. }
  4808. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  4809. }
  4810. [, $adminName] = $this->GetUseName();
  4811. $this->view->assign('adminNickname', $adminName);
  4812. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  4813. return $this->view->fetch();
  4814. }
  4815. /**
  4816. * 业务员外发新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  4817. */
  4818. public function rfqlist()
  4819. {
  4820. $this->relationSearch = false;
  4821. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  4822. $this->request->filter(['strip_tags', 'trim']);
  4823. if ($this->request->isAjax()) {
  4824. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  4825. $limit = max(10, min(500, (int)$limit));
  4826. $applyFilters = function ($query) use ($where) {
  4827. $query->where('scydgy_id', '<', 0);
  4828. $query->whereRaw(
  4829. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  4830. );
  4831. if (!$this->auth->isSuperAdmin()) {
  4832. [, $adminName] = $this->GetUseName();
  4833. $query->where('cywyxm', $adminName);
  4834. }
  4835. if (!empty($where)) {
  4836. $query->where($where);
  4837. }
  4838. };
  4839. $countQuery = Db::table('purchase_order');
  4840. $applyFilters($countQuery);
  4841. $total = (int)$countQuery->count();
  4842. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  4843. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  4844. $listQuery = Db::table('purchase_order');
  4845. $applyFilters($listQuery);
  4846. $rows = $listQuery
  4847. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  4848. ->order($sortField, $orderDir)
  4849. ->limit($offset, $limit)
  4850. ->select();
  4851. if (!is_array($rows)) {
  4852. $rows = [];
  4853. }
  4854. $out = [];
  4855. foreach ($rows as $r) {
  4856. if (!is_array($r)) {
  4857. continue;
  4858. }
  4859. $sid = (int)($r['scydgy_id'] ?? 0);
  4860. if ($sid >= 0) {
  4861. continue;
  4862. }
  4863. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  4864. if ($createdText === '') {
  4865. $createdText = trim((string)($r['dStamp'] ?? ''));
  4866. }
  4867. $out[] = [
  4868. 'id' => (int)($r['id'] ?? 0),
  4869. 'scydgy_id' => $sid,
  4870. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  4871. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  4872. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  4873. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  4874. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  4875. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  4876. 'createtime' => $r['createtime'] ?? null,
  4877. 'createtime_text' => $createdText,
  4878. ];
  4879. }
  4880. return json(['total' => $total, 'rows' => $out]);
  4881. }
  4882. [, $adminName] = $this->GetUseName();
  4883. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  4884. $this->view->assign('adminNickname', $adminName);
  4885. return $this->view->fetch('procuremen/rfqlist');
  4886. }
  4887. /**
  4888. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  4889. */
  4890. public function rfqlistDetails()
  4891. {
  4892. return $this->details();
  4893. }
  4894. /**
  4895. * 手工新增工序详情:业务员只看本人;超管及外发流程岗位可看全部
  4896. */
  4897. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  4898. {
  4899. if ($scydgyId >= 0) {
  4900. return;
  4901. }
  4902. try {
  4903. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4904. } catch (\Throwable $e) {
  4905. $po = null;
  4906. }
  4907. if (!is_array($po)) {
  4908. $this->error('订单不存在');
  4909. }
  4910. $modRq = trim((string)($po['mod_rq'] ?? ''));
  4911. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  4912. $this->error('订单不存在');
  4913. }
  4914. if ($this->auth->isSuperAdmin()) {
  4915. return;
  4916. }
  4917. [, $adminName] = $this->GetUseName();
  4918. $cywy = trim((string)($po['cywyxm'] ?? ''));
  4919. if ($cywy !== '' && $cywy === $adminName) {
  4920. return;
  4921. }
  4922. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  4923. try {
  4924. if ($this->auth->check($rule)) {
  4925. return;
  4926. }
  4927. } catch (\Throwable $e) {
  4928. }
  4929. }
  4930. $this->error('无权查看该订单');
  4931. }
  4932. /**
  4933. * @deprecated 使用 {@see assertManualOrderDetailsViewable}
  4934. */
  4935. protected function assertRfqRowViewable(int $scydgyId): void
  4936. {
  4937. $this->assertManualOrderDetailsViewable($scydgyId);
  4938. }
  4939. /**
  4940. * 手工新增外发工序进度文案
  4941. */
  4942. protected function formatProcuremenRfqProgressText(array $row): string
  4943. {
  4944. $st = trim((string)($row['status'] ?? ''));
  4945. // status=1 才表示主单已完结;status=0 为流程进行中(与详情 buildProcuremenDetailsViewData 一致)
  4946. if ($st === '1') {
  4947. return '已完结';
  4948. }
  4949. $wf = (int)($row['wflow_status'] ?? 0);
  4950. if ($wf === 2) {
  4951. return '待采购确认';
  4952. }
  4953. if ($wf === 1) {
  4954. return '待确认供应商';
  4955. }
  4956. $sid = (int)($row['scydgy_id'] ?? 0);
  4957. if ($sid < 0) {
  4958. try {
  4959. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  4960. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  4961. $detCnt = (int)$detCntQuery->count();
  4962. if ($detCnt > 0) {
  4963. return '已下发待确认';
  4964. }
  4965. } catch (\Throwable $e) {
  4966. }
  4967. }
  4968. return '待外发下发';
  4969. }
  4970. /**
  4971. * 外发初选列表 — 批量软删除
  4972. */
  4973. public function pickDelete()
  4974. {
  4975. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4976. $this->error(__('Invalid parameters'));
  4977. }
  4978. $rowsRaw = $this->request->post('rows_json', '[]');
  4979. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  4980. if (!is_array($rows) || $rows === []) {
  4981. $this->error('请至少勾选一条工序');
  4982. }
  4983. $done = 0;
  4984. Db::startTrans();
  4985. try {
  4986. foreach ($rows as $row) {
  4987. if (!is_array($row)) {
  4988. continue;
  4989. }
  4990. $this->softDeleteProcuremenPickRow($row);
  4991. $done++;
  4992. }
  4993. if ($done < 1) {
  4994. throw new \Exception('没有可删除的工序');
  4995. }
  4996. Db::commit();
  4997. } catch (\InvalidArgumentException $e) {
  4998. Db::rollback();
  4999. $this->error($e->getMessage());
  5000. } catch (\Throwable $e) {
  5001. Db::rollback();
  5002. $this->error($e->getMessage());
  5003. }
  5004. $this->success('已删除 ' . $done . ' 条工序');
  5005. }
  5006. /**
  5007. * 外发下发 — 手工新增工序(弹窗)
  5008. */
  5009. public function pickAdd()
  5010. {
  5011. if ($this->request->isPost()) {
  5012. $params = $this->request->post('row/a');
  5013. if (!is_array($params)) {
  5014. $this->error(__('Parameter %s can not be empty', ''));
  5015. }
  5016. try {
  5017. $sid = $this->saveManualPickOrder($params);
  5018. } catch (\InvalidArgumentException $e) {
  5019. $this->error($e->getMessage());
  5020. } catch (\Throwable $e) {
  5021. $this->error($e->getMessage());
  5022. }
  5023. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5024. }
  5025. return $this->view->fetch('procuremen/pick_add');
  5026. }
  5027. /**
  5028. * 外发下发提交 — 弹窗「确认下发」→ POST procuremen/picksubmit
  5029. */
  5030. public function pickSubmit()
  5031. {
  5032. if (!$this->request->isPost()) {
  5033. $this->error(__('Invalid parameters'));
  5034. }
  5035. // ---------- 接口订单数据 ----------
  5036. $rowJson = $this->request->post('row_json', '');
  5037. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  5038. $companiesJson = $this->request->post('companies_json', '[]');
  5039. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  5040. $companies = json_decode($companiesJson, true);
  5041. if (!is_array($companies)) {
  5042. $this->error('供应商数据无效');
  5043. }
  5044. $issueCompanies = $this->normalizePickCompanies($companies);
  5045. if ($issueCompanies === []) {
  5046. $this->error('请至少选择一家合作供应商');
  5047. }
  5048. $issueNameLabels = [];
  5049. foreach ($issueCompanies as $pc) {
  5050. $issueNameLabels[] = $pc['name'];
  5051. }
  5052. $issueNamesSummary = implode('、', $issueNameLabels);
  5053. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  5054. if ($sysRq === '') {
  5055. $this->error('请选择截止时间');
  5056. }
  5057. $sysRqTs = strtotime($sysRq);
  5058. if ($sysRqTs === false || $sysRqTs <= 0) {
  5059. $this->error('截止时间格式无效');
  5060. }
  5061. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  5062. $isMerge = count($mergeRows) > 1;
  5063. $logMsg = ($isMerge ? '合并外发初选(' . count($mergeRows) . ' 道工序)' : '外发初选')
  5064. . ',通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  5065. $issueTime = date('Y-m-d H:i:s');
  5066. $logSidList = [];
  5067. foreach ($mergeRows as $row) {
  5068. if (!is_array($row)) {
  5069. continue;
  5070. }
  5071. $sid = $this->extractScydgyRowId($row);
  5072. if ($this->isValidScydgyRowId($sid)) {
  5073. $logSidList[$sid] = true;
  5074. }
  5075. }
  5076. $existingBySid = [];
  5077. if ($logSidList !== []) {
  5078. try {
  5079. $existingRows = Db::table('purchase_order')
  5080. ->where('scydgy_id', 'in', array_keys($logSidList))
  5081. ->select();
  5082. if (is_array($existingRows)) {
  5083. foreach ($existingRows as $poRow) {
  5084. if (!is_array($poRow)) {
  5085. continue;
  5086. }
  5087. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5088. if ($this->isValidScydgyRowId($sid)) {
  5089. $existingBySid[$sid] = $poRow;
  5090. }
  5091. }
  5092. }
  5093. } catch (\Throwable $e) {
  5094. $existingBySid = [];
  5095. }
  5096. }
  5097. Db::startTrans();
  5098. try {
  5099. // ---------- 主表 wflow_status=1;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  5100. foreach ($mergeRows as $row) {
  5101. if (!is_array($row)) {
  5102. continue;
  5103. }
  5104. $sid = $this->extractScydgyRowId($row);
  5105. $this->upsertPurchaseOrderFromRow(
  5106. $row,
  5107. $sysRqDb,
  5108. 1,
  5109. $issueTime,
  5110. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  5111. );
  5112. }
  5113. foreach ($issueCompanies as $c) {
  5114. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  5115. }
  5116. Db::commit();
  5117. } catch (\Throwable $e) {
  5118. Db::rollback();
  5119. $this->error($e->getMessage());
  5120. }
  5121. $poIdBySid = [];
  5122. if ($logSidList !== []) {
  5123. try {
  5124. $poIdBySid = Db::table('purchase_order')
  5125. ->where('scydgy_id', 'in', array_keys($logSidList))
  5126. ->column('id', 'scydgy_id');
  5127. } catch (\Throwable $e) {
  5128. $poIdBySid = [];
  5129. }
  5130. }
  5131. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  5132. if ($logSidList !== []) {
  5133. list($adminId, $adminName) = $this->GetUseName();
  5134. $cut = function ($s, $max) {
  5135. if (function_exists('mb_substr')) {
  5136. return mb_substr($s, 0, $max, 'UTF-8');
  5137. }
  5138. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  5139. };
  5140. $logRows = [];
  5141. $seenLogSid = [];
  5142. foreach ($mergeRows as $row) {
  5143. if (!is_array($row)) {
  5144. continue;
  5145. }
  5146. $ids = $this->extractScydgyRowId($row);
  5147. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  5148. continue;
  5149. }
  5150. $seenLogSid[$ids] = true;
  5151. $poIdLog = null;
  5152. if (isset($poIdBySid[$ids])) {
  5153. $tid = (int)$poIdBySid[$ids];
  5154. $poIdLog = $tid > 0 ? $tid : null;
  5155. }
  5156. $logRows[] = [
  5157. 'scydgy_id' => $ids,
  5158. 'purchase_order_id' => $poIdLog,
  5159. 'admin_id' => $adminId,
  5160. 'admin_name' => $cut($adminName, 64),
  5161. 'action' => $cut('issue_submit', 64),
  5162. 'content' => $cut($logMsg, 1000),
  5163. 'createtime' => time(),
  5164. ];
  5165. }
  5166. if ($logRows !== []) {
  5167. try {
  5168. Db::table('purchase_order_oper_log')->insertAll($logRows);
  5169. } catch (\Throwable $e) {
  5170. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  5171. }
  5172. }
  5173. }
  5174. $notifyErrors = [];
  5175. $posNotify = [];
  5176. if ($logSidList !== []) {
  5177. try {
  5178. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  5179. } catch (\Throwable $e) {
  5180. $posNotify = [];
  5181. }
  5182. }
  5183. if (!is_array($posNotify)) {
  5184. $posNotify = [];
  5185. }
  5186. foreach ($posNotify as $i => $prow) {
  5187. if (is_array($posNotify[$i])) {
  5188. $posNotify[$i]['sys_rq'] = $sysRqDb;
  5189. }
  5190. }
  5191. $ccydhPick = '';
  5192. foreach ($mergeRows as $row) {
  5193. if (!is_array($row)) {
  5194. continue;
  5195. }
  5196. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  5197. if ($ccydhPick !== '') {
  5198. break;
  5199. }
  5200. }
  5201. $notifyBundleBase = [
  5202. 'ccydh' => $ccydhPick,
  5203. 'pos' => $posNotify,
  5204. 'merge_rows' => $mergeRows,
  5205. ];
  5206. try {
  5207. $this->notifyDryRunPreview = [];
  5208. foreach ($issueCompanies as $c) {
  5209. if (!is_array($c)) {
  5210. continue;
  5211. }
  5212. $cname = trim((string)($c['name'] ?? ''));
  5213. if ($cname === '') {
  5214. continue;
  5215. }
  5216. try {
  5217. $this->sendAuditSupplierConfirmNotify($c, $mergeRows, $notifyBundleBase);
  5218. } catch (\Throwable $e) {
  5219. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5220. }
  5221. }
  5222. } catch (\Throwable $e) {
  5223. $this->error('通知发送失败:' . $e->getMessage());
  5224. }
  5225. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  5226. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5227. }
  5228. if ($this->isProcuremenNotifyDryRun()) {
  5229. $this->success('【演练模式】已保存并生成通知预览', '', [
  5230. 'notify_dry_run' => true,
  5231. 'notify_preview' => $this->notifyDryRunPreview,
  5232. ]);
  5233. }
  5234. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「外发审批下发」确认供应商');
  5235. }
  5236. /**
  5237. * 确认供应商弹窗
  5238. */
  5239. public function auditIssue()
  5240. {
  5241. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5242. if (is_array($ids)) {
  5243. $ids = isset($ids[0]) ? $ids[0] : '';
  5244. }
  5245. $ids = trim((string)$ids);
  5246. if ($ids === '') {
  5247. $this->error(__('Invalid parameters'));
  5248. }
  5249. if ($this->request->isPost()) {
  5250. $this->error('请使用弹窗内「确认」提交');
  5251. }
  5252. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  5253. $pos = $bundle['pos'];
  5254. if ($pos === []) {
  5255. $this->error('该订单不在待确认供应商状态');
  5256. }
  5257. $po = $pos[0];
  5258. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5259. if ($quoteGroups === []) {
  5260. $this->error('暂无下发明细,请确认该订单已在「外发初选」完成下发');
  5261. }
  5262. $pickedName = '';
  5263. foreach ($pos as $poRow) {
  5264. if (!is_array($poRow)) {
  5265. continue;
  5266. }
  5267. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  5268. if ($pn !== '') {
  5269. $pickedName = $pn;
  5270. break;
  5271. }
  5272. }
  5273. $this->view->assign('po', $po);
  5274. $this->view->assign('scydgyId', $ids);
  5275. $this->view->assign('orderCcydh', $bundle['ccydh']);
  5276. $mergeRows = $bundle['merge_rows'];
  5277. $this->view->assign('processRows', $mergeRows);
  5278. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  5279. $this->view->assign('processCount', count($mergeRows));
  5280. $this->view->assign('quoteGroups', $quoteGroups);
  5281. $this->view->assign('quoteGroupsJson', json_encode($quoteGroups, JSON_UNESCAPED_UNICODE));
  5282. $this->view->assign('pickedCompanyName', $pickedName);
  5283. $this->view->assign('sysRq', $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null));
  5284. return $this->view->fetch('procuremen/audit_issue');
  5285. }
  5286. /**
  5287. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  5288. */
  5289. public function auditSubmit()
  5290. {
  5291. if (!$this->request->isPost()) {
  5292. $this->error(__('Invalid parameters'));
  5293. }
  5294. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5295. if ($scydgyId === '') {
  5296. $this->error('参数无效');
  5297. }
  5298. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5299. $pos = $bundle['pos'];
  5300. $mergeRows = $bundle['merge_rows'];
  5301. if ($pos === [] || $mergeRows === []) {
  5302. $this->error('该订单不在待确认供应商状态');
  5303. }
  5304. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5305. if ($quoteGroups === []) {
  5306. $this->error('暂无供应商报价,请确认已完成外发初选通知');
  5307. }
  5308. $companyName = trim((string)$this->request->post('selected_company', ''));
  5309. if ($companyName === '') {
  5310. $this->error('请选择一家供应商');
  5311. }
  5312. $matched = null;
  5313. foreach ($quoteGroups as $g) {
  5314. if (!is_array($g)) {
  5315. continue;
  5316. }
  5317. if (trim((string)($g['name'] ?? '')) === $companyName) {
  5318. $matched = $g;
  5319. break;
  5320. }
  5321. }
  5322. if ($matched === null) {
  5323. $this->error('所选供应商不在本单报价列表中');
  5324. }
  5325. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  5326. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5327. $procCnt = count($mergeRows);
  5328. $logMsg = '确认供应商(订单' . ($ccydhLog !== '' ? $ccydhLog : '')
  5329. . ($procCnt > 1 ? ',' . $procCnt . ' 道工序' : '')
  5330. . '),选定:' . $companyName;
  5331. Db::startTrans();
  5332. try {
  5333. foreach ($pos as $poRow) {
  5334. if (!is_array($poRow)) {
  5335. continue;
  5336. }
  5337. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5338. if (!$this->isValidScydgyRowId($sid)) {
  5339. continue;
  5340. }
  5341. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  5342. 'wflow_status' => 2,
  5343. 'status' => 0,
  5344. 'pick_company_name' => $companyName,
  5345. 'sys_rq' => $sysRqDb,
  5346. ]);
  5347. }
  5348. Db::commit();
  5349. } catch (\Throwable $e) {
  5350. Db::rollback();
  5351. $this->error($e->getMessage());
  5352. }
  5353. foreach ($pos as $poRow) {
  5354. if (!is_array($poRow)) {
  5355. continue;
  5356. }
  5357. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5358. if (!$this->isValidScydgyRowId($sid)) {
  5359. continue;
  5360. }
  5361. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  5362. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  5363. }
  5364. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  5365. }
  5366. /**
  5367. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  5368. */
  5369. public function auditResendSms()
  5370. {
  5371. if (!$this->request->isPost()) {
  5372. $this->error(__('Invalid parameters'));
  5373. }
  5374. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5375. if ($scydgyId === '') {
  5376. $this->error('参数无效');
  5377. }
  5378. $loaded = $this->loadAuditResendBundle($scydgyId);
  5379. $mergeRows = $loaded['merge_rows'];
  5380. $bundle = $loaded['bundle'];
  5381. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5382. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5383. if ($quoteGroups === []) {
  5384. $this->error('暂无可通知的供应商');
  5385. }
  5386. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5387. $companiesJson = (string)$this->request->post('companies_json', '');
  5388. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5389. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  5390. }
  5391. /**
  5392. * 确认供应商 — 二次发送邮件(可选单家/批量)
  5393. */
  5394. public function auditResendEmail()
  5395. {
  5396. if (!$this->request->isPost()) {
  5397. $this->error(__('Invalid parameters'));
  5398. }
  5399. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5400. if ($scydgyId === '') {
  5401. $this->error('参数无效');
  5402. }
  5403. $loaded = $this->loadAuditResendBundle($scydgyId);
  5404. $mergeRows = $loaded['merge_rows'];
  5405. $bundle = $loaded['bundle'];
  5406. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5407. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5408. if ($quoteGroups === []) {
  5409. $this->error('暂无可通知的供应商');
  5410. }
  5411. $companiesJson = (string)$this->request->post('companies_json', '');
  5412. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5413. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5414. if ($companiesJson === '' && $selectedCompany === '') {
  5415. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  5416. }
  5417. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  5418. }
  5419. /**
  5420. * 废弃单个订单 bundle(退回外发初选,明细归档留痕)
  5421. *
  5422. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  5423. * @return array<int, true> 已处理的 scydgy_id 集合
  5424. */
  5425. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回外发初选'): array
  5426. {
  5427. $pos = $bundle['pos'] ?? [];
  5428. if (!is_array($pos) || $pos === []) {
  5429. return [];
  5430. }
  5431. $sids = [];
  5432. foreach ($pos as $poRow) {
  5433. if (!is_array($poRow)) {
  5434. continue;
  5435. }
  5436. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5437. if ($this->isValidScydgyRowId($sid)) {
  5438. $sids[$sid] = true;
  5439. }
  5440. }
  5441. if ($sids === []) {
  5442. return [];
  5443. }
  5444. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5445. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '') . $logSuffix;
  5446. Db::table('purchase_order')
  5447. ->where('scydgy_id', 'in', array_keys($sids))
  5448. ->update([
  5449. 'wflow_status' => 0,
  5450. 'status' => '',
  5451. 'pick_company_name' => '',
  5452. 'pick_time' => null,
  5453. 'sys_rq' => null,
  5454. ]);
  5455. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  5456. foreach (array_keys($sids) as $sid) {
  5457. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  5458. }
  5459. return $sids;
  5460. }
  5461. /**
  5462. * 废弃单个审批订单 bundle(退回外发初选,明细归档留痕)
  5463. *
  5464. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  5465. * @return array<int, true> 已处理的 scydgy_id 集合
  5466. */
  5467. protected function abandonAuditOrderBundle(array $bundle): array
  5468. {
  5469. return $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  5470. }
  5471. /**
  5472. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  5473. *
  5474. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5475. */
  5476. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  5477. {
  5478. $scydgyId = trim($scydgyId);
  5479. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5480. if ($scydgyId === '') {
  5481. return $empty;
  5482. }
  5483. try {
  5484. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5485. } catch (\Throwable $e) {
  5486. $anchor = null;
  5487. }
  5488. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  5489. return $empty;
  5490. }
  5491. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5492. if ($ccydh === '') {
  5493. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  5494. }
  5495. try {
  5496. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  5497. $query->whereRaw("(TRIM(CAST(`status` AS CHAR)) = '1' OR CAST(`status` AS UNSIGNED) = 1)");
  5498. $pos = $query->order('scydgy_id', 'asc')->select();
  5499. } catch (\Throwable $e) {
  5500. $pos = [$anchor];
  5501. }
  5502. if (!is_array($pos) || $pos === []) {
  5503. $pos = [$anchor];
  5504. }
  5505. return [
  5506. 'ccydh' => $ccydh,
  5507. 'pos' => $pos,
  5508. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5509. ];
  5510. }
  5511. protected function purchaseOrderRowIsCompleted(array $po): bool
  5512. {
  5513. $st = $po['status'] ?? null;
  5514. if ($st === 1 || $st === '1') {
  5515. return true;
  5516. }
  5517. if (is_string($st) && trim($st) === '1') {
  5518. return true;
  5519. }
  5520. return is_numeric($st) && (int)$st === 1;
  5521. }
  5522. /**
  5523. * 废弃订单 — 退回外发初选重新询价(支持单条或批量)
  5524. */
  5525. public function auditAbandon()
  5526. {
  5527. if (!$this->request->isPost()) {
  5528. $this->error(__('Invalid parameters'));
  5529. }
  5530. $anchorIds = [];
  5531. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  5532. if ($batchRaw !== '') {
  5533. $decoded = json_decode($batchRaw, true);
  5534. if (is_array($decoded)) {
  5535. foreach ($decoded as $id) {
  5536. $s = trim((string)$id);
  5537. if ($s !== '') {
  5538. $anchorIds[] = $s;
  5539. }
  5540. }
  5541. }
  5542. }
  5543. if ($anchorIds === []) {
  5544. $single = trim((string)$this->request->post('scydgy_id', ''));
  5545. if ($single !== '') {
  5546. $anchorIds[] = $single;
  5547. }
  5548. }
  5549. if ($anchorIds === []) {
  5550. $this->error('请至少选择一条订单');
  5551. }
  5552. $processedCcydh = [];
  5553. $doneOrders = 0;
  5554. $allSids = [];
  5555. Db::startTrans();
  5556. try {
  5557. foreach ($anchorIds as $anchorId) {
  5558. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  5559. if (($bundle['pos'] ?? []) === []) {
  5560. continue;
  5561. }
  5562. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5563. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  5564. if (isset($processedCcydh[$dedupeKey])) {
  5565. continue;
  5566. }
  5567. $processedCcydh[$dedupeKey] = true;
  5568. $sids = $this->abandonAuditOrderBundle($bundle);
  5569. if ($sids === []) {
  5570. continue;
  5571. }
  5572. $doneOrders++;
  5573. foreach (array_keys($sids) as $sid) {
  5574. $allSids[(int)$sid] = true;
  5575. }
  5576. }
  5577. if ($doneOrders < 1) {
  5578. throw new \Exception('所选订单均不在待确认供应商状态');
  5579. }
  5580. Db::commit();
  5581. } catch (\Throwable $e) {
  5582. Db::rollback();
  5583. $this->error($e->getMessage());
  5584. }
  5585. $this->pickHiddenScydgySetCache = null;
  5586. $msg = $doneOrders > 1
  5587. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回外发初选,历史下发与操作记录已保留')
  5588. : '已退回外发初选,请重新选择供应商下发(历史记录已保留)';
  5589. $this->success($msg);
  5590. }
  5591. /**
  5592. * 历史存证 — 已完结订单重新下发,退回外发初选(支持单条或批量)
  5593. */
  5594. public function archiveAbandon()
  5595. {
  5596. if (!$this->request->isPost()) {
  5597. $this->error(__('Invalid parameters'));
  5598. }
  5599. $anchorIds = [];
  5600. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  5601. if ($batchRaw !== '') {
  5602. $decoded = json_decode($batchRaw, true);
  5603. if (is_array($decoded)) {
  5604. foreach ($decoded as $id) {
  5605. $s = trim((string)$id);
  5606. if ($s !== '') {
  5607. $anchorIds[] = $s;
  5608. }
  5609. }
  5610. }
  5611. }
  5612. if ($anchorIds === []) {
  5613. $single = trim((string)$this->request->post('scydgy_id', ''));
  5614. if ($single !== '') {
  5615. $anchorIds[] = $single;
  5616. }
  5617. }
  5618. if ($anchorIds === []) {
  5619. $this->error('请至少选择一条订单');
  5620. }
  5621. $processedCcydh = [];
  5622. $doneOrders = 0;
  5623. Db::startTrans();
  5624. try {
  5625. foreach ($anchorIds as $anchorId) {
  5626. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  5627. if (($bundle['pos'] ?? []) === []) {
  5628. continue;
  5629. }
  5630. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5631. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  5632. if (isset($processedCcydh[$dedupeKey])) {
  5633. continue;
  5634. }
  5635. $processedCcydh[$dedupeKey] = true;
  5636. $sids = $this->abandonOrderBundleToPick(
  5637. $bundle,
  5638. 'archive_abandon',
  5639. ',从历史存证退回外发初选'
  5640. );
  5641. if ($sids === []) {
  5642. continue;
  5643. }
  5644. $doneOrders++;
  5645. }
  5646. if ($doneOrders < 1) {
  5647. throw new \Exception('所选订单均不是已完结状态');
  5648. }
  5649. Db::commit();
  5650. } catch (\Throwable $e) {
  5651. Db::rollback();
  5652. $this->error($e->getMessage());
  5653. }
  5654. $this->pickHiddenScydgySetCache = null;
  5655. $msg = $doneOrders > 1
  5656. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回外发初选,历史记录已保留')
  5657. : '已退回外发初选,请重新选择供应商下发(历史记录已保留)';
  5658. $this->success($msg);
  5659. }
  5660. /**
  5661. * 采购终审 — 审批驳回(退回外发审批下发,不发送短信)
  5662. */
  5663. public function purchaseApprovalReject()
  5664. {
  5665. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5666. $this->error(__('Invalid parameters'));
  5667. }
  5668. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  5669. $decoded = json_decode($batchRaw, true);
  5670. if (!is_array($decoded) || $decoded === []) {
  5671. $this->error('提交数据无效');
  5672. }
  5673. Db::startTrans();
  5674. try {
  5675. foreach ($decoded as $item) {
  5676. if (!is_array($item)) {
  5677. continue;
  5678. }
  5679. $sid = (int)($item['scydgy_id'] ?? 0);
  5680. if (!$this->isValidScydgyRowId($sid)) {
  5681. continue;
  5682. }
  5683. $this->runPurchaseApprovalRejectForSid($sid);
  5684. }
  5685. Db::commit();
  5686. } catch (\Throwable $e) {
  5687. Db::rollback();
  5688. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  5689. }
  5690. $this->success('已驳回并退回「外发审批下发」');
  5691. }
  5692. /**
  5693. * @throws \Exception
  5694. */
  5695. protected function runPurchaseApprovalRejectForSid(int $sid): void
  5696. {
  5697. $allIds = $this->purchaseOrderDetail($sid);
  5698. if ($allIds === []) {
  5699. throw new \Exception('未找到下发明细');
  5700. }
  5701. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  5702. 'wflow_status' => 1,
  5703. 'status' => 0,
  5704. 'pick_company_name' => '',
  5705. ]);
  5706. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => 0]);
  5707. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  5708. $poId = 0;
  5709. try {
  5710. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  5711. if (is_array($po)) {
  5712. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  5713. }
  5714. } catch (\Throwable $e) {
  5715. }
  5716. $this->addOrderLog($sid, 'purchase_reject', '采购终审驳回,退回外发审批下发', $poId > 0 ? $poId : null);
  5717. }
  5718. /**
  5719. * 审核弹窗(旧入口,POST 已关闭)
  5720. */
  5721. public function review()
  5722. {
  5723. if ($this->request->isPost()) {
  5724. $this->error('请使用第一步「外发下发」通知供应商,再在「确认供应商」中选定一家');
  5725. }
  5726. $this->view->assign('pickMode', 0);
  5727. return $this->view->fetch('procuremen/review');
  5728. }
  5729. /**
  5730. * 审核弹窗获取公司列表
  5731. */
  5732. public function reviewCompanies()
  5733. {
  5734. if (!$this->request->isAjax()) {
  5735. $this->error(__('Invalid parameters'));
  5736. }
  5737. $list = [];
  5738. try {
  5739. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  5740. $rows = Db::table('customer')
  5741. ->where(function ($q) {
  5742. $q->where('status', 1)
  5743. ->whereOr('status', '1')
  5744. ->whereOr('status', '')
  5745. ->whereNull('status');
  5746. })
  5747. ->order('id', 'desc')
  5748. ->select();
  5749. } catch (\Throwable $e) {
  5750. $this->success('', '', []);
  5751. return;
  5752. }
  5753. if (!is_array($rows)) {
  5754. $this->success('', '', []);
  5755. return;
  5756. }
  5757. $detailColCandidates = [
  5758. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  5759. 'company_detail', 'company_desc', 'address',
  5760. ];
  5761. foreach ($rows as $row) {
  5762. if (!is_array($row)) {
  5763. continue;
  5764. }
  5765. $norm = [];
  5766. foreach ($row as $k => $v) {
  5767. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  5768. }
  5769. $row = $norm;
  5770. $st = $row['status'] ?? '';
  5771. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  5772. continue;
  5773. }
  5774. $id = isset($row['id']) ? (string)$row['id'] : '';
  5775. $companyName = '';
  5776. foreach (['company_name', 'name'] as $nk) {
  5777. if (!empty($row[$nk])) {
  5778. $companyName = trim((string)$row[$nk]);
  5779. break;
  5780. }
  5781. }
  5782. $username = '';
  5783. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  5784. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  5785. $username = trim((string)$row[$uk]);
  5786. break;
  5787. }
  5788. }
  5789. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  5790. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  5791. if ($phone === '' && isset($row['account'])) {
  5792. $phone = trim((string)$row['account']);
  5793. }
  5794. if ($phone === '' && isset($row['mobile'])) {
  5795. $phone = trim((string)$row['mobile']);
  5796. }
  5797. /* 邮箱、手机号均为空则无法发短信/邮件,不在下发弹窗展示 */
  5798. if ($email === '' && $phone === '') {
  5799. continue;
  5800. }
  5801. $category = '';
  5802. foreach (['company_type', 'category', 'type_name'] as $ck) {
  5803. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  5804. $category = trim((string)$row[$ck]);
  5805. break;
  5806. }
  5807. }
  5808. $detail = '';
  5809. foreach ($detailColCandidates as $dk) {
  5810. if (!isset($row[$dk])) {
  5811. continue;
  5812. }
  5813. $dv = trim((string)$row[$dk]);
  5814. if ($dv !== '') {
  5815. $detail = $dv;
  5816. break;
  5817. }
  5818. }
  5819. $list[] = [
  5820. 'id' => $id,
  5821. 'name' => $companyName,
  5822. 'company_name' => $companyName,
  5823. 'username' => $username,
  5824. 'email' => $email,
  5825. 'phone' => $phone,
  5826. 'category' => $category,
  5827. 'company_type' => $category,
  5828. 'detail' => $detail,
  5829. ];
  5830. }
  5831. $this->success('', '', $list);
  5832. }
  5833. /**
  5834. * 采购确认-下发明细弹窗:
  5835. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  5836. */
  5837. public function outward_detail()
  5838. {
  5839. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5840. if (is_array($ids)) {
  5841. $ids = isset($ids[0]) ? $ids[0] : '';
  5842. }
  5843. $ids = trim((string)$ids);
  5844. if ($ids === '') {
  5845. $this->error(__('Invalid parameters'));
  5846. }
  5847. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  5848. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  5849. $wffTab = 'all';
  5850. }
  5851. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  5852. $purchaseOrderId = 0;
  5853. $po = null;
  5854. try {
  5855. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5856. if (is_array($po)) {
  5857. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  5858. }
  5859. } catch (\Throwable $e) {
  5860. $purchaseOrderId = 0;
  5861. $po = null;
  5862. }
  5863. if (!$isPurchaseConfirm && is_array($po)) {
  5864. $wf = (int)($po['wflow_status'] ?? 0);
  5865. $st = trim((string)($po['status'] ?? ''));
  5866. $isDone = ($st === '1' || $st === 1);
  5867. if ($wf === 2 && !$isDone) {
  5868. $isPurchaseConfirm = true;
  5869. }
  5870. }
  5871. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  5872. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5873. $confirmProcessCount = 1;
  5874. $confirmPickGroups = [];
  5875. $processDisplayRows = [];
  5876. $allDetailsBySid = [];
  5877. $requiredSidList = [];
  5878. $sidList = [$ids];
  5879. if ($isPurchaseConfirm) {
  5880. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  5881. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  5882. if ($mergeRows !== []) {
  5883. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5884. }
  5885. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  5886. if ($confirmBundle['pos'] !== []) {
  5887. $sidList = [];
  5888. foreach ($confirmBundle['pos'] as $poRow) {
  5889. if (!is_array($poRow)) {
  5890. continue;
  5891. }
  5892. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5893. if (!$this->isValidScydgyRowId($sid)) {
  5894. continue;
  5895. }
  5896. $sidList[] = (string)$sid;
  5897. $requiredSidList[] = $sid;
  5898. }
  5899. }
  5900. if ($sidList === []) {
  5901. $sidList = [$ids];
  5902. $requiredSidList = [(int)$ids];
  5903. }
  5904. $confirmProcessCount = max(1, count($requiredSidList));
  5905. if (is_array($po) && $purchaseOrderId <= 0) {
  5906. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  5907. }
  5908. }
  5909. $rows = [];
  5910. try {
  5911. if (count($sidList) === 1) {
  5912. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  5913. } else {
  5914. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  5915. }
  5916. } catch (\Throwable $e) {
  5917. $rows = [];
  5918. }
  5919. if ($isPurchaseConfirm) {
  5920. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  5921. }
  5922. foreach ($rows as &$r) {
  5923. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5924. $r['id'] = $r['ID'];
  5925. }
  5926. if (isset($r['createtime'])) {
  5927. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5928. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5929. } else {
  5930. $r['createtime_text'] = (string)$r['createtime'];
  5931. }
  5932. } else {
  5933. $r['createtime_text'] = '';
  5934. }
  5935. }
  5936. unset($r);
  5937. $pickedCompanyName = '';
  5938. if ($isPurchaseConfirm) {
  5939. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  5940. if (!is_array($poRow)) {
  5941. continue;
  5942. }
  5943. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  5944. if ($pn !== '') {
  5945. $pickedCompanyName = $pn;
  5946. break;
  5947. }
  5948. }
  5949. }
  5950. $this->view->assign('rows', $rows ?: []);
  5951. $this->view->assign('rowCount', count($rows ?: []));
  5952. $this->view->assign('scydgyId', $ids);
  5953. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  5954. $this->view->assign('headTitle', $headTitle);
  5955. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  5956. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  5957. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  5958. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  5959. $this->view->assign('processDisplayRows', $processDisplayRows);
  5960. $this->view->assign('confirmPickGroups', $confirmPickGroups);
  5961. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  5962. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  5963. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  5964. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  5965. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  5966. if ($isPurchaseConfirm) {
  5967. return $this->view->fetch();
  5968. }
  5969. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5970. $this->view->engine->layout(false);
  5971. try {
  5972. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  5973. $this->view->assign('dialogBody', $bodyHtml);
  5974. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  5975. } finally {
  5976. if ($restoreLayout) {
  5977. $this->view->engine->layout($restoreLayout);
  5978. }
  5979. }
  5980. }
  5981. /**
  5982. * 月度导出记录表(不存在时自动创建)
  5983. */
  5984. protected function ensurePurchaseMonthExportLogTable(): void
  5985. {
  5986. try {
  5987. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  5988. } catch (\Throwable $e) {
  5989. Db::execute(
  5990. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  5991. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  5992. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  5993. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  5994. `admin_name` varchar(64) NOT NULL DEFAULT '',
  5995. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  5996. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  5997. `createtime` int(10) unsigned DEFAULT NULL,
  5998. PRIMARY KEY (`id`),
  5999. KEY `idx_ym` (`ym`),
  6000. KEY `idx_ct` (`createtime`)
  6001. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度外发明细导出记录'"
  6002. );
  6003. }
  6004. }
  6005. /**
  6006. * 按月份导出:已完结且采购确认已选定供应商(明细 status=1),与列表「已完结」∩「已选中」一致。
  6007. * 表头固定 8 列(与历史「外发明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  6008. */
  6009. public function export_month_outward()
  6010. {
  6011. $this->request->filter(['strip_tags', 'trim']);
  6012. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  6013. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  6014. $ym = date('Y-m');
  6015. }
  6016. $monthStart = $ym . '-01 00:00:00';
  6017. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  6018. $dbRows = [];
  6019. try {
  6020. $query = Db::table('purchase_order');
  6021. $query->whereRaw("(TRIM(CAST(`status` AS CHAR)) = '1' OR CAST(`status` AS UNSIGNED) = 1)");
  6022. $dbRows = $query->select();
  6023. } catch (\Throwable $e) {
  6024. $dbRows = [];
  6025. }
  6026. if (!is_array($dbRows)) {
  6027. $dbRows = [];
  6028. }
  6029. $pickedSidSet = $this->loadScydgyIdsWithPickedSupplierDetail();
  6030. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($pickedSidSet) {
  6031. if (!is_array($dbRow)) {
  6032. return false;
  6033. }
  6034. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  6035. if ($sid <= 0 && isset($dbRow['SCYDGY_ID'])) {
  6036. $sid = (int)$dbRow['SCYDGY_ID'];
  6037. }
  6038. return $sid > 0 && isset($pickedSidSet[$sid]);
  6039. }));
  6040. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  6041. $filtered = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], 'pick_time');
  6042. $mainBySid = [];
  6043. foreach ($filtered as $rw) {
  6044. if (!is_array($rw)) {
  6045. continue;
  6046. }
  6047. $rid = (int)($rw['ID'] ?? 0);
  6048. if ($rid > 0) {
  6049. $mainBySid[$rid] = $rw;
  6050. }
  6051. }
  6052. if ($mainBySid === []) {
  6053. $detailRows = [];
  6054. } else {
  6055. try {
  6056. $detailRows = Db::table('purchase_order_detail')
  6057. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6058. ->where('status', 1)
  6059. ->order('CCYDH', 'asc')
  6060. ->order('company_name', 'asc')
  6061. ->order('id', 'asc')
  6062. ->select();
  6063. } catch (\Throwable $e) {
  6064. try {
  6065. $detailRows = Db::table('purchase_order_detail')
  6066. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6067. ->where('status', 1)
  6068. ->order('CCYDH', 'asc')
  6069. ->order('company_name', 'asc')
  6070. ->order('ID', 'asc')
  6071. ->select();
  6072. } catch (\Throwable $e2) {
  6073. $detailRows = [];
  6074. }
  6075. }
  6076. }
  6077. if (!is_array($detailRows)) {
  6078. $detailRows = [];
  6079. }
  6080. $exportLines = [];
  6081. foreach ($detailRows as $dr) {
  6082. if (!is_array($dr)) {
  6083. continue;
  6084. }
  6085. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6086. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  6087. continue;
  6088. }
  6089. $m = $mainBySid[$sid];
  6090. $exportLines[] = [
  6091. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6092. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6093. 'company_name' => (string)($dr['company_name'] ?? ''),
  6094. 'CDF' => (string)($m['CDF'] ?? ''),
  6095. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6096. 'gx' => $this->procuremenExportGxText($m),
  6097. 'detail' => $dr,
  6098. ];
  6099. }
  6100. $groups = [];
  6101. foreach ($exportLines as $line) {
  6102. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  6103. if (!isset($groups[$k])) {
  6104. $groups[$k] = [];
  6105. }
  6106. $groups[$k][] = $line;
  6107. }
  6108. ksort($groups, SORT_STRING);
  6109. $spreadsheet = new Spreadsheet();
  6110. $sheet = $spreadsheet->getActiveSheet();
  6111. $sheet->setTitle('外发明细');
  6112. $mon = (int)substr($ym, 5, 2);
  6113. $sheet->mergeCells('A1:H1');
  6114. $sheet->setCellValue('A1', $mon . '月外发明细');
  6115. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  6116. $sheet->getStyle('A1')->getAlignment()
  6117. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  6118. ->setVertical(Alignment::VERTICAL_CENTER);
  6119. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  6120. $col = 'A';
  6121. foreach ($headers as $h) {
  6122. $sheet->setCellValue($col . '2', $h);
  6123. $col++;
  6124. }
  6125. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  6126. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6127. $rowNum = 3;
  6128. $sumSubtotalCounts = 0;
  6129. $grandAmount = 0.0;
  6130. if ($groups === []) {
  6131. $sheet->mergeCells('A3:H3');
  6132. $sheet->setCellValue('A3', '(当月暂无符合条件的外发明细)');
  6133. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6134. $rowNum = 4;
  6135. } else {
  6136. foreach ($groups as $items) {
  6137. if ($items === []) {
  6138. continue;
  6139. }
  6140. $groupLineCount = count($items);
  6141. $subAmount = 0.0;
  6142. $i = 0;
  6143. foreach ($items as $line) {
  6144. $i++;
  6145. $dr = $line['detail'];
  6146. $amt = $this->procuremenExportAmount($dr);
  6147. $subAmount += $amt;
  6148. $sheet->setCellValue('A' . $rowNum, $i);
  6149. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  6150. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  6151. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  6152. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  6153. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  6154. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  6155. $sheet->setCellValue('H' . $rowNum, $amt);
  6156. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  6157. $rowNum++;
  6158. }
  6159. $sumSubtotalCounts += $groupLineCount;
  6160. $grandAmount += $subAmount;
  6161. $sheet->setCellValue('A' . $rowNum, $groupLineCount);
  6162. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6163. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  6164. $sheet->getStyle('G' . $rowNum)->getAlignment()
  6165. ->setHorizontal(Alignment::HORIZONTAL_RIGHT)
  6166. ->setVertical(Alignment::VERTICAL_CENTER);
  6167. $rowNum++;
  6168. }
  6169. }
  6170. $sheet->setCellValue('A' . $rowNum, '总计');
  6171. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  6172. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6173. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  6174. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  6175. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  6176. $lastRow = $rowNum;
  6177. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  6178. 'borders' => [
  6179. 'allBorders' => [
  6180. 'borderStyle' => Border::BORDER_THIN,
  6181. 'color' => ['rgb' => '000000'],
  6182. ],
  6183. ],
  6184. ]);
  6185. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  6186. if ($lastRow >= 3) {
  6187. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6188. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6189. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6190. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6191. }
  6192. $sheet->getColumnDimension('A')->setWidth(7);
  6193. $sheet->getColumnDimension('B')->setWidth(16);
  6194. $sheet->getColumnDimension('C')->setWidth(52);
  6195. $sheet->getColumnDimension('D')->setWidth(32);
  6196. $sheet->getColumnDimension('E')->setWidth(12);
  6197. $sheet->getColumnDimension('F')->setWidth(44);
  6198. $sheet->getColumnDimension('G')->setWidth(26);
  6199. $sheet->getColumnDimension('H')->setWidth(13);
  6200. $sheet->getRowDimension(1)->setRowHeight(28);
  6201. $fileBase = '外发明细_' . str_replace('-', '', $ym);
  6202. $filename = $fileBase . '.xlsx';
  6203. try {
  6204. $this->ensurePurchaseMonthExportLogTable();
  6205. list($adminId, $adminName) = $this->GetUseName();
  6206. Db::table('purchase_month_export_log')->insert([
  6207. 'ym' => $ym,
  6208. 'admin_id' => (int)$adminId,
  6209. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  6210. 'row_count' => count($exportLines),
  6211. 'total_amount' => round($grandAmount, 2),
  6212. 'createtime' => time(),
  6213. ]);
  6214. } catch (\Throwable $e) {
  6215. Log::write('month export log: ' . $e->getMessage(), 'error');
  6216. }
  6217. if (ob_get_length()) {
  6218. ob_end_clean();
  6219. }
  6220. $asciiName = 'outward_' . str_replace('-', '', $ym) . '.xlsx';
  6221. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  6222. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  6223. header('Cache-Control: max-age=0');
  6224. $writer = new Xlsx($spreadsheet);
  6225. $writer->save('php://output');
  6226. $spreadsheet->disconnectWorksheets();
  6227. unset($spreadsheet);
  6228. exit;
  6229. }
  6230. /**
  6231. * 导出用:工序列文案
  6232. */
  6233. protected function procuremenExportGxText(array $r)
  6234. {
  6235. $a = trim((string)($r['CDXMC'] ?? ''));
  6236. $b = trim((string)($r['CGYMC'] ?? ''));
  6237. if ($a !== '' && $b !== '') {
  6238. return $a . ':' . $b;
  6239. }
  6240. return $a !== '' ? $a : $b;
  6241. }
  6242. /**
  6243. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  6244. */
  6245. protected function procuremenExportAmount(array $r)
  6246. {
  6247. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  6248. if (!array_key_exists($k, $r)) {
  6249. continue;
  6250. }
  6251. $v = $r[$k];
  6252. if ($v === null || $v === '') {
  6253. continue;
  6254. }
  6255. if (is_numeric($v)) {
  6256. return (float)$v;
  6257. }
  6258. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  6259. if ($v !== '' && is_numeric($v)) {
  6260. return (float)$v;
  6261. }
  6262. }
  6263. return 0.0;
  6264. }
  6265. /**
  6266. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  6267. */
  6268. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  6269. {
  6270. $s = trim($ccydh);
  6271. if ($s === '') {
  6272. return 'ORDER';
  6273. }
  6274. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  6275. $s = trim($s, '._-');
  6276. if ($s === '') {
  6277. return 'ORDER';
  6278. }
  6279. if (function_exists('mb_substr')) {
  6280. return mb_substr($s, 0, 80, 'UTF-8');
  6281. }
  6282. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  6283. }
  6284. /**
  6285. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  6286. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  6287. *
  6288. * @return array{objectKey: string, webPath: string}
  6289. */
  6290. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  6291. {
  6292. $sid = (int)$scydgyId;
  6293. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  6294. $y = date('Y');
  6295. $m = date('m');
  6296. $d = date('d');
  6297. $basename = $safeOrder . '_' . $sid . '.pdf';
  6298. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  6299. return [
  6300. 'objectKey' => $objectKey,
  6301. 'webPath' => '/' . $objectKey,
  6302. ];
  6303. }
  6304. /**
  6305. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  6306. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  6307. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  6308. *
  6309. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  6310. */
  6311. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  6312. {
  6313. if (!$this->isValidScydgyRowId($scydgyId)) {
  6314. return '';
  6315. }
  6316. $ids = trim((string)$scydgyId);
  6317. $prep = $this->prepareProcuremenDetailsView($ids);
  6318. if (!$prep['ok']) {
  6319. return '';
  6320. }
  6321. $ccydh = $prep['ccydh'];
  6322. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  6323. $objectKey = $paths['objectKey'];
  6324. $webPath = $paths['webPath'];
  6325. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  6326. $this->view->assign([
  6327. 'pdf_export' => 1,
  6328. 'pdfMetaLine' => $meta,
  6329. ]);
  6330. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  6331. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6332. $this->view->engine->layout(false);
  6333. try {
  6334. $html = $this->view->fetch('procuremen/details_pdf_shell');
  6335. } catch (\Throwable $e) {
  6336. if ($restoreLayout) {
  6337. $this->view->engine->layout($restoreLayout);
  6338. }
  6339. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  6340. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  6341. return '';
  6342. }
  6343. if ($restoreLayout) {
  6344. $this->view->engine->layout($restoreLayout);
  6345. }
  6346. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  6347. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  6348. if (!is_dir($tempDir)) {
  6349. @mkdir($tempDir, 0755, true);
  6350. }
  6351. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  6352. try {
  6353. $mpdf = new \Mpdf\Mpdf([
  6354. 'mode' => 'utf-8',
  6355. 'format' => 'A4',
  6356. 'margin_left' => 12,
  6357. 'margin_right' => 12,
  6358. 'margin_top' => 14,
  6359. 'margin_bottom' => 14,
  6360. 'tempDir' => $tempDir,
  6361. 'autoScriptToLang' => true,
  6362. 'autoLangToFont' => true,
  6363. ]);
  6364. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  6365. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  6366. $mpdf->SetBasePath('http://127.0.0.1/');
  6367. $mpdf->WriteHTML($html);
  6368. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  6369. } catch (\Throwable $e) {
  6370. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  6371. if (is_file($tempPdf)) {
  6372. @unlink($tempPdf);
  6373. }
  6374. return '';
  6375. }
  6376. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  6377. if ($ossUrl !== '') {
  6378. @unlink($tempPdf);
  6379. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  6380. return $ossUrl;
  6381. }
  6382. $pi = pathinfo($objectKey);
  6383. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  6384. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  6385. if ($baseFile === '') {
  6386. @unlink($tempPdf);
  6387. return '';
  6388. }
  6389. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  6390. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  6391. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  6392. @unlink($tempPdf);
  6393. return '';
  6394. }
  6395. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  6396. if (!@copy($tempPdf, $fullPath)) {
  6397. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  6398. @unlink($tempPdf);
  6399. return '';
  6400. }
  6401. @unlink($tempPdf);
  6402. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  6403. return $webPath;
  6404. }
  6405. /**
  6406. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  6407. */
  6408. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  6409. {
  6410. if ($scydgyId <= 0 || $webPath === '') {
  6411. return;
  6412. }
  6413. try {
  6414. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  6415. } catch (\Throwable $e) {
  6416. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  6417. }
  6418. }
  6419. /**
  6420. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  6421. *
  6422. * @param array<string, string> $vars
  6423. * @return array<string, string>
  6424. */
  6425. protected function normalizeSmsTemplateVars(array $vars): array
  6426. {
  6427. $out = [];
  6428. foreach ($vars as $k => $v) {
  6429. $out[(string)$k] = trim((string)$v);
  6430. }
  6431. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  6432. $out['contact_name'] = $out['company_name'];
  6433. }
  6434. return $out;
  6435. }
  6436. /**
  6437. * 按手机号或公司名称查 customer 表联系人姓名
  6438. */
  6439. protected function resolveCustomerContactName(string $phone, string $companyName): string
  6440. {
  6441. $phone = trim($phone);
  6442. $companyName = trim($companyName);
  6443. try {
  6444. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  6445. $row = Db::table('customer')
  6446. ->where(function ($q) use ($phone) {
  6447. $q->where('phone', $phone)->whereOr('account', $phone);
  6448. })
  6449. ->order('id', 'asc')
  6450. ->find();
  6451. if (is_array($row)) {
  6452. $nm = trim((string)($row['username'] ?? ''));
  6453. if ($nm !== '') {
  6454. return $nm;
  6455. }
  6456. }
  6457. }
  6458. if ($companyName !== '') {
  6459. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  6460. if (is_array($row)) {
  6461. return trim((string)($row['username'] ?? ''));
  6462. }
  6463. }
  6464. } catch (\Throwable $e) {
  6465. }
  6466. return '';
  6467. }
  6468. /**
  6469. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  6470. */
  6471. protected function plainTextToHtmlEmailBody(string $text): string
  6472. {
  6473. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  6474. $parts = explode("\n", $text);
  6475. $out = [];
  6476. foreach ($parts as $line) {
  6477. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  6478. $out[] = $line;
  6479. } else {
  6480. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  6481. }
  6482. }
  6483. return implode("<br>\n", $out);
  6484. }
  6485. /**
  6486. * 短信场景:去掉链接类变量,避免误填 URL
  6487. *
  6488. * @param array<string, string> $vars
  6489. * @return array<string, string>
  6490. */
  6491. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  6492. {
  6493. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  6494. return $vars;
  6495. }
  6496. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  6497. $vars[$k] = '';
  6498. }
  6499. return $vars;
  6500. }
  6501. /**
  6502. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  6503. *
  6504. * @param array<string, string> $vars
  6505. */
  6506. protected function renderNotifyTemplate(string $scene, array $vars): string
  6507. {
  6508. $vars = $this->normalizeSmsTemplateVars($vars);
  6509. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  6510. $row = $this->loadNotifyTemplateRow($scene);
  6511. if ($row === null) {
  6512. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  6513. }
  6514. $tpl = trim((string)($row['content'] ?? ''));
  6515. if ($tpl === '') {
  6516. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  6517. }
  6518. foreach ($vars as $k => $v) {
  6519. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  6520. }
  6521. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  6522. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  6523. return $tpl;
  6524. }
  6525. protected function resolveProcuremenEmailSubject(string $scene): string
  6526. {
  6527. $map = [
  6528. 'review_email' => '您有新的外发加工订单',
  6529. ];
  6530. $subject = trim((string)($map[$scene] ?? ''));
  6531. if ($subject === '') {
  6532. $this->error('未配置邮件主题:' . $scene);
  6533. }
  6534. return $subject;
  6535. }
  6536. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  6537. {
  6538. $map = [
  6539. 'review_email' => '外发下发-邮箱',
  6540. 'review_sms' => '外发下发-短信',
  6541. 'confirm_ok' => '采购确认-通过',
  6542. 'confirm_fail' => '采购确认-未通过',
  6543. ];
  6544. $label = $map[$scene] ?? $scene;
  6545. if ($titleRequired) {
  6546. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  6547. }
  6548. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  6549. }
  6550. /** @deprecated 使用 renderNotifyTemplate */
  6551. protected function renderSmsTemplate(string $scene, array $vars): string
  6552. {
  6553. return $this->renderNotifyTemplate($scene, $vars);
  6554. }
  6555. /**
  6556. * 是否开启外发通知演练(不发真实短信/邮件)
  6557. */
  6558. protected function isProcuremenNotifyDryRun(): bool
  6559. {
  6560. return (bool)Config::get('procuremen_notify_dry_run');
  6561. }
  6562. /**
  6563. * @param array<string, mixed> $payload
  6564. */
  6565. protected function recordNotifyDryRunPreview(array $payload): void
  6566. {
  6567. $this->notifyDryRunPreview[] = $payload;
  6568. Log::write('[外发通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6569. }
  6570. /**
  6571. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  6572. * @throws \Exception
  6573. */
  6574. protected function smsbao($phone, $content)
  6575. {
  6576. if ($this->isProcuremenNotifyDryRun()) {
  6577. $this->recordNotifyDryRunPreview([
  6578. 'scene' => 'sms_only',
  6579. 'phone' => $phone,
  6580. 'sms_content' => $content,
  6581. ]);
  6582. return;
  6583. }
  6584. $statusStr = [
  6585. '0' => '短信发送成功',
  6586. '-1' => '参数不全',
  6587. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  6588. '30' => '密码错误',
  6589. '40' => '账号不存在',
  6590. '41' => '余额不足',
  6591. '42' => '帐户已过期',
  6592. '43' => 'IP地址限制',
  6593. '50' => '内容含有敏感词',
  6594. ];
  6595. $smsapi = 'http://api.smsbao.com/';
  6596. $user = 'zhuwei123';
  6597. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  6598. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  6599. $result = @file_get_contents($sendurl);
  6600. if ($result === false) {
  6601. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  6602. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  6603. }
  6604. $result = trim((string)$result);
  6605. if ($result !== '0') {
  6606. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  6607. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  6608. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  6609. }
  6610. }
  6611. }