Procuremen.php 331 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenStatus;
  8. use app\common\library\ProcuremenTime;
  9. use PHPMailer\PHPMailer\PHPMailer;
  10. use think\Config;
  11. use think\Cache;
  12. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  13. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  14. use PhpOffice\PhpSpreadsheet\Style\Border;
  15. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  16. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  17. use think\Db;
  18. use think\Log;
  19. class Procuremen extends Backend
  20. {
  21. /**
  22. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  23. */
  24. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  25. /**
  26. * Procuremen模型对象
  27. * @var \app\admin\model\Procuremen
  28. */
  29. protected $model = null;
  30. /**
  31. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  32. */
  33. protected $notifyDryRunPreview = [];
  34. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  35. protected $procuremenRedisCache = null;
  36. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  37. protected $pickHiddenScydgySetCache = null;
  38. /** 邮件发送日志表结构已就绪缓存键 */
  39. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  40. /**
  41. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  42. * @var array
  43. */
  44. protected $noNeedRight = [
  45. 'pickreview', 'review', 'reviewcompanies',
  46. ];
  47. public function _initialize()
  48. {
  49. parent::_initialize();
  50. $this->model = new \app\admin\model\Procuremen;
  51. $this->maybeMigrateLegacyWflowStatusText();
  52. $this->assignProcuremenAuthConfig();
  53. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  54. $this->ensurePurchaseEmailSendLogTableOnce();
  55. }
  56. }
  57. /**
  58. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  59. */
  60. protected function maybeMigrateLegacyWflowStatusText(): void
  61. {
  62. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  63. if (is_file($flagFile)) {
  64. return;
  65. }
  66. $map = [
  67. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  68. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  69. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  70. '3' => ProcuremenStatus::WFLOW_APPROVED,
  71. ];
  72. try {
  73. foreach ($map as $num => $text) {
  74. Db::table('purchase_order')
  75. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  76. ->update(['wflow_status' => $text]);
  77. }
  78. @file_put_contents($flagFile, date('c'));
  79. } catch (\Throwable $e) {
  80. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  81. }
  82. }
  83. /**
  84. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  85. *
  86. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  87. */
  88. protected function hasProcuremenPerm(array $actions): bool
  89. {
  90. foreach ($actions as $action) {
  91. $action = strtolower(trim((string)$action));
  92. if ($action === '') {
  93. continue;
  94. }
  95. if (strpos($action, 'procuremen/') !== 0) {
  96. $action = 'procuremen/' . $action;
  97. }
  98. if ($this->auth->check($action)) {
  99. return true;
  100. }
  101. }
  102. $suffixes = [];
  103. foreach ($actions as $action) {
  104. $action = strtolower(trim((string)$action));
  105. $action = preg_replace('#^procuremen/#', '', $action);
  106. if ($action !== '') {
  107. $suffixes[$action] = true;
  108. }
  109. }
  110. if ($suffixes === []) {
  111. return false;
  112. }
  113. try {
  114. foreach ($this->auth->getRuleList() as $rule) {
  115. $rule = strtolower((string)$rule);
  116. if (strpos($rule, 'procuremen/') !== 0) {
  117. continue;
  118. }
  119. foreach (array_keys($suffixes) as $suffix) {
  120. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  121. return true;
  122. }
  123. }
  124. }
  125. } catch (\Throwable $e) {
  126. }
  127. return false;
  128. }
  129. /**
  130. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  131. *
  132. * @param string[] $actions
  133. */
  134. protected function hasProcuremenPermStrict(array $actions): bool
  135. {
  136. foreach ($actions as $action) {
  137. $action = strtolower(trim((string)$action));
  138. if ($action === '') {
  139. continue;
  140. }
  141. if (strpos($action, 'procuremen/') !== 0) {
  142. $action = 'procuremen/' . $action;
  143. }
  144. if ($this->auth->check($action)) {
  145. return true;
  146. }
  147. }
  148. return false;
  149. }
  150. /**
  151. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  152. *
  153. * @param string[] $titles
  154. */
  155. protected function authHasAssignedRuleTitle(array $titles): bool
  156. {
  157. $titles = array_values(array_filter(array_map('trim', $titles)));
  158. if ($titles === []) {
  159. return false;
  160. }
  161. try {
  162. $ids = $this->auth->getRuleIds();
  163. if (in_array('*', $ids, true)) {
  164. return true;
  165. }
  166. if ($ids === []) {
  167. return false;
  168. }
  169. $rows = Db::name('auth_rule')
  170. ->where('status', 'normal')
  171. ->whereIn('id', $ids)
  172. ->column('title');
  173. foreach ($rows as $title) {
  174. $t = trim((string)$title);
  175. if ($t !== '' && in_array($t, $titles, true)) {
  176. return true;
  177. }
  178. }
  179. } catch (\Throwable $e) {
  180. }
  181. return false;
  182. }
  183. protected function procuremenCanPickDelete(): bool
  184. {
  185. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  186. return true;
  187. }
  188. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  189. }
  190. protected function procuremenCanComplete(): bool
  191. {
  192. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  193. return true;
  194. }
  195. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  196. }
  197. protected function procuremenCanDispatch(): bool
  198. {
  199. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  200. }
  201. /**
  202. * 前端按钮显隐(Config.procuremenAuth)
  203. */
  204. protected function assignProcuremenAuthConfig(): void
  205. {
  206. $authMap = [
  207. 'pickreview' => $this->procuremenCanDispatch(),
  208. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  209. 'pickdelete' => $this->procuremenCanPickDelete(),
  210. 'completedirectly' => $this->procuremenCanComplete(),
  211. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  212. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  213. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  214. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  215. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  216. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  217. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  218. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  219. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  220. 'details' => $this->hasProcuremenPerm(['details']),
  221. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  222. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  223. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  224. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  225. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  226. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  227. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  228. 'add' => $this->hasProcuremenPerm(['add']),
  229. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  230. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  231. ];
  232. $this->assignconfig('procuremenAuth', $authMap);
  233. }
  234. /**
  235. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  236. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  237. *
  238. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  239. */
  240. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  241. {
  242. static $mprocCfgLoaded = false;
  243. if (!$mprocCfgLoaded) {
  244. $mprocCfgLoaded = true;
  245. if (is_file(APP_PATH . 'extra/mproc.php')) {
  246. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  247. }
  248. }
  249. $eid = (int)$purchaseOrderDetailId;
  250. $base = $this->resolveMprocMobilePublicBaseUrl();
  251. if ($base === '') {
  252. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  253. }
  254. $path = trim((string)Config::get('mproc.mobile_index_path'));
  255. if ($path === '') {
  256. $path = '/index.php/index/index/index';
  257. } else {
  258. $path = '/' . ltrim($path, '/');
  259. }
  260. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  261. if ($eid > 0) {
  262. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  263. }
  264. return $base . $path . '?main_tab=orders';
  265. }
  266. /**
  267. * 邮件/短信外链:须为带点的公网域名
  268. */
  269. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  270. {
  271. $u = trim((string)$baseUrl);
  272. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  273. return false;
  274. }
  275. $host = parse_url($u, PHP_URL_HOST);
  276. if (!is_string($host) || $host === '') {
  277. return false;
  278. }
  279. if (strcasecmp($host, 'localhost') === 0) {
  280. return false;
  281. }
  282. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  283. return false;
  284. }
  285. if (strpos($host, '.') === false) {
  286. return false;
  287. }
  288. return true;
  289. }
  290. /**
  291. * 解析用于协助邮件/短信的手机端站点根
  292. */
  293. protected function resolveMprocMobilePublicBaseUrl()
  294. {
  295. $candidates = [];
  296. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  297. $candidates[] = trim((string)Config::get('site.indexurl'));
  298. $cdn = trim((string)Config::get('site.cdnurl'));
  299. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  300. $candidates[] = rtrim($cdn, '/');
  301. }
  302. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  303. $candidates[] = $reqBase;
  304. foreach ($candidates as $c) {
  305. if ($c === '') {
  306. continue;
  307. }
  308. $c = rtrim($c, '/');
  309. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  310. return $c;
  311. }
  312. }
  313. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  314. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  315. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  316. return $reqBase;
  317. }
  318. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  319. return '';
  320. }
  321. /**
  322. * 获取 Redis 中 procuremen_redis
  323. */
  324. protected function ProcuremenRedis(): array
  325. {
  326. if ($this->procuremenRedisCache !== null) {
  327. return $this->procuremenRedisCache;
  328. }
  329. try {
  330. $redis = redis();
  331. $raw = $redis->get('procuremen_redis');
  332. if ($raw === false || $raw === '') {
  333. $this->procuremenRedisCache = [];
  334. return $this->procuremenRedisCache;
  335. }
  336. $decoded = json_decode($raw, true);
  337. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  338. $this->procuremenRedisCache = [];
  339. return $this->procuremenRedisCache;
  340. }
  341. $this->procuremenRedisCache = $decoded['data'];
  342. return $this->procuremenRedisCache;
  343. } catch (\Throwable $e) {
  344. $this->procuremenRedisCache = [];
  345. return $this->procuremenRedisCache;
  346. }
  347. }
  348. /**
  349. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  350. *
  351. * @return array<int, array<string, mixed>>
  352. */
  353. protected function procuremenFetchErpPoolFromDb(): array
  354. {
  355. try {
  356. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  357. $endTime = date('Y-m-d 23:59:59');
  358. $list = Db::table('scydgy')
  359. ->alias('a')
  360. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  361. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  362. ->where([
  363. 'a.bwjg' => 1,
  364. 'a.iEndBz' => 0,
  365. 'a.iType' => 0,
  366. 'a.iStatus' => 10,
  367. ])
  368. ->where('a.dStamp', '>=', $startTime)
  369. ->where('a.dStamp', '<=', $endTime)
  370. ->order('a.dStamp', 'desc')
  371. ->select();
  372. if (!is_array($list)) {
  373. return [];
  374. }
  375. try {
  376. $redis = redis();
  377. $payload = [
  378. 'code' => 200,
  379. 'msg' => 'success',
  380. 'data' => $list,
  381. ];
  382. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  383. $this->procuremenRedisCache = $list;
  384. } catch (\Throwable $e) {
  385. }
  386. return $list;
  387. } catch (\Throwable $e) {
  388. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  389. return [];
  390. }
  391. }
  392. /**
  393. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  394. *
  395. * @return array<int, array<string, mixed>>
  396. */
  397. protected function procuremenEnsureRedisPool(): array
  398. {
  399. $pool = $this->ProcuremenRedis();
  400. if (is_array($pool) && $pool !== []) {
  401. return $pool;
  402. }
  403. static $warmed = false;
  404. if ($warmed) {
  405. return is_array($pool) ? $pool : [];
  406. }
  407. $warmed = true;
  408. return $this->procuremenFetchErpPoolFromDb();
  409. }
  410. /**
  411. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  412. *
  413. * @param array<string, mixed> $row
  414. */
  415. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  416. {
  417. $t = $this->procuremenRowListSortTime($row, $primary);
  418. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  419. return null;
  420. }
  421. $mo = (int)$m[2];
  422. if ($mo < 1 || $mo > 12) {
  423. return null;
  424. }
  425. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  426. }
  427. /**
  428. * @param array<int, array{year:string, months:array}> $sidebar
  429. * @return array<int, array{year:string, months:array}>
  430. */
  431. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  432. {
  433. $ym = trim($ym);
  434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  435. return $sidebar;
  436. }
  437. foreach ($sidebar as $block) {
  438. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  439. continue;
  440. }
  441. foreach ($block['months'] as $item) {
  442. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  443. return $sidebar;
  444. }
  445. }
  446. }
  447. $y = substr($ym, 0, 4);
  448. $mo = (int)substr($ym, 5, 2);
  449. $sidebar[] = [
  450. 'year' => $y,
  451. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  452. ];
  453. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  454. }
  455. /**
  456. * @param array<int, array{year:string, months:array}> $sidebar
  457. * @return string[]
  458. */
  459. protected function flattenProcuremenSidebarYms(array $sidebar): array
  460. {
  461. $yms = [];
  462. foreach ($sidebar as $block) {
  463. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  464. continue;
  465. }
  466. foreach ($block['months'] as $item) {
  467. if (!is_array($item)) {
  468. continue;
  469. }
  470. $ym = trim((string)($item['ym'] ?? ''));
  471. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  472. $yms[$ym] = true;
  473. }
  474. }
  475. }
  476. return array_keys($yms);
  477. }
  478. /**
  479. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  480. */
  481. protected function GetIndexYearMonths()
  482. {
  483. $ymSet = [];
  484. $pool = $this->procuremenEnsureRedisPool();
  485. foreach ($pool as $r) {
  486. if (!is_array($r)) {
  487. continue;
  488. }
  489. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  490. if ($ym !== null) {
  491. $ymSet[$ym] = true;
  492. }
  493. }
  494. foreach ($this->loadPickManualOrderRows() as $r) {
  495. if (!is_array($r)) {
  496. continue;
  497. }
  498. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  499. if ($ym !== null) {
  500. $ymSet[$ym] = true;
  501. }
  502. }
  503. $ymList = array_keys($ymSet);
  504. if ($ymList === []) {
  505. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  506. }
  507. return $this->buildYearMonthSidebar($ymList);
  508. }
  509. /**
  510. * @param string[] $ymList 形如 2026-06
  511. * @return array<int, array{year:string, months:array}>
  512. */
  513. protected function buildYearMonthSidebar(array $ymList): array
  514. {
  515. rsort($ymList, SORT_STRING);
  516. $byYear = [];
  517. foreach ($ymList as $ym) {
  518. $y = substr($ym, 0, 4);
  519. $mo = (int)substr($ym, 5, 2);
  520. if (!isset($byYear[$y])) {
  521. $byYear[$y] = [];
  522. }
  523. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  524. }
  525. krsort($byYear, SORT_NUMERIC);
  526. foreach ($byYear as $y => $items) {
  527. usort($byYear[$y], function ($a, $b) {
  528. return strcmp($b['ym'], $a['ym']);
  529. });
  530. }
  531. $sidebar = [];
  532. foreach ($byYear as $y => $months) {
  533. $sidebar[] = ['year' => $y, 'months' => $months];
  534. }
  535. return $sidebar;
  536. }
  537. /**
  538. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  539. */
  540. protected function GetIssuedOrderYearMonths(string $stage): array
  541. {
  542. $ymSet = [];
  543. try {
  544. $query = Db::table('purchase_order');
  545. $this->applyPurchaseOrderNotDeletedWhere($query);
  546. if ($stage === 'audit') {
  547. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  548. } elseif ($stage === 'confirm') {
  549. $this->applyPurchaseOrderConfirmStageWhere($query);
  550. } else {
  551. return $this->GetIndexYearMonths();
  552. }
  553. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  554. if (is_array($rows)) {
  555. foreach ($rows as $r) {
  556. if (!is_array($r)) {
  557. continue;
  558. }
  559. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  560. if ($ym !== null) {
  561. $ymSet[$ym] = true;
  562. }
  563. }
  564. }
  565. } catch (\Throwable $e) {
  566. $ymSet = [];
  567. }
  568. $ymList = array_keys($ymSet);
  569. if ($ymList === []) {
  570. $def = $this->resolveProcuremenDefaultYm($stage);
  571. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  572. }
  573. return $this->buildYearMonthSidebar($ymList);
  574. }
  575. /**
  576. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  577. */
  578. protected function resolveProcuremenDefaultYm(string $stage): string
  579. {
  580. if ($stage === 'pick') {
  581. return date('Y-m');
  582. }
  583. try {
  584. $query = Db::table('purchase_order');
  585. $this->applyPurchaseOrderNotDeletedWhere($query);
  586. if ($stage === 'audit') {
  587. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  588. } elseif ($stage === 'confirm') {
  589. $this->applyPurchaseOrderConfirmStageWhere($query);
  590. } else {
  591. return date('Y-m');
  592. }
  593. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  594. if ($latest === null || $latest === '') {
  595. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  596. }
  597. $t = $this->formatProcuremenDetailTime($latest);
  598. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  599. return $m[1] . '-' . $m[2];
  600. }
  601. } catch (\Throwable $e) {
  602. }
  603. return date('Y-m');
  604. }
  605. protected function applyPurchaseOrderNotDeletedWhere($query): void
  606. {
  607. $query->whereRaw(
  608. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  609. );
  610. }
  611. /**
  612. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  613. */
  614. protected function applyPurchaseOrderConfirmStageWhere($query): void
  615. {
  616. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  617. $quoted = [];
  618. foreach ($vals as $v) {
  619. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  620. }
  621. if ($quoted === []) {
  622. $query->whereRaw('1 = 0');
  623. return;
  624. }
  625. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  626. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  627. }
  628. /**
  629. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  630. *
  631. * @param array<string, mixed> $row
  632. * @return array<string, mixed>
  633. */
  634. protected function normalizePurchaseOrderListTimeRow(array $row): array
  635. {
  636. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  637. $pick = trim((string)($row['pick_time'] ?? ''));
  638. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  639. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  640. $t = trim((string)($row[$key] ?? ''));
  641. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  642. $row['pick_time'] = $t;
  643. break;
  644. }
  645. }
  646. }
  647. return $row;
  648. }
  649. /**
  650. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  651. */
  652. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  653. {
  654. if (!in_array($stage, ['audit', 'confirm'], true)) {
  655. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  656. }
  657. if ($pool === []) {
  658. $def = $this->resolveProcuremenDefaultYm($stage);
  659. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  660. }
  661. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  662. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  663. return false;
  664. }
  665. $monthStart = $ym . '-01 00:00:00';
  666. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  667. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  668. return $probe !== [];
  669. };
  670. if ($tryYm($requestedYm)) {
  671. return $requestedYm;
  672. }
  673. $fallback = $this->resolveProcuremenDefaultYm($stage);
  674. if ($tryYm($fallback)) {
  675. return $fallback;
  676. }
  677. $bestYm = '';
  678. $bestTime = '';
  679. foreach ($pool as $row) {
  680. if (!is_array($row)) {
  681. continue;
  682. }
  683. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  684. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  685. continue;
  686. }
  687. $ymRow = $m[1];
  688. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  689. $bestTime = $t;
  690. $bestYm = $ymRow;
  691. }
  692. }
  693. if ($bestYm !== '') {
  694. return $bestYm;
  695. }
  696. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  697. }
  698. protected function isPurchaseOrderDetailVoid(array $row): bool
  699. {
  700. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  701. return true;
  702. }
  703. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  704. }
  705. /**
  706. * 仅当前有效下发明细(排除废弃归档)
  707. */
  708. protected function applyActivePurchaseOrderDetailWhere($query): void
  709. {
  710. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  711. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  712. }
  713. /**
  714. * @param array<string, mixed> $detailRow
  715. */
  716. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  717. {
  718. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  719. return false;
  720. }
  721. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  722. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  723. }
  724. /**
  725. * 废弃退回初选:下发明细标记归档,不物理删除
  726. *
  727. * @param array<int, int|string> $scydgyIds
  728. */
  729. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  730. {
  731. $ids = [];
  732. foreach ($scydgyIds as $sid) {
  733. $n = (int)$sid;
  734. if ($this->isValidScydgyRowId($n) || $n < 0) {
  735. $ids[$n] = true;
  736. }
  737. }
  738. if ($ids === []) {
  739. return;
  740. }
  741. $void = ProcuremenStatus::POD_VOID;
  742. Db::table('purchase_order_detail')
  743. ->where('scydgy_id', 'in', array_keys($ids))
  744. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  745. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  746. ->update([
  747. 'status' => $void,
  748. 'status_name' => $void,
  749. ]);
  750. }
  751. /**
  752. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  753. */
  754. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  755. {
  756. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  757. $norm = function (string $col) use ($p): string {
  758. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  759. };
  760. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  761. $parts = [];
  762. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  763. if ($key === 'createtime') {
  764. $parts[] = $createtime;
  765. } else {
  766. $parts[] = $norm($key);
  767. }
  768. }
  769. return 'COALESCE(' . implode(', ', $parts) . ')';
  770. }
  771. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  772. {
  773. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  774. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  775. }
  776. /**
  777. * @return array<int, array<string, mixed>>
  778. */
  779. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  780. {
  781. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  782. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  783. try {
  784. $query = Db::table('purchase_order')->field($fields);
  785. $this->applyPurchaseOrderNotDeletedWhere($query);
  786. if ($stage === 'audit') {
  787. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  788. } elseif ($stage === 'confirm') {
  789. $this->applyPurchaseOrderConfirmStageWhere($query);
  790. } else {
  791. return [];
  792. }
  793. $query->order('pick_time', 'desc')->order('id', 'desc');
  794. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  795. $monthStart = $ym . '-01 00:00:00';
  796. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  797. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  798. }
  799. $rows = $query->select();
  800. } catch (\Throwable $e) {
  801. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  802. $rows = [];
  803. }
  804. return is_array($rows) ? $rows : [];
  805. }
  806. /**
  807. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  808. */
  809. protected function resolveProcuremenListStage(): string
  810. {
  811. $tab = trim((string)$this->request->request('wff_tab', ''));
  812. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  813. return $tab;
  814. }
  815. $action = strtolower((string)$this->request->action());
  816. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  817. return $action;
  818. }
  819. return 'pick';
  820. }
  821. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  822. {
  823. $rootTrue = rtrim((string)$this->request->root(true), '/');
  824. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  825. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  826. $indexPhpRoot = $rootTrue . '/index.php';
  827. }
  828. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  829. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  830. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  831. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  832. $this->view->assign('defaultYm', $defaultYm);
  833. $this->view->assign('sidebarYearMonths', $sidebar);
  834. $this->view->assign('procuremenStage', $stage);
  835. $this->view->assign('procuremenPageTitle', $pageTitle);
  836. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  837. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  838. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  839. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  840. }
  841. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  842. public function pick()
  843. {
  844. $this->request->filter(['strip_tags', 'trim']);
  845. if (!$this->request->isAjax()) {
  846. $this->assignProcuremenListPage('pick', '协助下发');
  847. return $this->view->fetch('procuremen/index');
  848. }
  849. return $this->index();
  850. }
  851. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  852. public function audit()
  853. {
  854. $this->request->filter(['strip_tags', 'trim']);
  855. if (!$this->request->isAjax()) {
  856. $this->assignProcuremenListPage('audit', '确认供应商');
  857. return $this->view->fetch('procuremen/index');
  858. }
  859. return $this->index();
  860. }
  861. /** 采购确认(定标) */
  862. public function confirm()
  863. {
  864. $this->request->filter(['strip_tags', 'trim']);
  865. if (!$this->request->isAjax()) {
  866. $this->assignProcuremenListPage('confirm', '采购确认');
  867. return $this->view->fetch('procuremen/index');
  868. }
  869. return $this->index();
  870. }
  871. /**
  872. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  873. */
  874. public function index()
  875. {
  876. $this->request->filter(['strip_tags', 'trim']);
  877. if (!$this->request->isAjax()) {
  878. $this->assignProcuremenListPage('pick', '协助下发');
  879. return $this->view->fetch('procuremen/index');
  880. }
  881. if ($this->request->request('keyField')) {
  882. return $this->selectpage();
  883. }
  884. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  885. $limit = max(10, min(500, (int)$limit));
  886. $ym = $this->request->request('ym', '');
  887. $ym = is_string($ym) ? trim($ym) : '';
  888. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  889. $wffTab = $this->resolveProcuremenListStage();
  890. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  891. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  892. ? $this->resolveProcuremenDefaultYm($wffTab)
  893. : date('Y-m');
  894. }
  895. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  896. $ym = date('Y-m');
  897. }
  898. $monthStart = $ym . '-01 00:00:00';
  899. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  900. $search = trim((string)$this->request->get('search', ''));
  901. $hasActiveSearch = ($search !== '');
  902. if (!$hasActiveSearch) {
  903. $filterStr = $this->request->get('filter', '');
  904. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  905. $arr = json_decode($filterStr, true);
  906. if (is_array($arr) && count($arr) > 0) {
  907. foreach ($arr as $v) {
  908. if (is_array($v)) {
  909. if (array_filter($v, function ($x) {
  910. return $x !== '' && $x !== null;
  911. })) {
  912. $hasActiveSearch = true;
  913. break;
  914. }
  915. } elseif ($v !== '' && $v !== null) {
  916. $hasActiveSearch = true;
  917. break;
  918. }
  919. }
  920. }
  921. }
  922. }
  923. $applyMonthRange = !$hasActiveSearch;
  924. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  925. $opArr = (array)json_decode($this->request->get('op', ''), true);
  926. try {
  927. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  928. if ($wffTab === 'audit') {
  929. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  930. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  931. );
  932. } elseif ($wffTab === 'confirm') {
  933. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  934. if ($dbRows === []) {
  935. try {
  936. $dbRows = Db::table('purchase_order')
  937. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  938. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  939. ->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%\')')
  940. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  941. ->order('pick_time', 'desc')->order('id', 'desc')
  942. ->select();
  943. } catch (\Throwable $e) {
  944. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  945. $dbRows = [];
  946. }
  947. }
  948. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  949. if ($pool === []) {
  950. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  951. }
  952. } else {
  953. $pool = $this->procuremenEnsureRedisPool();
  954. if (!is_array($pool)) {
  955. $pool = [];
  956. }
  957. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  958. $hideSet = $this->loadPickHiddenScydgySet();
  959. if ($pool !== [] && $hideSet !== []) {
  960. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  961. if (!is_array($r)) {
  962. return false;
  963. }
  964. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  965. return $id <= 0 || !isset($hideSet[$id]);
  966. }));
  967. }
  968. $manualPool = $this->loadPickManualOrderRows();
  969. if ($manualPool !== []) {
  970. $pool = array_merge($pool, $manualPool);
  971. }
  972. if ($pool === []) {
  973. return json([
  974. 'total' => 0,
  975. 'rows' => [],
  976. ]);
  977. }
  978. }
  979. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  980. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  981. $monthStart = $ym . '-01 00:00:00';
  982. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  983. }
  984. $filtered = $this->filterProcuremenIndexPool(
  985. $pool,
  986. $monthStart,
  987. $monthEnd,
  988. $applyMonthRange,
  989. $search,
  990. $filterArr,
  991. $opArr,
  992. $listTimePrimary
  993. );
  994. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  995. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  996. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  997. }
  998. $sortField = 'ID';
  999. if (is_string($sort) && $sort !== '') {
  1000. $parts = explode(',', $sort);
  1001. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1002. if ($sortField === '') {
  1003. $sortField = 'ID';
  1004. }
  1005. }
  1006. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1007. $nFiltered = count($filtered);
  1008. if ($nFiltered > 1) {
  1009. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1010. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1011. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1012. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1013. if ($ta === $tb) {
  1014. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1015. }
  1016. if ($ta === '') {
  1017. return 1;
  1018. }
  1019. if ($tb === '') {
  1020. return -1;
  1021. }
  1022. return strcmp($ta, $tb) * $ord;
  1023. });
  1024. } elseif ($sortField === 'ID') {
  1025. $sortKeys = [];
  1026. foreach ($filtered as $i => $row) {
  1027. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1028. }
  1029. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1030. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1031. } elseif ($sortField === 'CCYDH') {
  1032. usort($filtered, function ($a, $b) use ($ord) {
  1033. $sa = trim((string)($a['CCYDH'] ?? ''));
  1034. $sb = trim((string)($b['CCYDH'] ?? ''));
  1035. if ($sa === $sb) {
  1036. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1037. }
  1038. if ($sa === '') {
  1039. return 1;
  1040. }
  1041. if ($sb === '') {
  1042. return -1;
  1043. }
  1044. return strcmp($sa, $sb) * $ord;
  1045. });
  1046. } else {
  1047. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1048. $va = $a[$sortField] ?? null;
  1049. $vb = $b[$sortField] ?? null;
  1050. $sa = (string)$va;
  1051. $sb = (string)$vb;
  1052. if ($sa === $sb) {
  1053. return 0;
  1054. }
  1055. return strcmp($sa, $sb) * $ord;
  1056. });
  1057. }
  1058. }
  1059. $offset = max(0, (int)$offset);
  1060. $limit = max(1, (int)$limit);
  1061. $rows = array_slice($filtered, $offset, $limit);
  1062. foreach ($rows as &$rw) {
  1063. if (!is_array($rw)) {
  1064. continue;
  1065. }
  1066. $rid = (int)($rw['ID'] ?? 0);
  1067. $rw['_iss_out'] = ($wffTab !== 'pick');
  1068. }
  1069. unset($rw);
  1070. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1071. $idList = [];
  1072. foreach ($rows as $rw) {
  1073. if (!is_array($rw)) {
  1074. continue;
  1075. }
  1076. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1077. foreach ($rw['_order_merge_rows'] as $mr) {
  1078. $mid = (int)($mr['ID'] ?? 0);
  1079. if ($this->isValidScydgyRowId($mid)) {
  1080. $idList[$mid] = true;
  1081. }
  1082. }
  1083. }
  1084. $id = (int)($rw['ID'] ?? 0);
  1085. if ($this->isValidScydgyRowId($id)) {
  1086. $idList[$id] = true;
  1087. }
  1088. }
  1089. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1090. foreach ($rows as &$rw) {
  1091. if (!is_array($rw)) {
  1092. continue;
  1093. }
  1094. $mergeIds = [];
  1095. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1096. foreach ($rw['_order_merge_rows'] as $mr) {
  1097. $mid = (int)($mr['ID'] ?? 0);
  1098. if ($this->isValidScydgyRowId($mid)) {
  1099. $mergeIds[$mid] = true;
  1100. }
  1101. }
  1102. }
  1103. $rid = (int)($rw['ID'] ?? 0);
  1104. if ($this->isValidScydgyRowId($rid)) {
  1105. $mergeIds[$rid] = true;
  1106. }
  1107. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1108. $rw['po_detail_count'] = $s['cnt'];
  1109. $rw['po_amount_fill_cnt'] = $s['amt'];
  1110. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1111. }
  1112. unset($rw);
  1113. }
  1114. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1115. $idList = [];
  1116. foreach ($rows as $rw) {
  1117. if (!is_array($rw)) {
  1118. continue;
  1119. }
  1120. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1121. foreach ($rw['_order_merge_rows'] as $mr) {
  1122. $mid = (int)($mr['ID'] ?? 0);
  1123. if ($this->isValidScydgyRowId($mid)) {
  1124. $idList[$mid] = true;
  1125. }
  1126. }
  1127. }
  1128. $id = (int)($rw['ID'] ?? 0);
  1129. if ($this->isValidScydgyRowId($id)) {
  1130. $idList[$id] = true;
  1131. }
  1132. }
  1133. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1134. foreach ($rows as &$rw) {
  1135. if (!is_array($rw)) {
  1136. continue;
  1137. }
  1138. $mergeIds = [];
  1139. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1140. foreach ($rw['_order_merge_rows'] as $mr) {
  1141. $mid = (int)($mr['ID'] ?? 0);
  1142. if ($this->isValidScydgyRowId($mid)) {
  1143. $mergeIds[$mid] = true;
  1144. }
  1145. }
  1146. }
  1147. $rid = (int)($rw['ID'] ?? 0);
  1148. if ($this->isValidScydgyRowId($rid)) {
  1149. $mergeIds[$rid] = true;
  1150. }
  1151. $buckets = [];
  1152. foreach (array_keys($mergeIds) as $mid) {
  1153. if (isset($quoteBucket[$mid])) {
  1154. $buckets[] = $quoteBucket[$mid];
  1155. }
  1156. }
  1157. $supplierText = $buckets !== []
  1158. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1159. : '';
  1160. if ($wffTab === 'confirm') {
  1161. $rw['picked_supplier_name'] = $supplierText;
  1162. } else {
  1163. $rw['notify_supplier_text'] = $supplierText;
  1164. }
  1165. }
  1166. unset($rw);
  1167. }
  1168. if ($wffTab === 'all' && count($rows) > 0) {
  1169. $this->mergePurchaseOrder($rows);
  1170. }
  1171. if ($wffTab === 'pick' && count($rows) > 0) {
  1172. $this->mergePurchaseOrder($rows);
  1173. }
  1174. foreach ($rows as &$rwClean) {
  1175. if (is_array($rwClean)) {
  1176. unset($rwClean['_order_merge_rows']);
  1177. if (array_key_exists('NGZL', $rwClean)) {
  1178. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1179. }
  1180. }
  1181. }
  1182. unset($rwClean);
  1183. return json([
  1184. 'total' => count($filtered),
  1185. 'rows' => $rows,
  1186. 'activeYm' => $ym,
  1187. ]);
  1188. } catch (\Throwable $e) {
  1189. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1190. return json([
  1191. 'total' => 0,
  1192. 'rows' => [],
  1193. ]);
  1194. }
  1195. }
  1196. /**
  1197. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1198. *
  1199. * @return array<int, true>
  1200. */
  1201. protected function loadPickHiddenScydgySet(): array
  1202. {
  1203. if ($this->pickHiddenScydgySetCache !== null) {
  1204. return $this->pickHiddenScydgySetCache;
  1205. }
  1206. $hideSet = [];
  1207. try {
  1208. $poIds = Db::table('purchase_order')
  1209. ->where(function ($q) {
  1210. $q->whereIn('wflow_status', array_merge(
  1211. ProcuremenStatus::wflowPendingConfirmValues(),
  1212. ProcuremenStatus::wflowPendingApprovalValues()
  1213. ))
  1214. ->whereOr(function ($q1) {
  1215. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1216. })
  1217. ->whereOr(function ($q2) {
  1218. $q2->whereNotNull('pick_time')
  1219. ->where('pick_time', '<>', '')
  1220. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1221. })
  1222. ->whereOr(function ($q3) {
  1223. $q3->whereNotNull('mod_rq')
  1224. ->where('mod_rq', '<>', '')
  1225. ->where('mod_rq', 'not like', '0000-00-00%');
  1226. });
  1227. })
  1228. ->column('scydgy_id');
  1229. if (is_array($poIds)) {
  1230. foreach ($poIds as $pid) {
  1231. $k = (int)$pid;
  1232. if ($k !== 0) {
  1233. $hideSet[$k] = true;
  1234. }
  1235. }
  1236. }
  1237. } catch (\Throwable $e) {
  1238. }
  1239. try {
  1240. $detIdsQuery = Db::table('purchase_order_detail');
  1241. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1242. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1243. if (is_array($detIds)) {
  1244. foreach ($detIds as $pid) {
  1245. $k = (int)$pid;
  1246. if ($this->isValidScydgyRowId($k)) {
  1247. $hideSet[$k] = true;
  1248. }
  1249. }
  1250. }
  1251. } catch (\Throwable $e) {
  1252. }
  1253. $this->pickHiddenScydgySetCache = $hideSet;
  1254. return $hideSet;
  1255. }
  1256. /**
  1257. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1258. *
  1259. * @return array<int, array<string, mixed>>
  1260. */
  1261. protected function loadPickManualOrderRows(): array
  1262. {
  1263. try {
  1264. $dbRows = Db::table('purchase_order')
  1265. ->where('scydgy_id', '<', 0)
  1266. ->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%\')')
  1267. ->order('scydgy_id', 'asc')
  1268. ->select();
  1269. } catch (\Throwable $e) {
  1270. try {
  1271. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1272. } catch (\Throwable $e2) {
  1273. return [];
  1274. }
  1275. }
  1276. if (!is_array($dbRows) || $dbRows === []) {
  1277. return [];
  1278. }
  1279. $detailSidSet = [];
  1280. try {
  1281. $negIds = [];
  1282. foreach ($dbRows as $dbRow) {
  1283. if (!is_array($dbRow)) {
  1284. continue;
  1285. }
  1286. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1287. if ($sid < 0) {
  1288. $negIds[$sid] = true;
  1289. }
  1290. }
  1291. if ($negIds !== []) {
  1292. $detQuery = Db::table('purchase_order_detail')
  1293. ->where('scydgy_id', 'in', array_keys($negIds));
  1294. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1295. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1296. if (is_array($detRows)) {
  1297. foreach ($detRows as $did) {
  1298. $detailSidSet[(int)$did] = true;
  1299. }
  1300. }
  1301. }
  1302. } catch (\Throwable $e) {
  1303. }
  1304. $pool = [];
  1305. foreach ($dbRows as $dbRow) {
  1306. if (!is_array($dbRow)) {
  1307. continue;
  1308. }
  1309. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1310. if ($sid >= 0) {
  1311. continue;
  1312. }
  1313. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1314. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1315. continue;
  1316. }
  1317. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1318. if ($st === ProcuremenStatus::PO_COMPLETED || $st === ProcuremenStatus::PO_IN_PROGRESS) {
  1319. continue;
  1320. }
  1321. if (isset($detailSidSet[$sid])) {
  1322. continue;
  1323. }
  1324. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1325. $r['_is_manual'] = 1;
  1326. $pool[] = $r;
  1327. }
  1328. return $pool;
  1329. }
  1330. /**
  1331. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1332. */
  1333. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1334. {
  1335. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1336. foreach ($keys as $k) {
  1337. $t = trim((string)($row[$k] ?? ''));
  1338. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1339. return $t;
  1340. }
  1341. }
  1342. return '';
  1343. }
  1344. /**
  1345. * 分配手工新增工序行 ID(负数递减)
  1346. */
  1347. protected function allocateManualScydgyId(): int
  1348. {
  1349. try {
  1350. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1351. $min = (int)$min;
  1352. return $min < 0 ? $min - 1 : -1;
  1353. } catch (\Throwable $e) {
  1354. return -1;
  1355. }
  1356. }
  1357. /**
  1358. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1359. */
  1360. protected function allocateManualOrderCcydh(): string
  1361. {
  1362. $prefix = 'YW' . date('Ymd');
  1363. $maxSeq = 0;
  1364. try {
  1365. $rows = Db::table('purchase_order')
  1366. ->where('CCYDH', 'like', $prefix . '%')
  1367. ->column('CCYDH');
  1368. if (is_array($rows)) {
  1369. foreach ($rows as $ccydh) {
  1370. $ccydh = trim((string)$ccydh);
  1371. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1372. $maxSeq = max($maxSeq, (int)$m[1]);
  1373. }
  1374. }
  1375. }
  1376. } catch (\Throwable $e) {
  1377. }
  1378. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1379. }
  1380. /**
  1381. * purchase_order.mod_rq 是否有有效软删除时间
  1382. */
  1383. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1384. {
  1385. $t = trim((string)$modRq);
  1386. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1387. }
  1388. /**
  1389. * 列表行 → purchase_order 写入字段
  1390. *
  1391. * @return array<string, mixed>
  1392. */
  1393. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1394. {
  1395. return [
  1396. 'scydgy_id' => $scydgyId,
  1397. 'CCYDH' => $row['CCYDH'] ?? null,
  1398. 'CYJMC' => $row['CYJMC'] ?? null,
  1399. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1400. 'CDXMC' => $row['CDXMC'] ?? null,
  1401. 'CGYBH' => $row['CGYBH'] ?? null,
  1402. 'CGYMC' => $row['CGYMC'] ?? null,
  1403. 'CDW' => $row['CDW'] ?? null,
  1404. 'NGZL' => $row['NGZL'] ?? null,
  1405. 'CDF' => $row['CDF'] ?? null,
  1406. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1407. 'MBZ' => $row['MBZ'] ?? null,
  1408. 'bwjg' => $row['bwjg'] ?? null,
  1409. 'iStatus' => $row['iStatus'] ?? null,
  1410. 'dStamp' => $row['dStamp'] ?? null,
  1411. 'dputrecord' => $row['dputrecord'] ?? null,
  1412. 'cywyxm' => $row['cywyxm'] ?? null,
  1413. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1414. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1415. ];
  1416. }
  1417. /**
  1418. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1419. *
  1420. * @return array{po:?array<string,mixed>, hidden:bool}
  1421. */
  1422. protected function resolvePickRowPoContext(int $sid): array
  1423. {
  1424. $po = null;
  1425. try {
  1426. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1427. if (is_array($found)) {
  1428. $po = $found;
  1429. }
  1430. } catch (\Throwable $e) {
  1431. }
  1432. $hideSet = $this->loadPickHiddenScydgySet();
  1433. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1434. }
  1435. /**
  1436. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1437. */
  1438. protected function assertPickRowCanDelete(int $sid, array $row): void
  1439. {
  1440. $ctx = $this->resolvePickRowPoContext($sid);
  1441. $po = $ctx['po'];
  1442. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1443. return;
  1444. }
  1445. if (is_array($po)) {
  1446. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1447. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1448. }
  1449. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1450. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1451. }
  1452. }
  1453. if ($ctx['hidden']) {
  1454. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1455. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1456. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1457. }
  1458. }
  1459. /**
  1460. * 初选直接完结前校验
  1461. */
  1462. protected function assertPickRowCanComplete(int $sid, array $row): void
  1463. {
  1464. $ctx = $this->resolvePickRowPoContext($sid);
  1465. $po = $ctx['po'];
  1466. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1467. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1468. }
  1469. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1470. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1471. }
  1472. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1473. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1474. }
  1475. }
  1476. /**
  1477. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1478. */
  1479. protected function softDeleteProcuremenPickRow(array $row): void
  1480. {
  1481. $sid = $this->extractScydgyRowId($row);
  1482. if (!$this->isValidScydgyRowId($sid)) {
  1483. throw new \InvalidArgumentException('无效的行主键');
  1484. }
  1485. $this->assertPickRowCanDelete($sid, $row);
  1486. $po = $this->resolvePickRowPoContext($sid)['po'];
  1487. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1488. return;
  1489. }
  1490. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1491. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1492. }
  1493. $now = date('Y-m-d H:i:s');
  1494. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1495. if (is_array($exists)) {
  1496. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1497. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1498. } else {
  1499. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1500. $data['mod_rq'] = $now;
  1501. $data['createtime'] = $now;
  1502. Db::table('purchase_order')->insert($data);
  1503. $poIdLog = (int)Db::getLastInsID();
  1504. }
  1505. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1506. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1507. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1508. if ($gymcLog !== '') {
  1509. $logTail .= ' / ' . $gymcLog;
  1510. }
  1511. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1512. }
  1513. /**
  1514. * 手工新增协助工序(写入 purchase_order)
  1515. *
  1516. * @param array<string, mixed> $params
  1517. * @return int scydgy_id
  1518. */
  1519. protected function saveManualPickOrder(array $params): int
  1520. {
  1521. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1522. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1523. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1524. if ($ccydh === '') {
  1525. $ccydh = $this->allocateManualOrderCcydh();
  1526. }
  1527. $now = date('Y-m-d H:i:s');
  1528. $sid = $this->allocateManualScydgyId();
  1529. $data = [
  1530. 'scydgy_id' => $sid,
  1531. 'CCYDH' => $ccydh,
  1532. 'CYJMC' => $cyjmc,
  1533. 'CGYMC' => $cgymc,
  1534. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1535. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1536. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1537. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1538. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1539. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1540. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1541. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1542. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1543. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1544. 'createtime' => $now,
  1545. 'dStamp' => $now,
  1546. 'dputrecord' => $now,
  1547. ];
  1548. Db::table('purchase_order')->insert($data);
  1549. $poId = (int)Db::getLastInsID();
  1550. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1551. return $sid;
  1552. }
  1553. protected function formatProcuremenRowLabel(array $row): string
  1554. {
  1555. $dh = trim((string)($row['CCYDH'] ?? ''));
  1556. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1557. if ($dh !== '' && $gymc !== '') {
  1558. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1559. }
  1560. if ($dh !== '') {
  1561. return '订单「' . $dh . '」';
  1562. }
  1563. if ($gymc !== '') {
  1564. return '工序「' . $gymc . '」';
  1565. }
  1566. $id = $this->extractScydgyRowId($row);
  1567. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1568. }
  1569. /**
  1570. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1571. */
  1572. protected function extractScydgyRowId(array $row): int
  1573. {
  1574. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1575. }
  1576. protected function isValidScydgyRowId(int $id): bool
  1577. {
  1578. return ProcuremenGuard::isValidScydgyId($id);
  1579. }
  1580. protected function isManualScydgyRowId(int $id): bool
  1581. {
  1582. return $id < 0;
  1583. }
  1584. /**
  1585. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1586. *
  1587. * @param int[] $scydgyIds
  1588. * @return array<int, string[]>
  1589. */
  1590. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1591. {
  1592. $out = [];
  1593. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1594. if ($scydgyIds === []) {
  1595. return $out;
  1596. }
  1597. try {
  1598. $rows = Db::table('purchase_order_detail')
  1599. ->where('scydgy_id', 'in', $scydgyIds)
  1600. ->field('scydgy_id,company_name')
  1601. ->order('company_name', 'asc')
  1602. ->select();
  1603. } catch (\Throwable $e) {
  1604. $rows = [];
  1605. }
  1606. if (!is_array($rows)) {
  1607. return $out;
  1608. }
  1609. foreach ($rows as $r) {
  1610. if (!is_array($r)) {
  1611. continue;
  1612. }
  1613. $sid = (int)($r['scydgy_id'] ?? 0);
  1614. $cn = trim((string)($r['company_name'] ?? ''));
  1615. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1616. continue;
  1617. }
  1618. if (!isset($out[$sid])) {
  1619. $out[$sid] = [];
  1620. }
  1621. if (!in_array($cn, $out[$sid], true)) {
  1622. $out[$sid][] = $cn;
  1623. }
  1624. }
  1625. return $out;
  1626. }
  1627. /**
  1628. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1629. *
  1630. * @param string[] $names
  1631. */
  1632. protected function formatNotifySupplierDisplay(array $names): string
  1633. {
  1634. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1635. return trim((string)$n);
  1636. }, $names))));
  1637. if ($names === []) {
  1638. return '';
  1639. }
  1640. sort($names, SORT_STRING);
  1641. return implode("\n", $names);
  1642. }
  1643. /**
  1644. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1645. *
  1646. * @param int[] $scydgyIds
  1647. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1648. */
  1649. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1650. {
  1651. $out = [];
  1652. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1653. if ($scydgyIds === []) {
  1654. return $out;
  1655. }
  1656. try {
  1657. $rows = Db::table('purchase_order_detail')
  1658. ->where('scydgy_id', 'in', $scydgyIds)
  1659. ->field('scydgy_id,company_name,amount')
  1660. ->select();
  1661. } catch (\Throwable $e) {
  1662. $rows = [];
  1663. }
  1664. if (!is_array($rows)) {
  1665. return $out;
  1666. }
  1667. foreach ($rows as $r) {
  1668. if (!is_array($r)) {
  1669. continue;
  1670. }
  1671. $sid = (int)($r['scydgy_id'] ?? 0);
  1672. $cn = trim((string)($r['company_name'] ?? ''));
  1673. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1674. continue;
  1675. }
  1676. if (!isset($out[$sid])) {
  1677. $out[$sid] = ['all' => [], 'quoted' => []];
  1678. }
  1679. $out[$sid]['all'][$cn] = true;
  1680. $am = trim((string)($r['amount'] ?? ''));
  1681. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1682. $out[$sid]['quoted'][$cn] = true;
  1683. }
  1684. }
  1685. return $out;
  1686. }
  1687. /**
  1688. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1689. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1690. */
  1691. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1692. {
  1693. $merged = ['all' => [], 'quoted' => []];
  1694. foreach ($buckets as $b) {
  1695. if (!is_array($b)) {
  1696. continue;
  1697. }
  1698. foreach ($b['all'] ?? [] as $cn => $_) {
  1699. $merged['all'][$cn] = true;
  1700. }
  1701. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1702. $merged['quoted'][$cn] = true;
  1703. }
  1704. }
  1705. return $merged;
  1706. }
  1707. /**
  1708. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1709. */
  1710. protected function formatQuotedSupplierLines(array $bucket): string
  1711. {
  1712. $all = array_keys($bucket['all'] ?? []);
  1713. if ($all === []) {
  1714. return '';
  1715. }
  1716. sort($all, SORT_STRING);
  1717. $lines = [];
  1718. foreach ($all as $cn) {
  1719. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1720. $lines[] = $cn . '(' . $status . ')';
  1721. }
  1722. return implode("\n", $lines);
  1723. }
  1724. /**
  1725. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1726. */
  1727. protected function resolveBundleSysRq(array $bundle): string
  1728. {
  1729. foreach ($bundle['pos'] ?? [] as $po) {
  1730. if (!is_array($po)) {
  1731. continue;
  1732. }
  1733. $sr = trim((string)($po['sys_rq'] ?? ''));
  1734. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1735. return $sr;
  1736. }
  1737. }
  1738. return '';
  1739. }
  1740. /**
  1741. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1742. */
  1743. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1744. {
  1745. $raw = trim((string)$sysRq);
  1746. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1747. return true;
  1748. }
  1749. $ts = strtotime(str_replace('T', ' ', $raw));
  1750. if ($ts === false || $ts <= 0) {
  1751. return true;
  1752. }
  1753. return time() >= $ts;
  1754. }
  1755. /**
  1756. * 截止时间前:隐藏单价/交期真实值,统一展示文案
  1757. *
  1758. * @param array<string, mixed> $line
  1759. */
  1760. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  1761. {
  1762. $amountFilled = !empty($line['amount_filled']);
  1763. $deliveryFilled = !empty($line['delivery_filled']);
  1764. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  1765. $line['amount_show'] = '';
  1766. if (array_key_exists('amount_text', $line)) {
  1767. $line['amount_text'] = $line['unit_price_text'];
  1768. }
  1769. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  1770. $line['delivery_show'] = $deliveryText;
  1771. if (array_key_exists('delivery_text', $line)) {
  1772. $line['delivery_text'] = $deliveryText;
  1773. }
  1774. $line['delivery_ymd'] = '';
  1775. $line['subtotal_text'] = $amountFilled ? '' : '';
  1776. $line['subtotal_num'] = null;
  1777. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  1778. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  1779. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled) ? 1 : 0;
  1780. $line['amount_filled'] = false;
  1781. $line['delivery_filled'] = false;
  1782. $line['is_quoted'] = false;
  1783. if (array_key_exists('quote_label', $line)) {
  1784. $line['quote_label'] = ($amountFilled || $deliveryFilled) ? '未开标验证' : '未报价';
  1785. }
  1786. }
  1787. protected function ensurePurchaseOrderBidOpenTable(): void
  1788. {
  1789. try {
  1790. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  1791. } catch (\Throwable $e) {
  1792. Db::execute(
  1793. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  1794. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  1795. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  1796. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  1797. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  1798. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  1799. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  1800. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  1801. `operator_name` varchar(64) NOT NULL DEFAULT '',
  1802. `createtime` datetime DEFAULT NULL,
  1803. PRIMARY KEY (`id`),
  1804. UNIQUE KEY `uk_ccydh` (`ccydh`)
  1805. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  1806. );
  1807. }
  1808. }
  1809. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  1810. {
  1811. $ccydh = trim($ccydh);
  1812. if ($ccydh === '') {
  1813. return false;
  1814. }
  1815. $this->ensurePurchaseOrderBidOpenTable();
  1816. try {
  1817. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1818. return is_array($row);
  1819. } catch (\Throwable $e) {
  1820. return false;
  1821. }
  1822. }
  1823. /**
  1824. * @param array{ccydh?:string} $bundle
  1825. */
  1826. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  1827. {
  1828. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  1829. }
  1830. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  1831. {
  1832. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  1833. }
  1834. protected function loadBidOpenAdminUser(int $adminId): ?array
  1835. {
  1836. if ($adminId <= 0) {
  1837. return null;
  1838. }
  1839. try {
  1840. $row = Db::name('admin')->where('id', $adminId)->find();
  1841. } catch (\Throwable $e) {
  1842. return null;
  1843. }
  1844. if (!is_array($row)) {
  1845. return null;
  1846. }
  1847. $status = strtolower(trim((string)($row['status'] ?? '')));
  1848. if ($status !== '' && $status !== 'normal') {
  1849. return null;
  1850. }
  1851. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  1852. return null;
  1853. }
  1854. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  1855. if (!preg_match('/^1\d{10}$/', $phone)) {
  1856. return null;
  1857. }
  1858. $name = trim((string)($row['nickname'] ?? ''));
  1859. if ($name === '') {
  1860. $name = trim((string)($row['username'] ?? ''));
  1861. }
  1862. return [
  1863. 'id' => (int)$row['id'],
  1864. 'username' => trim((string)($row['username'] ?? '')),
  1865. 'nickname' => $name,
  1866. 'mobile' => $phone,
  1867. ];
  1868. }
  1869. /**
  1870. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  1871. */
  1872. protected function bidOpenVerifierAuthGroupRootId(): int
  1873. {
  1874. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  1875. return $id > 0 ? $id : 10;
  1876. }
  1877. /**
  1878. * @return int[]
  1879. */
  1880. protected function loadBidOpenVerifierAuthGroupIds(): array
  1881. {
  1882. static $memo = [];
  1883. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  1884. if (isset($memo[$rootId])) {
  1885. return $memo[$rootId];
  1886. }
  1887. try {
  1888. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  1889. } catch (\Throwable $e) {
  1890. $memo[$rootId] = [$rootId];
  1891. return $memo[$rootId];
  1892. }
  1893. if (!is_array($groups) || $groups === []) {
  1894. $memo[$rootId] = [$rootId];
  1895. return $memo[$rootId];
  1896. }
  1897. $groupList = [];
  1898. foreach ($groups as $g) {
  1899. if (is_array($g)) {
  1900. $groupList[] = $g;
  1901. }
  1902. }
  1903. if ($groupList === []) {
  1904. $memo[$rootId] = [$rootId];
  1905. return $memo[$rootId];
  1906. }
  1907. $tree = \fast\Tree::instance();
  1908. $tree->init($groupList);
  1909. $ids = $tree->getChildrenIds($rootId, true);
  1910. if (!is_array($ids) || $ids === []) {
  1911. $memo[$rootId] = [$rootId];
  1912. return $memo[$rootId];
  1913. }
  1914. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  1915. return $memo[$rootId];
  1916. }
  1917. protected function isBidOpenVerifierAdmin(int $adminId): bool
  1918. {
  1919. if ($adminId <= 0) {
  1920. return false;
  1921. }
  1922. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  1923. if ($groupIds === []) {
  1924. return false;
  1925. }
  1926. try {
  1927. return (bool)Db::name('auth_group_access')
  1928. ->where('uid', $adminId)
  1929. ->where('group_id', 'in', $groupIds)
  1930. ->count();
  1931. } catch (\Throwable $e) {
  1932. return false;
  1933. }
  1934. }
  1935. /**
  1936. * @return array<int, array<string, mixed>>
  1937. */
  1938. protected function listBidOpenVerifierCandidates(): array
  1939. {
  1940. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  1941. if ($groupIds === []) {
  1942. return [];
  1943. }
  1944. try {
  1945. $adminIds = Db::name('auth_group_access')
  1946. ->where('group_id', 'in', $groupIds)
  1947. ->column('uid');
  1948. } catch (\Throwable $e) {
  1949. $adminIds = [];
  1950. }
  1951. $adminIds = is_array($adminIds)
  1952. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  1953. : [];
  1954. if ($adminIds === []) {
  1955. return [];
  1956. }
  1957. try {
  1958. $rows = Db::name('admin')
  1959. ->where('status', 'normal')
  1960. ->where('id', 'in', $adminIds)
  1961. ->where('mobile', '<>', '')
  1962. ->order('id', 'asc')
  1963. ->select();
  1964. } catch (\Throwable $e) {
  1965. return [];
  1966. }
  1967. if (!is_array($rows)) {
  1968. return [];
  1969. }
  1970. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  1971. $out = [];
  1972. foreach ($rows as $row) {
  1973. if (!is_array($row)) {
  1974. continue;
  1975. }
  1976. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  1977. if ($one === null) {
  1978. continue;
  1979. }
  1980. $out[] = [
  1981. 'id' => $one['id'],
  1982. 'username' => $one['username'],
  1983. 'nickname' => $one['nickname'],
  1984. 'group_name' => $groupNameMap[$one['id']] ?? '',
  1985. 'mobile' => mask_phone($one['mobile']),
  1986. ];
  1987. }
  1988. return $out;
  1989. }
  1990. /**
  1991. * @param int[] $adminIds
  1992. * @return array<int, string>
  1993. */
  1994. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  1995. {
  1996. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  1997. if ($adminIds === []) {
  1998. return [];
  1999. }
  2000. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2001. try {
  2002. $rows = Db::name('auth_group_access')
  2003. ->alias('aga')
  2004. ->join('auth_group ag', 'aga.group_id = ag.id')
  2005. ->where('aga.uid', 'in', $adminIds)
  2006. ->where('aga.group_id', 'in', $groupIds)
  2007. ->field('aga.uid,ag.name')
  2008. ->order('aga.uid', 'asc')
  2009. ->order('aga.group_id', 'asc')
  2010. ->select();
  2011. } catch (\Throwable $e) {
  2012. return [];
  2013. }
  2014. if (!is_array($rows)) {
  2015. return [];
  2016. }
  2017. $out = [];
  2018. foreach ($rows as $row) {
  2019. if (!is_array($row)) {
  2020. continue;
  2021. }
  2022. $uid = (int)($row['uid'] ?? 0);
  2023. $name = trim((string)($row['name'] ?? ''));
  2024. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2025. continue;
  2026. }
  2027. $out[$uid] = $name;
  2028. }
  2029. return $out;
  2030. }
  2031. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2032. {
  2033. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2034. }
  2035. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2036. {
  2037. return 'procuremen_bidopen_wait_' . $adminId;
  2038. }
  2039. protected function renderBidOpenVerifySms(string $code): string
  2040. {
  2041. $tpl = '';
  2042. try {
  2043. $row = $this->loadNotifyTemplateRow('bid_open');
  2044. if (is_array($row)) {
  2045. $tpl = trim((string)($row['content'] ?? ''));
  2046. }
  2047. } catch (\Throwable $e) {
  2048. $tpl = '';
  2049. }
  2050. if ($tpl === '') {
  2051. $tpl = '【可集达】您的短信验证码是{code}';
  2052. }
  2053. return str_replace('{code}', $code, $tpl);
  2054. }
  2055. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2056. {
  2057. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2058. }
  2059. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2060. {
  2061. $code = trim($code);
  2062. if (!preg_match('/^\d{6}$/', $code)) {
  2063. return false;
  2064. }
  2065. $mock = Config::get('mproc.mock_sms_code');
  2066. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2067. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2068. return true;
  2069. }
  2070. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2071. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2072. return false;
  2073. }
  2074. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2075. return true;
  2076. }
  2077. /**
  2078. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2079. */
  2080. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2081. {
  2082. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2083. if ($ccydh === '') {
  2084. throw new \InvalidArgumentException('订单号无效');
  2085. }
  2086. $this->ensurePurchaseOrderBidOpenTable();
  2087. list($operatorId, $operatorName) = $this->GetUseName();
  2088. $now = date('Y-m-d H:i:s');
  2089. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2090. $payload = [
  2091. 'ccydh' => $ccydh,
  2092. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2093. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2094. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2095. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2096. 'operator_id' => (int)$operatorId,
  2097. 'operator_name' => trim((string)$operatorName),
  2098. 'createtime' => $now,
  2099. ];
  2100. if (is_array($exists)) {
  2101. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2102. } else {
  2103. Db::table('purchase_order_bid_open')->insert($payload);
  2104. }
  2105. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2106. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2107. $orderPart = '(订单' . $ccydh . ')';
  2108. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2109. $seenSid = [];
  2110. foreach ($bundle['pos'] ?? [] as $poRow) {
  2111. if (!is_array($poRow)) {
  2112. continue;
  2113. }
  2114. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2115. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2116. continue;
  2117. }
  2118. $seenSid[$sid] = true;
  2119. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2120. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2121. }
  2122. if ($seenSid === []) {
  2123. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2124. if ($this->isValidScydgyRowId($anchor)) {
  2125. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2126. }
  2127. }
  2128. }
  2129. /**
  2130. * 报价行展示字段默认值(模板安全访问)
  2131. *
  2132. * @param array<string, mixed> $line
  2133. * @return array<string, mixed>
  2134. */
  2135. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2136. {
  2137. if (!array_key_exists('amount_quote_pending', $line)) {
  2138. $line['amount_quote_pending'] = 0;
  2139. }
  2140. if (!array_key_exists('delivery_quote_pending', $line)) {
  2141. $line['delivery_quote_pending'] = 0;
  2142. }
  2143. if (!array_key_exists('quote_before_deadline', $line)) {
  2144. $line['quote_before_deadline'] = 0;
  2145. }
  2146. if (!array_key_exists('amount_filled', $line)) {
  2147. $line['amount_filled'] = 0;
  2148. }
  2149. if (!array_key_exists('delivery_filled', $line)) {
  2150. $line['delivery_filled'] = 0;
  2151. }
  2152. return $line;
  2153. }
  2154. /**
  2155. * 审核弹窗:按供应商汇总报价明细
  2156. *
  2157. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2158. * @return array<int, array<string, mixed>>
  2159. */
  2160. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2161. {
  2162. $sids = [];
  2163. foreach ($bundle['pos'] ?? [] as $po) {
  2164. if (!is_array($po)) {
  2165. continue;
  2166. }
  2167. $sid = (int)($po['scydgy_id'] ?? 0);
  2168. if ($this->isValidScydgyRowId($sid)) {
  2169. $sids[$sid] = true;
  2170. }
  2171. }
  2172. if ($sids === []) {
  2173. return [];
  2174. }
  2175. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2176. $gymcMap = [];
  2177. $qtyBySid = [];
  2178. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2179. if (!is_array($mr)) {
  2180. continue;
  2181. }
  2182. $gid = $this->extractScydgyRowId($mr);
  2183. if ($this->isValidScydgyRowId($gid)) {
  2184. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2185. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2186. if ($qty === '') {
  2187. $qty = trim((string)($mr['NGZL'] ?? ''));
  2188. }
  2189. $qtyBySid[$gid] = $qty;
  2190. }
  2191. }
  2192. foreach ($bundle['pos'] ?? [] as $po) {
  2193. if (!is_array($po)) {
  2194. continue;
  2195. }
  2196. $gid = (int)($po['scydgy_id'] ?? 0);
  2197. if ($this->isValidScydgyRowId($gid)) {
  2198. $nm = trim((string)($po['CGYMC'] ?? ''));
  2199. if ($nm !== '') {
  2200. $gymcMap[$gid] = $nm;
  2201. }
  2202. }
  2203. }
  2204. try {
  2205. $detailsQuery = Db::table('purchase_order_detail')
  2206. ->where('scydgy_id', 'in', array_keys($sids));
  2207. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2208. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2209. } catch (\Throwable $e) {
  2210. try {
  2211. $detailsQuery = Db::table('purchase_order_detail')
  2212. ->where('scydgy_id', 'in', array_keys($sids));
  2213. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2214. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2215. } catch (\Throwable $e2) {
  2216. $details = [];
  2217. }
  2218. }
  2219. if (!is_array($details)) {
  2220. $details = [];
  2221. }
  2222. $byCompany = [];
  2223. foreach ($details as $d) {
  2224. if (!is_array($d)) {
  2225. continue;
  2226. }
  2227. $cn = trim((string)($d['company_name'] ?? ''));
  2228. if ($cn === '') {
  2229. continue;
  2230. }
  2231. if (!isset($byCompany[$cn])) {
  2232. $ph = trim((string)($d['phone'] ?? ''));
  2233. $username = trim((string)($d['username'] ?? ''));
  2234. if ($username === '') {
  2235. $username = $this->resolveCustomerContactName($ph, $cn);
  2236. }
  2237. $byCompany[$cn] = [
  2238. 'name' => $cn,
  2239. 'email' => trim((string)($d['email'] ?? '')),
  2240. 'phone' => $ph,
  2241. 'username' => $username,
  2242. 'has_quote' => false,
  2243. 'lines' => [],
  2244. ];
  2245. }
  2246. $sid = (int)($d['scydgy_id'] ?? 0);
  2247. $am = trim((string)($d['amount'] ?? ''));
  2248. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2249. if ($gymc === '') {
  2250. $gymc = '工序';
  2251. }
  2252. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2253. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2254. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2255. $deliveryShow = $deliveryRaw;
  2256. }
  2257. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2258. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2259. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2260. $subtotal = null;
  2261. if ($amountNum !== null) {
  2262. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2263. }
  2264. $unitPriceText = $amountFilled
  2265. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2266. : '未填写';
  2267. $lineRow = [
  2268. 'cgymc' => $gymc,
  2269. 'amount' => $am,
  2270. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2271. 'amount_filled' => $amountFilled,
  2272. 'unit_price_text' => $unitPriceText,
  2273. 'delivery' => $deliveryRaw,
  2274. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2275. 'delivery_filled' => $deliveryFilled,
  2276. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2277. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2278. 'subtotal_num' => $subtotal,
  2279. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2280. 'is_quoted' => $amountFilled,
  2281. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2282. ];
  2283. if (!$quoteVisible) {
  2284. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2285. }
  2286. $byCompany[$cn]['lines'][] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2287. }
  2288. foreach ($byCompany as $cn => $g) {
  2289. $total = count($g['lines']);
  2290. $quoted = 0;
  2291. $groupTotal = 0.0;
  2292. $groupHasTotal = false;
  2293. if ($quoteVisible) {
  2294. foreach ($g['lines'] as $ln) {
  2295. $am = trim((string)($ln['amount'] ?? ''));
  2296. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2297. $quoted++;
  2298. }
  2299. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2300. $groupTotal += (float)$ln['subtotal_num'];
  2301. $groupHasTotal = true;
  2302. }
  2303. }
  2304. }
  2305. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2306. $byCompany[$cn]['line_count'] = $total;
  2307. $byCompany[$cn]['has_total'] = $total > 0;
  2308. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2309. $byCompany[$cn]['display_rowspan'] = $total + ($total > 0 ? 1 : 0);
  2310. }
  2311. return array_values($byCompany);
  2312. }
  2313. /**
  2314. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2315. *
  2316. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2317. * @return array<int, array<string, mixed>>
  2318. */
  2319. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2320. {
  2321. $sids = [];
  2322. $poIdMap = [];
  2323. foreach ($bundle['pos'] ?? [] as $po) {
  2324. if (!is_array($po)) {
  2325. continue;
  2326. }
  2327. $sid = (int)($po['scydgy_id'] ?? 0);
  2328. if ($this->isValidScydgyRowId($sid)) {
  2329. $sids[$sid] = true;
  2330. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2331. }
  2332. }
  2333. if ($sids === []) {
  2334. return [];
  2335. }
  2336. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2337. $gymcMap = [];
  2338. $qtyBySid = [];
  2339. $orderedSids = [];
  2340. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2341. if (!is_array($mr)) {
  2342. continue;
  2343. }
  2344. $gid = $this->extractScydgyRowId($mr);
  2345. if ($this->isValidScydgyRowId($gid)) {
  2346. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2347. $orderedSids[] = $gid;
  2348. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2349. if ($qty === '') {
  2350. $qty = trim((string)($mr['NGZL'] ?? ''));
  2351. }
  2352. $qtyBySid[$gid] = $qty;
  2353. }
  2354. }
  2355. foreach ($bundle['pos'] ?? [] as $po) {
  2356. if (!is_array($po)) {
  2357. continue;
  2358. }
  2359. $gid = (int)($po['scydgy_id'] ?? 0);
  2360. if ($this->isValidScydgyRowId($gid)) {
  2361. $nm = trim((string)($po['CGYMC'] ?? ''));
  2362. if ($nm !== '') {
  2363. $gymcMap[$gid] = $nm;
  2364. }
  2365. }
  2366. }
  2367. try {
  2368. $details = Db::table('purchase_order_detail')
  2369. ->where('scydgy_id', 'in', array_keys($sids))
  2370. ->order('company_name', 'asc')
  2371. ->order('id', 'asc')
  2372. ->select();
  2373. } catch (\Throwable $e) {
  2374. try {
  2375. $details = Db::table('purchase_order_detail')
  2376. ->where('scydgy_id', 'in', array_keys($sids))
  2377. ->order('company_name', 'asc')
  2378. ->order('ID', 'asc')
  2379. ->select();
  2380. } catch (\Throwable $e2) {
  2381. $details = [];
  2382. }
  2383. }
  2384. if (!is_array($details)) {
  2385. $details = [];
  2386. }
  2387. $byCompany = [];
  2388. foreach ($details as $d) {
  2389. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2390. continue;
  2391. }
  2392. $cn = trim((string)($d['company_name'] ?? ''));
  2393. if ($cn === '') {
  2394. continue;
  2395. }
  2396. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2397. $sid = (int)($d['scydgy_id'] ?? 0);
  2398. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2399. continue;
  2400. }
  2401. if (!isset($byCompany[$cn])) {
  2402. $ph = trim((string)($d['phone'] ?? ''));
  2403. $username = trim((string)($d['username'] ?? ''));
  2404. if ($username === '') {
  2405. $username = $this->resolveCustomerContactName($ph, $cn);
  2406. }
  2407. $byCompany[$cn] = [
  2408. 'name' => $cn,
  2409. 'email' => trim((string)($d['email'] ?? '')),
  2410. 'phone' => $ph,
  2411. 'username' => $username,
  2412. 'pick_lines' => [],
  2413. 'detail_picks' => [],
  2414. ];
  2415. }
  2416. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2417. if ($gymc === '') {
  2418. $gymc = '工序';
  2419. }
  2420. $am = trim((string)($d['amount'] ?? ''));
  2421. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2422. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2423. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2424. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2425. $deliveryShow = $deliveryRaw;
  2426. }
  2427. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2428. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2429. $subtotal = null;
  2430. if ($amountNum !== null) {
  2431. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2432. }
  2433. $unitPriceText = $amountFilled
  2434. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2435. : '未填写';
  2436. $pickLine = [
  2437. 'cgymc' => $gymc,
  2438. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2439. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2440. 'amount_filled' => $amountFilled,
  2441. 'delivery_filled' => $deliveryFilled,
  2442. 'unit_price_text' => $unitPriceText,
  2443. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2444. 'subtotal_num' => $subtotal,
  2445. 'is_quoted' => $amountFilled,
  2446. ];
  2447. if (!$quoteVisible) {
  2448. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2449. }
  2450. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2451. $byCompany[$cn]['detail_picks'][$sid] = [
  2452. 'scydgy_id' => $sid,
  2453. 'detail_id' => $detailId,
  2454. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2455. 'cgymc' => $gymc,
  2456. ];
  2457. }
  2458. $out = [];
  2459. foreach ($byCompany as $g) {
  2460. $pickLinesMap = $g['pick_lines'] ?? [];
  2461. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2462. continue;
  2463. }
  2464. $pickLines = [];
  2465. $usedLineSids = [];
  2466. foreach ($orderedSids as $sid) {
  2467. if (!isset($pickLinesMap[$sid])) {
  2468. continue;
  2469. }
  2470. $pickLines[] = $pickLinesMap[$sid];
  2471. $usedLineSids[$sid] = true;
  2472. }
  2473. foreach ($pickLinesMap as $sid => $ln) {
  2474. if (isset($usedLineSids[$sid])) {
  2475. continue;
  2476. }
  2477. $pickLines[] = $ln;
  2478. }
  2479. $groupTotal = 0.0;
  2480. $groupHasTotal = false;
  2481. if ($quoteVisible) {
  2482. foreach ($pickLines as $ln) {
  2483. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2484. $groupTotal += (float)$ln['subtotal_num'];
  2485. $groupHasTotal = true;
  2486. }
  2487. }
  2488. }
  2489. $lineCount = count($pickLines);
  2490. $g['pick_lines'] = $pickLines;
  2491. $g['line_count'] = $lineCount;
  2492. $g['has_total'] = $lineCount > 0;
  2493. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2494. $g['display_rowspan'] = $lineCount + ($lineCount > 0 ? 1 : 0);
  2495. $detailPicks = $g['detail_picks'] ?? [];
  2496. $g['detail_picks'] = array_values(is_array($detailPicks) ? $detailPicks : []);
  2497. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2498. unset($g['detail_picks']);
  2499. $out[] = $g;
  2500. }
  2501. return $out;
  2502. }
  2503. /**
  2504. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2505. * @return array<int, int[]> scydgy_id => detail_id[]
  2506. */
  2507. protected function mapDetailIdsByScydgyId(array $details): array
  2508. {
  2509. $out = [];
  2510. foreach ($details as $d) {
  2511. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2512. continue;
  2513. }
  2514. $sid = (int)($d['scydgy_id'] ?? 0);
  2515. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2516. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2517. continue;
  2518. }
  2519. if (!isset($out[$sid])) {
  2520. $out[$sid] = [];
  2521. }
  2522. $out[$sid][] = $pk;
  2523. }
  2524. foreach ($out as $sid => $ids) {
  2525. $out[$sid] = array_values(array_unique($ids));
  2526. }
  2527. return $out;
  2528. }
  2529. /**
  2530. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2531. *
  2532. * @param array<string, mixed> $dbRow
  2533. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2534. */
  2535. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2536. {
  2537. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2538. $r = [
  2539. 'ID' => $sid,
  2540. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2541. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2542. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2543. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2544. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2545. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2546. 'CDW' => $dbRow['CDW'] ?? '',
  2547. 'NGZL' => $dbRow['NGZL'] ?? '',
  2548. 'CDF' => $dbRow['CDF'] ?? '',
  2549. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2550. 'MBZ' => $dbRow['MBZ'] ?? '',
  2551. 'bwjg' => $dbRow['bwjg'] ?? '',
  2552. 'iStatus' => $dbRow['iStatus'] ?? '',
  2553. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2554. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2555. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2556. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2557. 'dStamp' => $dbRow['dStamp'] ?? '',
  2558. 'pick_time' => $dbRow['pick_time'] ?? '',
  2559. ];
  2560. if ($sid > 0 && isset($dStampMap[$sid])) {
  2561. $t = trim((string)$dStampMap[$sid]);
  2562. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2563. $r['dStamp'] = $dStampMap[$sid];
  2564. }
  2565. }
  2566. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2567. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2568. $ct = $dbRow['createtime'];
  2569. if (is_numeric($ct) && (int)$ct > 946684800) {
  2570. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2571. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2572. $r['dStamp'] = trim($ct);
  2573. }
  2574. }
  2575. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2576. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2577. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2578. $fallback = trim((string)($r['dStamp'] ?? ''));
  2579. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2580. $r['dputrecord'] = $fallback;
  2581. }
  2582. }
  2583. if (array_key_exists('id', $dbRow)) {
  2584. $r['purchase_order_id'] = (int)$dbRow['id'];
  2585. }
  2586. if ($sid < 0) {
  2587. $r['_is_manual'] = 1;
  2588. }
  2589. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2590. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2591. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2592. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2593. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2594. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2595. $r['pick_time'] = $pickFallback;
  2596. break;
  2597. }
  2598. }
  2599. }
  2600. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2601. if ($pickNm !== '') {
  2602. $r['pick_company_name'] = $pickNm;
  2603. $r['picked_supplier_name'] = $pickNm;
  2604. }
  2605. return $r;
  2606. }
  2607. /**
  2608. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2609. *
  2610. * @return array<int, array<string, mixed>>
  2611. */
  2612. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2613. {
  2614. $pool = [];
  2615. if (!is_array($dbRows) || $dbRows === []) {
  2616. return $pool;
  2617. }
  2618. $dStampMap = [];
  2619. $sidList = [];
  2620. foreach ($dbRows as $tmpRow) {
  2621. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2622. $sid = (int)$tmpRow['scydgy_id'];
  2623. if ($sid > 0) {
  2624. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2625. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2626. $sidList[$sid] = true;
  2627. }
  2628. }
  2629. }
  2630. }
  2631. if ($sidList !== []) {
  2632. try {
  2633. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2634. } catch (\Throwable $e) {
  2635. $dStampMap = [];
  2636. }
  2637. }
  2638. foreach ($dbRows as $dbRow) {
  2639. if (!is_array($dbRow)) {
  2640. continue;
  2641. }
  2642. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2643. }
  2644. return $pool;
  2645. }
  2646. /**
  2647. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2648. *
  2649. * @param int[] $scydgyIds
  2650. * @return array<int, array<string, mixed>>
  2651. */
  2652. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2653. {
  2654. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2655. if ($scydgyIds === []) {
  2656. return [];
  2657. }
  2658. try {
  2659. $list = Db::table('purchase_order_detail')
  2660. ->where('scydgy_id', 'in', $scydgyIds)
  2661. ->field('scydgy_id,company_name,amount,delivery')
  2662. ->select();
  2663. } catch (\Throwable $e) {
  2664. $list = [];
  2665. }
  2666. return is_array($list) ? $list : [];
  2667. }
  2668. /**
  2669. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2670. *
  2671. * @param int[] $scydgyIds
  2672. * @param array<int, array<string, mixed>> $allRows
  2673. * @return array{cnt:int, amt:int, deliv:int}
  2674. */
  2675. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2676. {
  2677. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2678. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2679. if ($scydgyIds === [] || $allRows === []) {
  2680. return $out;
  2681. }
  2682. $idSet = array_flip($scydgyIds);
  2683. $all = [];
  2684. $withAmt = [];
  2685. $withDeliv = [];
  2686. foreach ($allRows as $r) {
  2687. if (!is_array($r)) {
  2688. continue;
  2689. }
  2690. $sid = (int)($r['scydgy_id'] ?? 0);
  2691. if (!isset($idSet[$sid])) {
  2692. continue;
  2693. }
  2694. $cn = trim((string)($r['company_name'] ?? ''));
  2695. if ($cn === '') {
  2696. continue;
  2697. }
  2698. $all[$cn] = true;
  2699. $am = $r['amount'] ?? null;
  2700. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2701. $withAmt[$cn] = true;
  2702. }
  2703. $dv = $r['delivery'] ?? null;
  2704. if ($dv !== null && trim((string)$dv) !== '') {
  2705. $withDeliv[$cn] = true;
  2706. }
  2707. }
  2708. return [
  2709. 'cnt' => count($all),
  2710. 'amt' => count($withAmt),
  2711. 'deliv' => count($withDeliv),
  2712. ];
  2713. }
  2714. /**
  2715. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2716. *
  2717. * @param int[] $scydgyIds
  2718. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2719. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2720. */
  2721. protected function OrderDetailSummary(array $scydgyIds)
  2722. {
  2723. $out = [];
  2724. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2725. if ($scydgyIds === []) {
  2726. return $out;
  2727. }
  2728. $list = [];
  2729. try {
  2730. $list = Db::table('purchase_order_detail')
  2731. ->where('scydgy_id', 'in', $scydgyIds)
  2732. ->field('id,scydgy_id,amount,delivery')
  2733. ->select();
  2734. } catch (\Throwable $e) {
  2735. $list = [];
  2736. }
  2737. if (!is_array($list)) {
  2738. return $out;
  2739. }
  2740. foreach ($list as $r) {
  2741. if (!is_array($r)) {
  2742. continue;
  2743. }
  2744. $ids = (int)($r['scydgy_id'] ?? 0);
  2745. if (!$this->isValidScydgyRowId($ids)) {
  2746. continue;
  2747. }
  2748. if (!isset($out[$ids])) {
  2749. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2750. }
  2751. $out[$ids]['cnt']++;
  2752. $am = $r['amount'] ?? null;
  2753. if ($am !== null && $am !== '') {
  2754. if (!(is_string($am) && trim($am) === '')) {
  2755. $out[$ids]['amt']++;
  2756. }
  2757. }
  2758. $dv = $r['delivery'] ?? null;
  2759. if ($dv !== null && trim((string)$dv) !== '') {
  2760. $out[$ids]['deliv']++;
  2761. }
  2762. }
  2763. return $out;
  2764. }
  2765. /**
  2766. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  2767. *
  2768. * @return array
  2769. */
  2770. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  2771. {
  2772. $strContains = function ($haystack, $needle) {
  2773. if ($needle === '') {
  2774. return false;
  2775. }
  2776. $haystack = (string)$haystack;
  2777. if (function_exists('mb_stripos')) {
  2778. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  2779. }
  2780. return stripos($haystack, $needle) !== false;
  2781. };
  2782. $stripAlias = function ($f) {
  2783. return preg_replace('/^[ab]\./i', '', (string)$f);
  2784. };
  2785. $searchColNames = [];
  2786. foreach (explode(',', $this->searchFields) as $colRaw) {
  2787. $c = $stripAlias(trim($colRaw));
  2788. if ($c !== '') {
  2789. $searchColNames[] = $c;
  2790. }
  2791. }
  2792. $filtered = [];
  2793. foreach ($pool as $r) {
  2794. if (!is_array($r)) {
  2795. continue;
  2796. }
  2797. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  2798. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  2799. if (!$isManual) {
  2800. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  2801. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  2802. continue;
  2803. }
  2804. if ($applyMonthRange) {
  2805. $mo = (int)$m[2];
  2806. if ($mo < 1 || $mo > 12) {
  2807. continue;
  2808. }
  2809. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2810. $rowMonthStart = $ymRow . '-01 00:00:00';
  2811. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2812. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2813. continue;
  2814. }
  2815. }
  2816. } elseif ($applyMonthRange) {
  2817. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  2818. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2819. $ds = $listTime;
  2820. }
  2821. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  2822. continue;
  2823. }
  2824. $mo = (int)$m[2];
  2825. if ($mo < 1 || $mo > 12) {
  2826. continue;
  2827. }
  2828. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2829. $rowMonthStart = $ymRow . '-01 00:00:00';
  2830. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2831. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2832. continue;
  2833. }
  2834. }
  2835. if ($search !== '') {
  2836. $hitSearch = false;
  2837. foreach ($searchColNames as $c) {
  2838. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  2839. if ($cell !== '' && $strContains($cell, $search)) {
  2840. $hitSearch = true;
  2841. break;
  2842. }
  2843. }
  2844. if (!$hitSearch) {
  2845. continue;
  2846. }
  2847. }
  2848. foreach ($filterArr as $fk => $fv) {
  2849. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  2850. continue;
  2851. }
  2852. if (is_array($fv)) {
  2853. continue;
  2854. }
  2855. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  2856. continue;
  2857. }
  2858. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  2859. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  2860. $field = $stripAlias($fk);
  2861. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  2862. $cellStr = trim((string)$cell);
  2863. switch ($sym) {
  2864. case '=':
  2865. if ((string)$cell !== (string)$fv) {
  2866. continue 3;
  2867. }
  2868. break;
  2869. case '<>':
  2870. if ((string)$cell === (string)$fv) {
  2871. continue 3;
  2872. }
  2873. break;
  2874. case 'LIKE':
  2875. case 'NOT LIKE':
  2876. $needle = trim((string)$fv);
  2877. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  2878. if ($sym === 'LIKE' && !$hit) {
  2879. continue 3;
  2880. }
  2881. if ($sym === 'NOT LIKE' && $hit) {
  2882. continue 3;
  2883. }
  2884. break;
  2885. case '>':
  2886. case '>=':
  2887. case '<':
  2888. case '<=':
  2889. if (!is_numeric($cell) && $cellStr === '') {
  2890. continue 3;
  2891. }
  2892. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  2893. $vv = (float)$fv;
  2894. if ($sym === '>' && !($cv > $vv)) {
  2895. continue 3;
  2896. }
  2897. if ($sym === '>=' && !($cv >= $vv)) {
  2898. continue 3;
  2899. }
  2900. if ($sym === '<' && !($cv < $vv)) {
  2901. continue 3;
  2902. }
  2903. if ($sym === '<=' && !($cv <= $vv)) {
  2904. continue 3;
  2905. }
  2906. break;
  2907. case 'RANGE':
  2908. case 'NOT RANGE':
  2909. case 'BETWEEN':
  2910. case 'NOT BETWEEN':
  2911. case 'BETWEEN TIME':
  2912. case 'NOT BETWEEN TIME':
  2913. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  2914. $rawR = str_replace(' - ', ',', $rawR);
  2915. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  2916. if (count($arr) < 2) {
  2917. break;
  2918. }
  2919. $lo = $arr[0];
  2920. $hi = $arr[1];
  2921. if ($lo === '' && $hi === '') {
  2922. break;
  2923. }
  2924. $isNot = (strpos($sym, 'NOT') !== false);
  2925. if ($lo === '') {
  2926. $in = ($cellStr !== '' && $cellStr <= $hi);
  2927. if ($isNot ? $in : !$in) {
  2928. continue 3;
  2929. }
  2930. break;
  2931. }
  2932. if ($hi === '') {
  2933. $in = ($cellStr !== '' && $cellStr >= $lo);
  2934. if ($isNot ? $in : !$in) {
  2935. continue 3;
  2936. }
  2937. break;
  2938. }
  2939. $in = ($cellStr >= $lo && $cellStr <= $hi);
  2940. if ($isNot ? $in : !$in) {
  2941. continue 3;
  2942. }
  2943. break;
  2944. case 'NULL':
  2945. case 'IS NULL':
  2946. if ($cell !== null && $cell !== '') {
  2947. continue 3;
  2948. }
  2949. break;
  2950. case 'NOT NULL':
  2951. case 'IS NOT NULL':
  2952. if ($cell === null || $cell === '') {
  2953. continue 3;
  2954. }
  2955. break;
  2956. default:
  2957. break;
  2958. }
  2959. }
  2960. $filtered[] = $r;
  2961. }
  2962. return $filtered;
  2963. }
  2964. /**
  2965. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  2966. */
  2967. public function snapshotToProcure()
  2968. {
  2969. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2970. $this->error(__('Invalid parameters'));
  2971. }
  2972. $row = json_decode($this->request->post('row_json', ''), true);
  2973. if (!is_array($row)) {
  2974. $this->error(__('Invalid parameters'));
  2975. }
  2976. try {
  2977. $ids = $this->extractScydgyRowId($row);
  2978. if (!$this->isValidScydgyRowId($ids)) {
  2979. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2980. }
  2981. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2982. $data = [
  2983. 'scydgy_id' => $ids,
  2984. 'CCYDH' => $row['CCYDH'] ?? null,
  2985. 'CYJMC' => $row['CYJMC'] ?? null,
  2986. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2987. 'CDXMC' => $row['CDXMC'] ?? null,
  2988. 'CGYBH' => $row['CGYBH'] ?? null,
  2989. 'CGYMC' => $row['CGYMC'] ?? null,
  2990. 'CDW' => $row['CDW'] ?? null,
  2991. 'NGZL' => $row['NGZL'] ?? null,
  2992. 'CDF' => $row['CDF'] ?? null,
  2993. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2994. 'MBZ' => $row['MBZ'] ?? null,
  2995. 'bwjg' => $row['bwjg'] ?? null,
  2996. 'iStatus' => $row['iStatus'] ?? null,
  2997. 'dStamp' => $row['dStamp'] ?? null,
  2998. 'dputrecord' => $row['dputrecord'] ?? null,
  2999. 'cywyxm' => $row['cywyxm'] ?? null,
  3000. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3001. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3002. ];
  3003. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3004. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3005. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3006. $this->success('操作成功');
  3007. return;
  3008. }
  3009. if ($exists) {
  3010. $upd = $data;
  3011. unset($upd['scydgy_id'], $upd['status']);
  3012. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3013. } else {
  3014. // 新增:不写 status(空/走库默认);仅写创建时间
  3015. $data['createtime'] = date('Y-m-d H:i:s');
  3016. Db::table('purchase_order')->insert($data);
  3017. }
  3018. } catch (\Throwable $e) {
  3019. $this->error($e->getMessage());
  3020. }
  3021. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3022. $this->success('操作成功');
  3023. }
  3024. /**
  3025. * 未发列表
  3026. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3027. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3028. */
  3029. public function completeDirectly()
  3030. {
  3031. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3032. $this->error(__('参数错误'));
  3033. }
  3034. if (!$this->procuremenCanComplete()) {
  3035. $this->error(__('You have no permission'));
  3036. }
  3037. $row = json_decode($this->request->post('row_json', ''), true);
  3038. if (!is_array($row)) {
  3039. $this->error(__('Invalid parameters'));
  3040. }
  3041. $finishRaw = $this->request->post('finish', '1');
  3042. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3043. $poIdLog = null;
  3044. try {
  3045. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3046. $ids = $this->extractScydgyRowId($row);
  3047. if (!$this->isValidScydgyRowId($ids)) {
  3048. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3049. }
  3050. if ($asComplete) {
  3051. $this->assertPickRowCanComplete($ids, $row);
  3052. }
  3053. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3054. $data = [
  3055. 'scydgy_id' => $ids,
  3056. 'CCYDH' => $row['CCYDH'] ?? null,
  3057. 'CYJMC' => $row['CYJMC'] ?? null,
  3058. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3059. 'CDXMC' => $row['CDXMC'] ?? null,
  3060. 'CGYBH' => $row['CGYBH'] ?? null,
  3061. 'CGYMC' => $row['CGYMC'] ?? null,
  3062. 'CDW' => $row['CDW'] ?? null,
  3063. 'NGZL' => $row['NGZL'] ?? null,
  3064. 'CDF' => $row['CDF'] ?? null,
  3065. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3066. 'MBZ' => $row['MBZ'] ?? null,
  3067. 'bwjg' => $row['bwjg'] ?? null,
  3068. 'iStatus' => $row['iStatus'] ?? null,
  3069. 'dStamp' => $row['dStamp'] ?? null,
  3070. 'dputrecord' => $row['dputrecord'] ?? null,
  3071. 'cywyxm' => $row['cywyxm'] ?? null,
  3072. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3073. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3074. ];
  3075. if ($asComplete) {
  3076. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3077. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3078. }
  3079. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3080. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3081. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3082. $this->success('操作成功');
  3083. return;
  3084. }
  3085. if ($exists) {
  3086. $upd = $data;
  3087. unset($upd['scydgy_id']);
  3088. if (!$asComplete) {
  3089. unset($upd['status']);
  3090. }
  3091. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3092. } else {
  3093. // 新增:不写 status;完结时 $data 已含 status=1
  3094. $data['createtime'] = date('Y-m-d H:i:s');
  3095. Db::table('purchase_order')->insert($data);
  3096. }
  3097. } catch (\Throwable $e) {
  3098. $this->error($e->getMessage());
  3099. }
  3100. try {
  3101. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3102. if (is_array($rpo)) {
  3103. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3104. $poIdLog = $tid > 0 ? $tid : null;
  3105. }
  3106. } catch (\Throwable $e) {
  3107. $poIdLog = null;
  3108. }
  3109. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3110. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3111. if ($asComplete) {
  3112. $this->addOrderLog(
  3113. $ids,
  3114. 'mark_complete',
  3115. '点击「完结」,已标记为已完结',
  3116. $poIdLog
  3117. );
  3118. try {
  3119. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3120. if ($pdfPublicPath === '') {
  3121. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3122. }
  3123. } catch (\Throwable $e) {
  3124. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3125. }
  3126. } else {
  3127. $this->addOrderLog(
  3128. $ids,
  3129. 'save_qty_price',
  3130. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3131. $poIdLog
  3132. );
  3133. }
  3134. $this->pickHiddenScydgySetCache = null;
  3135. $this->success("操作成功");
  3136. }
  3137. /**
  3138. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3139. *
  3140. * @param array<int, array> $rows 引用传递当前页行
  3141. */
  3142. protected function mergePurchaseOrder(array &$rows)
  3143. {
  3144. if ($rows === []) {
  3145. return;
  3146. }
  3147. $ids = [];
  3148. foreach ($rows as $rw) {
  3149. if (!is_array($rw)) {
  3150. continue;
  3151. }
  3152. $id = (int)($rw['ID'] ?? 0);
  3153. if ($id > 0) {
  3154. $ids[$id] = true;
  3155. }
  3156. }
  3157. $idList = array_keys($ids);
  3158. if ($idList === []) {
  3159. return;
  3160. }
  3161. try {
  3162. $list = Db::table('purchase_order')
  3163. ->where('scydgy_id', 'in', $idList)
  3164. ->field('scydgy_id,This_quantity,ceilingPrice')
  3165. ->select();
  3166. } catch (\Throwable $e) {
  3167. return;
  3168. }
  3169. if (!is_array($list)) {
  3170. return;
  3171. }
  3172. $byId = [];
  3173. foreach ($list as $dbRow) {
  3174. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3175. continue;
  3176. }
  3177. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3178. }
  3179. foreach ($rows as &$rw) {
  3180. if (!is_array($rw)) {
  3181. continue;
  3182. }
  3183. $sid = (int)($rw['ID'] ?? 0);
  3184. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3185. continue;
  3186. }
  3187. $db = $byId[$sid];
  3188. if (array_key_exists('This_quantity', $db) && $db['This_quantity'] !== null && $db['This_quantity'] !== '') {
  3189. $rw['This_quantity'] = $db['This_quantity'];
  3190. }
  3191. if (array_key_exists('ceilingPrice', $db) && $db['ceilingPrice'] !== null && $db['ceilingPrice'] !== '') {
  3192. $rw['ceilingPrice'] = $db['ceilingPrice'];
  3193. } elseif (array_key_exists('ceiling_price', $db) && $db['ceiling_price'] !== null && $db['ceiling_price'] !== '') {
  3194. $rw['ceilingPrice'] = $db['ceiling_price'];
  3195. }
  3196. }
  3197. unset($rw);
  3198. }
  3199. /**
  3200. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3201. */
  3202. public function purchaseConfirmPick()
  3203. {
  3204. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3205. $this->error(__('Invalid parameters'));
  3206. }
  3207. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3208. $this->error(__('You have no permission'));
  3209. }
  3210. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3211. if ($batchRaw !== '') {
  3212. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3213. return;
  3214. }
  3215. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3216. $sid = (int)$scydgyId;
  3217. if (!$this->isValidScydgyRowId($sid)) {
  3218. $this->error('参数无效');
  3219. }
  3220. $parseIdList = function ($raw) {
  3221. if (is_array($raw)) {
  3222. $arr = $raw;
  3223. } else {
  3224. $decoded = json_decode((string)$raw, true);
  3225. $arr = is_array($decoded) ? $decoded : [];
  3226. }
  3227. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3228. };
  3229. $selectedRaw = $this->request->post('selected_ids', null);
  3230. if ($selectedRaw === null || $selectedRaw === '') {
  3231. $legacy = (int)$this->request->post('selected_id', 0);
  3232. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3233. } else {
  3234. $selectedIds = $parseIdList($selectedRaw);
  3235. }
  3236. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3237. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3238. try {
  3239. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3240. } catch (\InvalidArgumentException $e) {
  3241. $this->error($e->getMessage());
  3242. } catch (\Throwable $e) {
  3243. $this->error($e->getMessage());
  3244. }
  3245. $this->pickHiddenScydgySetCache = null;
  3246. $this->success('操作成功', '', $result);
  3247. }
  3248. /**
  3249. * 整单采购确认(多道工序一次提交)
  3250. */
  3251. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3252. {
  3253. $decoded = json_decode($batchRaw, true);
  3254. if (!is_array($decoded) || $decoded === []) {
  3255. $this->error('提交数据无效');
  3256. }
  3257. $picks = [];
  3258. foreach ($decoded as $item) {
  3259. if (!is_array($item)) {
  3260. continue;
  3261. }
  3262. $sid = (int)($item['scydgy_id'] ?? 0);
  3263. if (!$this->isValidScydgyRowId($sid)) {
  3264. continue;
  3265. }
  3266. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3267. if (!is_array($sel)) {
  3268. $sel = [(int)$sel];
  3269. }
  3270. $unsel = $item['unselected_ids'] ?? [];
  3271. if (!is_array($unsel)) {
  3272. $unsel = json_decode((string)$unsel, true);
  3273. $unsel = is_array($unsel) ? $unsel : [];
  3274. }
  3275. $picks[] = [
  3276. 'scydgy_id' => $sid,
  3277. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3278. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3279. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3280. ];
  3281. }
  3282. if ($picks === []) {
  3283. $this->error('提交数据无效');
  3284. }
  3285. Db::startTrans();
  3286. $results = [];
  3287. try {
  3288. foreach ($picks as $pick) {
  3289. $results[] = $this->runPurchaseConfirmPick(
  3290. (int)$pick['scydgy_id'],
  3291. $pick['selected_ids'],
  3292. $pick['unselected_ids'],
  3293. (int)$pick['purchase_order_id'],
  3294. false,
  3295. false
  3296. );
  3297. }
  3298. Db::commit();
  3299. } catch (\Throwable $e) {
  3300. Db::rollback();
  3301. $msg = $e->getMessage();
  3302. $this->error($msg !== '' ? $msg : '提交失败');
  3303. }
  3304. try {
  3305. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3306. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3307. } catch (\Throwable $e) {
  3308. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3309. }
  3310. $this->pickHiddenScydgySetCache = null;
  3311. $this->success('操作成功', '', ['batch' => $results]);
  3312. }
  3313. /**
  3314. * @return array<string, mixed>
  3315. */
  3316. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3317. {
  3318. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3319. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3320. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3321. $scydgyId = (string)$sid;
  3322. if ($selectedIds === []) {
  3323. throw new \InvalidArgumentException('请至少勾选一条明细');
  3324. }
  3325. $inter = array_intersect($selectedIds, $unselectedIds);
  3326. if ($inter !== []) {
  3327. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3328. }
  3329. $allIds = $this->purchaseOrderDetail($sid);
  3330. if ($allIds === []) {
  3331. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3332. }
  3333. foreach ($selectedIds as $id) {
  3334. if (!in_array($id, $allIds, true)) {
  3335. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3336. }
  3337. }
  3338. foreach ($unselectedIds as $id) {
  3339. if (!in_array($id, $allIds, true)) {
  3340. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3341. }
  3342. }
  3343. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3344. sort($union, SORT_NUMERIC);
  3345. $expect = $allIds;
  3346. sort($expect, SORT_NUMERIC);
  3347. if ($union !== $expect) {
  3348. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3349. }
  3350. if ($manageTransaction) {
  3351. Db::startTrans();
  3352. }
  3353. try {
  3354. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3355. $aff = 0;
  3356. try {
  3357. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3358. } catch (\Throwable $e) {
  3359. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3360. }
  3361. if ($aff < 1) {
  3362. throw new \Exception('更新选中状态失败');
  3363. }
  3364. $poPayload = [
  3365. 'status' => ProcuremenStatus::PO_COMPLETED,
  3366. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3367. ];
  3368. if ($purchaseOrderId > 0) {
  3369. $poAff = (int)Db::table('purchase_order')
  3370. ->where('id', $purchaseOrderId)
  3371. ->where('scydgy_id', $sid)
  3372. ->update($poPayload);
  3373. if ($poAff < 1) {
  3374. throw new \Exception('主表订单不存在或与工序行不匹配');
  3375. }
  3376. } else {
  3377. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3378. if ($poAff < 1) {
  3379. throw new \Exception('未找到');
  3380. }
  3381. }
  3382. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3383. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3384. if ($manageTransaction) {
  3385. Db::commit();
  3386. }
  3387. } catch (\Throwable $e) {
  3388. if ($manageTransaction) {
  3389. Db::rollback();
  3390. }
  3391. throw $e;
  3392. }
  3393. $poIdFinal = $purchaseOrderId;
  3394. if ($poIdFinal <= 0) {
  3395. try {
  3396. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3397. if (is_array($rpo)) {
  3398. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3399. }
  3400. } catch (\Throwable $e) {
  3401. $poIdFinal = 0;
  3402. }
  3403. }
  3404. $pickNames = [];
  3405. foreach ($selectedIds as $pid) {
  3406. $dr = $this->purchaseOrderDetai($sid, $pid);
  3407. $nm = trim((string)($dr['company_name'] ?? ''));
  3408. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3409. }
  3410. $this->addOrderLog(
  3411. $sid,
  3412. 'purchase_confirm',
  3413. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3414. $poIdFinal > 0 ? $poIdFinal : null
  3415. );
  3416. if ($sendNotifications) {
  3417. try {
  3418. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3419. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3420. 'scydgy_id' => $sid,
  3421. 'selected_ids' => $selectedIds,
  3422. 'unselected_ids' => $unselectedIds,
  3423. 'purchase_order_id' => $purchaseOrderId,
  3424. ]]);
  3425. } catch (\Throwable $e) {
  3426. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3427. }
  3428. }
  3429. Log::write(sprintf(
  3430. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3431. $scydgyId,
  3432. $purchaseOrderId,
  3433. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3434. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3435. ), 'notice');
  3436. $pdfPublicPath = '';
  3437. try {
  3438. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3439. } catch (\Throwable $e) {
  3440. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3441. }
  3442. return [
  3443. 'scydgy_id' => $scydgyId,
  3444. 'purchase_order_id' => $purchaseOrderId,
  3445. 'selected_ids' => $selectedIds,
  3446. 'unselected_ids' => $unselectedIds,
  3447. 'purchase_confirm_pdf' => $pdfPublicPath,
  3448. ];
  3449. }
  3450. /**
  3451. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3452. *
  3453. * @param int[]|string[] $scydgyIds
  3454. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3455. */
  3456. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3457. {
  3458. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3459. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3460. if ($scydgyIds === []) {
  3461. return $empty;
  3462. }
  3463. $pos = [];
  3464. try {
  3465. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3466. } catch (\Throwable $e) {
  3467. $rows = [];
  3468. }
  3469. if (is_array($rows)) {
  3470. foreach ($rows as $po) {
  3471. if (is_array($po)) {
  3472. $pos[] = $po;
  3473. }
  3474. }
  3475. }
  3476. if ($pos === []) {
  3477. return $empty;
  3478. }
  3479. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3480. return [
  3481. 'ccydh' => $ccydh,
  3482. 'pos' => $pos,
  3483. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3484. ];
  3485. }
  3486. /**
  3487. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3488. *
  3489. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3490. * @param array<int, array<string, mixed>> $picks
  3491. */
  3492. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3493. {
  3494. if ($picks === []) {
  3495. return;
  3496. }
  3497. $fallbackDetailId = 0;
  3498. $winners = [];
  3499. $losers = [];
  3500. foreach ($picks as $pick) {
  3501. if (!is_array($pick)) {
  3502. continue;
  3503. }
  3504. $sid = (int)($pick['scydgy_id'] ?? 0);
  3505. if (!$this->isValidScydgyRowId($sid)) {
  3506. continue;
  3507. }
  3508. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3509. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3510. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3511. $fallbackDetailId = (int)$selectedIds[0];
  3512. }
  3513. foreach ($selectedIds as $pid) {
  3514. $dr = $this->purchaseOrderDetai($sid, $pid);
  3515. if (!is_array($dr)) {
  3516. continue;
  3517. }
  3518. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3519. }
  3520. foreach ($unselectedIds as $pid) {
  3521. $dr = $this->purchaseOrderDetai($sid, $pid);
  3522. if (!is_array($dr)) {
  3523. continue;
  3524. }
  3525. $key = $this->notifySupplierDedupeKey($dr);
  3526. if (!isset($winners[$key])) {
  3527. $losers[$key] = $dr;
  3528. }
  3529. }
  3530. }
  3531. if ($winners === [] && $losers === []) {
  3532. return;
  3533. }
  3534. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3535. $sendSmsSafe = function ($phone, $content) {
  3536. $phone = trim((string)$phone);
  3537. if ($phone === '') {
  3538. return;
  3539. }
  3540. try {
  3541. $this->smsbao($phone, $content);
  3542. } catch (\Throwable $e) {
  3543. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3544. }
  3545. };
  3546. foreach ($winners as $dr) {
  3547. $cname = trim((string)($dr['company_name'] ?? ''));
  3548. $ph = trim((string)($dr['phone'] ?? ''));
  3549. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3550. 'company_name' => $cname,
  3551. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3552. 'phone' => $ph,
  3553. ]));
  3554. $sendSmsSafe($ph, $sms);
  3555. }
  3556. foreach ($losers as $dr) {
  3557. $cname = trim((string)($dr['company_name'] ?? ''));
  3558. $ph = trim((string)($dr['phone'] ?? ''));
  3559. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3560. 'company_name' => $cname,
  3561. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3562. 'phone' => $ph,
  3563. ]));
  3564. $sendSmsSafe($ph, $sms);
  3565. }
  3566. }
  3567. /**
  3568. * 短信去重键:优先手机号,否则公司名
  3569. */
  3570. protected function notifySupplierDedupeKey(array $detailRow): string
  3571. {
  3572. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  3573. if ($ph !== '') {
  3574. return 'p:' . $ph;
  3575. }
  3576. $cn = trim((string)($detailRow['company_name'] ?? ''));
  3577. return 'c:' . $cn;
  3578. }
  3579. /**
  3580. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3581. *
  3582. * @param int[] $detailIds
  3583. */
  3584. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3585. {
  3586. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3587. if ($detailIds === []) {
  3588. return;
  3589. }
  3590. $payload = ['status_name' => $statusName];
  3591. try {
  3592. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3593. } catch (\Throwable $e) {
  3594. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3595. }
  3596. }
  3597. /**
  3598. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3599. */
  3600. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3601. {
  3602. try {
  3603. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3604. } catch (\Throwable $e) {
  3605. return;
  3606. }
  3607. if (!is_array($rows)) {
  3608. return;
  3609. }
  3610. foreach ($rows as $dr) {
  3611. if (!is_array($dr)) {
  3612. continue;
  3613. }
  3614. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3615. if ($id <= 0) {
  3616. continue;
  3617. }
  3618. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3619. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3620. try {
  3621. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3622. } catch (\Throwable $e) {
  3623. }
  3624. }
  3625. }
  3626. /**
  3627. * @param array<string, mixed> $detailRow
  3628. */
  3629. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3630. {
  3631. $am = $detailRow['amount'] ?? null;
  3632. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3633. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3634. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3635. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3636. }
  3637. /**
  3638. * @return int[]
  3639. */
  3640. protected function purchaseOrderDetail(int $scydgyId): array
  3641. {
  3642. if (!$this->isValidScydgyRowId($scydgyId)) {
  3643. return [];
  3644. }
  3645. try {
  3646. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3647. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3648. $list = $listQuery->select();
  3649. } catch (\Throwable $e) {
  3650. return [];
  3651. }
  3652. if (!is_array($list)) {
  3653. return [];
  3654. }
  3655. $ids = [];
  3656. foreach ($list as $r) {
  3657. if (!is_array($r)) {
  3658. continue;
  3659. }
  3660. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3661. if ($pk > 0) {
  3662. $ids[] = $pk;
  3663. }
  3664. }
  3665. return array_values(array_unique($ids));
  3666. }
  3667. /**
  3668. * 获取当前登录用户信息 [id, 展示名]
  3669. */
  3670. protected function GetUseName(): array
  3671. {
  3672. $id = 0;
  3673. $name = '';
  3674. try {
  3675. if ($this->auth && $this->auth->isLogin()) {
  3676. $u = $this->auth->getUserInfo();
  3677. if (is_array($u)) {
  3678. $id = (int)($u['id'] ?? 0);
  3679. $name = trim((string)($u['nickname'] ?? ''));
  3680. if ($name === '') {
  3681. $name = trim((string)($u['username'] ?? ''));
  3682. }
  3683. }
  3684. }
  3685. } catch (\Throwable $e) {
  3686. }
  3687. if ($name === '') {
  3688. $name = '未知用户';
  3689. }
  3690. return [$id, $name];
  3691. }
  3692. /**
  3693. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3694. */
  3695. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3696. {
  3697. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3698. }
  3699. /**
  3700. * 按主键取一条
  3701. */
  3702. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3703. {
  3704. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3705. return [];
  3706. }
  3707. try {
  3708. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3709. if (is_array($one)) {
  3710. return $one;
  3711. }
  3712. } catch (\Throwable $e) {
  3713. }
  3714. try {
  3715. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3716. if (is_array($one)) {
  3717. return $one;
  3718. }
  3719. } catch (\Throwable $e) {
  3720. }
  3721. return [];
  3722. }
  3723. /**
  3724. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3725. */
  3726. protected function formatProcuremenDetailTime($v): string
  3727. {
  3728. if ($v === null || $v === '') {
  3729. return '';
  3730. }
  3731. if (is_numeric($v) && (int)$v > 946684800) {
  3732. return date('Y-m-d H:i:s', (int)$v);
  3733. }
  3734. return ProcuremenTime::formatDisplayDateTime($v);
  3735. }
  3736. /**
  3737. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3738. */
  3739. protected function formatDeliveryYmd($v): string
  3740. {
  3741. if ($v === null || $v === '') {
  3742. return '';
  3743. }
  3744. $s = trim((string)$v);
  3745. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3746. return '';
  3747. }
  3748. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  3749. return $m[1];
  3750. }
  3751. $ts = strtotime($s);
  3752. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  3753. }
  3754. /**
  3755. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  3756. */
  3757. protected function detailRowSupplierOperated(array $r): bool
  3758. {
  3759. $am = $r['amount'] ?? null;
  3760. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3761. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3762. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3763. return $okAmt || $okDel;
  3764. }
  3765. /**
  3766. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  3767. */
  3768. protected function resolveDetailSupplierOperTime(array $r): string
  3769. {
  3770. if (!$this->detailRowSupplierOperated($r)) {
  3771. return '';
  3772. }
  3773. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  3774. if ($t !== '') {
  3775. return $t;
  3776. }
  3777. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  3778. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  3779. continue;
  3780. }
  3781. $t = $this->formatProcuremenDetailTime($r[$col]);
  3782. if ($t !== '') {
  3783. return $t;
  3784. }
  3785. }
  3786. return '';
  3787. }
  3788. /**
  3789. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  3790. */
  3791. protected function detailRowSupplierAccepted(array $r): bool
  3792. {
  3793. $am = $r['amount'] ?? null;
  3794. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3795. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3796. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3797. return $okAmt && $okDel;
  3798. }
  3799. /**
  3800. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  3801. */
  3802. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  3803. {
  3804. if ($detailCount > 0) {
  3805. return true;
  3806. }
  3807. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  3808. return true;
  3809. }
  3810. $pickTime = trim((string)($main['pick_time'] ?? ''));
  3811. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  3812. return true;
  3813. }
  3814. return false;
  3815. }
  3816. /**
  3817. * 下发时间:优先 pick_time,其次首条下发明细时间
  3818. */
  3819. protected function resolveProcuremenIssueTime(array $main, array $details): string
  3820. {
  3821. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  3822. if ($issueTime !== '') {
  3823. return $issueTime;
  3824. }
  3825. foreach ($details as $dr) {
  3826. if (!is_array($dr)) {
  3827. continue;
  3828. }
  3829. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3830. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  3831. $issueTime = $t;
  3832. }
  3833. }
  3834. if ($issueTime !== '') {
  3835. return $issueTime;
  3836. }
  3837. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3838. }
  3839. /**
  3840. * 直接点「完结」时间:优先操作记录 mark_complete
  3841. */
  3842. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  3843. {
  3844. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  3845. }
  3846. /**
  3847. * 操作记录时间(取指定 action 最近一条)
  3848. *
  3849. * @param string|array<int, string> $actions
  3850. */
  3851. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  3852. {
  3853. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  3854. }
  3855. /**
  3856. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  3857. *
  3858. * @param array $main purchase_order 一行
  3859. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  3860. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  3861. */
  3862. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  3863. {
  3864. $issueCnt = count($details);
  3865. $acceptCnt = 0;
  3866. $pickedName = '';
  3867. $pickedTime = '';
  3868. foreach ($details as $dr) {
  3869. if (!is_array($dr)) {
  3870. continue;
  3871. }
  3872. if ($this->detailRowSupplierAccepted($dr)) {
  3873. $acceptCnt++;
  3874. }
  3875. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3876. if ($pickedName === '') {
  3877. $pickedName = trim((string)($dr['company_name'] ?? ''));
  3878. }
  3879. if ($pickedTime === '') {
  3880. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  3881. if ($pickedTime === '') {
  3882. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3883. }
  3884. }
  3885. }
  3886. }
  3887. $hasMain = $main !== [];
  3888. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  3889. if ($poTime === '') {
  3890. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  3891. }
  3892. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  3893. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  3894. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  3895. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  3896. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  3897. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  3898. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  3899. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  3900. $supplierTime = '';
  3901. if ($acceptCnt > 0) {
  3902. foreach ($details as $dr) {
  3903. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  3904. continue;
  3905. }
  3906. $t = $this->resolveDetailSupplierOperTime($dr);
  3907. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  3908. $supplierTime = $t;
  3909. }
  3910. }
  3911. }
  3912. $directComplete = ($mainCompleted && !$issued);
  3913. $doneTime = '';
  3914. if ($mainCompleted) {
  3915. if ($directComplete) {
  3916. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  3917. }
  3918. if ($doneTime === '') {
  3919. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3920. }
  3921. if ($doneTime === '') {
  3922. foreach ($details as $dr) {
  3923. if (!is_array($dr)) {
  3924. continue;
  3925. }
  3926. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  3927. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  3928. $doneTime = $t;
  3929. }
  3930. }
  3931. }
  3932. if ($doneTime === '') {
  3933. $doneTime = $poTime;
  3934. }
  3935. if ($confirmApproveTime !== '') {
  3936. $doneTime = $confirmApproveTime;
  3937. }
  3938. }
  3939. if ($directComplete) {
  3940. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  3941. $step1Done = $hasMain;
  3942. $step2Done = false;
  3943. $step3Done = false;
  3944. $step4Done = false;
  3945. $step5Done = false;
  3946. $step6Done = true;
  3947. } else {
  3948. $step1Done = $issued;
  3949. $step2Done = $issued;
  3950. $step3Done = $acceptCnt > 0;
  3951. $step4Done = $wflowPendingApproval;
  3952. if (!$step4Done) {
  3953. foreach ($details as $dr) {
  3954. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3955. $step4Done = true;
  3956. break;
  3957. }
  3958. }
  3959. }
  3960. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  3961. $step6Done = $mainCompleted;
  3962. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  3963. if ($mainCompleted && $issued) {
  3964. $step3Done = true;
  3965. $step4Done = true;
  3966. $step5Done = true;
  3967. if ($supplierTime === '') {
  3968. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3969. if ($fillT !== '') {
  3970. $supplierTime = $fillT;
  3971. }
  3972. }
  3973. if ($pickedTime === '') {
  3974. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3975. if ($fillT !== '') {
  3976. $pickedTime = $fillT;
  3977. }
  3978. }
  3979. if ($auditSelectTime === '') {
  3980. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3981. if ($fillT !== '') {
  3982. $auditSelectTime = $fillT;
  3983. }
  3984. }
  3985. if ($confirmApproveTime === '') {
  3986. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3987. if ($fillT !== '') {
  3988. $confirmApproveTime = $fillT;
  3989. }
  3990. }
  3991. }
  3992. }
  3993. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  3994. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  3995. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  3996. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  3997. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  3998. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  3999. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4000. $steps = [
  4001. [
  4002. 'title' => '未发',
  4003. 'subtitle' => '',
  4004. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  4005. 'done' => $step1Done,
  4006. ],
  4007. [
  4008. 'title' => '下发',
  4009. 'subtitle' => '',
  4010. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  4011. 'done' => $step2Done,
  4012. ],
  4013. [
  4014. 'title' => '供应商接单',
  4015. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4016. 'time' => '',
  4017. 'done' => $step3Done,
  4018. ],
  4019. [
  4020. 'title' => '待确认',
  4021. 'subtitle' => $step4Done
  4022. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4023. : ($issued ? '待选供应商' : ''),
  4024. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  4025. 'done' => $step4Done,
  4026. ],
  4027. [
  4028. 'title' => '待审批',
  4029. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4030. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  4031. 'done' => $step5Done,
  4032. ],
  4033. [
  4034. 'title' => '已完结',
  4035. 'subtitle' => '',
  4036. 'time' => $step6Done ? $doneTime : '',
  4037. 'done' => $step6Done,
  4038. ],
  4039. ];
  4040. $currentIdx = count($steps) - 1;
  4041. if (!$directComplete) {
  4042. foreach ($steps as $i => $s) {
  4043. if (!$s['done']) {
  4044. $currentIdx = $i;
  4045. break;
  4046. }
  4047. }
  4048. }
  4049. $nSteps = count($steps);
  4050. foreach ($steps as $idx => &$s) {
  4051. $s['current'] = ($idx === $currentIdx);
  4052. if ($idx === 0) {
  4053. $s['pdf_left_bg'] = '';
  4054. } else {
  4055. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4056. }
  4057. if ($idx >= $nSteps - 1) {
  4058. $s['pdf_right_bg'] = '';
  4059. } else {
  4060. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4061. }
  4062. }
  4063. unset($s);
  4064. $labelMap = [
  4065. 'CCYDH' => '订单号',
  4066. 'CYJMC' => '印件名称',
  4067. 'CCLBMMC' => '承揽部门',
  4068. 'CGYMC' => '工序名称',
  4069. 'CDW' => '单位',
  4070. 'NGZL' => '工作量',
  4071. 'CDF' => '单价',
  4072. 'cGzzxMc' => '工作中心',
  4073. 'MBZ' => '备注',
  4074. 'This_quantity' => '本次数量',
  4075. 'ceilingPrice' => '最高限价',
  4076. ];
  4077. $orderSummary = [];
  4078. foreach ($labelMap as $key => $lab) {
  4079. if (!array_key_exists($key, $main)) {
  4080. continue;
  4081. }
  4082. $val = $main[$key];
  4083. if ($val === null) {
  4084. $val = '';
  4085. } elseif (!is_scalar($val)) {
  4086. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4087. } else {
  4088. $val = (string)$val;
  4089. }
  4090. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4091. }
  4092. $orderSummaryGrid = [];
  4093. $n = count($orderSummary);
  4094. for ($i = 0; $i < $n; $i += 2) {
  4095. $left = $orderSummary[$i];
  4096. $hasRight = ($i + 1) < $n;
  4097. $orderSummaryGrid[] = [
  4098. 'l1' => $left['label'],
  4099. 'v1' => $left['value'],
  4100. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4101. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4102. ];
  4103. }
  4104. return [
  4105. 'steps' => $steps,
  4106. 'orderSummary' => $orderSummary,
  4107. 'orderSummaryGrid' => $orderSummaryGrid,
  4108. 'detailRows' => $details,
  4109. ];
  4110. }
  4111. /**
  4112. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4113. *
  4114. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4115. */
  4116. protected function prepareProcuremenDetailsView(string $ids): array
  4117. {
  4118. $main = [];
  4119. try {
  4120. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4121. $main = is_array($one) ? $one : [];
  4122. } catch (\Throwable $e) {
  4123. $main = [];
  4124. }
  4125. $details = [];
  4126. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4127. if ($mergeRows === []) {
  4128. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4129. if ($mergeRows === [] && $main !== []) {
  4130. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4131. }
  4132. }
  4133. $detailSidList = [];
  4134. $anchorSid = (int)$ids;
  4135. if ($anchorSid !== 0) {
  4136. $detailSidList[$anchorSid] = true;
  4137. }
  4138. foreach ($mergeRows as $mr) {
  4139. if (!is_array($mr)) {
  4140. continue;
  4141. }
  4142. $sid = $this->extractScydgyRowId($mr);
  4143. if ($sid !== 0) {
  4144. $detailSidList[$sid] = true;
  4145. }
  4146. }
  4147. try {
  4148. if ($detailSidList !== []) {
  4149. $details = Db::table('purchase_order_detail')
  4150. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4151. ->order('id', 'asc')
  4152. ->select();
  4153. }
  4154. } catch (\Throwable $e) {
  4155. $details = [];
  4156. }
  4157. if (!is_array($details)) {
  4158. $details = [];
  4159. }
  4160. foreach ($details as &$r) {
  4161. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4162. $r['id'] = $r['ID'];
  4163. }
  4164. if (isset($r['createtime'])) {
  4165. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4166. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4167. } else {
  4168. $r['createtime_text'] = (string)$r['createtime'];
  4169. }
  4170. } else {
  4171. $r['createtime_text'] = '';
  4172. }
  4173. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4174. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4175. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4176. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4177. if (is_array($r)) {
  4178. $r = $this->maskSupplierContactFields($r);
  4179. }
  4180. }
  4181. unset($r);
  4182. $activeDetails = [];
  4183. foreach ($details as $r) {
  4184. if (is_array($r) && empty($r['is_void'])) {
  4185. $activeDetails[] = $r;
  4186. }
  4187. }
  4188. $operLogs = [];
  4189. try {
  4190. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  4191. } catch (\Throwable $e) {
  4192. $operLogs = [];
  4193. }
  4194. if (!is_array($operLogs)) {
  4195. $operLogs = [];
  4196. }
  4197. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4198. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4199. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4200. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4201. if ($ccydh === '') {
  4202. foreach ($details as $r) {
  4203. if (!is_array($r)) {
  4204. continue;
  4205. }
  4206. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4207. if ($ccydh !== '') {
  4208. break;
  4209. }
  4210. }
  4211. }
  4212. $this->view->assign('ccydh', $ccydh);
  4213. $this->view->assign('steps', $bundle['steps']);
  4214. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4215. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4216. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4217. $this->view->assign('processCount', count($mergeRows));
  4218. $this->view->assign('detailRows', $details);
  4219. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4220. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4221. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4222. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4223. $this->view->assign('operLogs', $operLogs);
  4224. return [
  4225. 'ok' => $main !== [] || $details !== [],
  4226. 'ccydh' => $ccydh,
  4227. ];
  4228. }
  4229. /**
  4230. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4231. */
  4232. public function details()
  4233. {
  4234. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4235. if (is_array($ids)) {
  4236. $ids = isset($ids[0]) ? $ids[0] : '';
  4237. }
  4238. $ids = trim((string)$ids);
  4239. if ($ids === '') {
  4240. $this->error(__('Invalid parameters'));
  4241. }
  4242. $this->assertManualOrderDetailsViewable((int)$ids);
  4243. $this->prepareProcuremenDetailsView($ids);
  4244. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4245. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4246. $this->view->engine->layout(false);
  4247. try {
  4248. return $this->view->fetch('procuremen/details_dialog_shell');
  4249. } finally {
  4250. if ($restoreLayout) {
  4251. $this->view->engine->layout($restoreLayout);
  4252. }
  4253. }
  4254. }
  4255. /**
  4256. * 解析合并审核工序行(订单号须一致,且均未协助)
  4257. *
  4258. * @return array<int, array<string, mixed>>
  4259. */
  4260. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4261. {
  4262. $primary = json_decode($rowJson, true);
  4263. if (!is_array($primary)) {
  4264. $this->error(__('Invalid parameters'));
  4265. }
  4266. $merge = json_decode($mergeRowsJson, true);
  4267. if (!is_array($merge) || $merge === []) {
  4268. $merge = [$primary];
  4269. }
  4270. $seen = [];
  4271. $out = [];
  4272. foreach ($merge as $r) {
  4273. if (!is_array($r)) {
  4274. continue;
  4275. }
  4276. $id = $this->extractScydgyRowId($r);
  4277. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4278. continue;
  4279. }
  4280. $seen[$id] = true;
  4281. $out[] = $r;
  4282. }
  4283. if ($out === []) {
  4284. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4285. }
  4286. $ccydh = null;
  4287. foreach ($out as $r) {
  4288. $dh = trim((string)($r['CCYDH'] ?? ''));
  4289. if ($ccydh === null) {
  4290. $ccydh = $dh;
  4291. } elseif ($dh !== $ccydh) {
  4292. $this->error('合并审核要求所选行的订单号一致');
  4293. }
  4294. }
  4295. $ids = [];
  4296. foreach ($out as $r) {
  4297. $id = $this->extractScydgyRowId($r);
  4298. if ($this->isValidScydgyRowId($id)) {
  4299. $ids[$id] = true;
  4300. }
  4301. }
  4302. $poBySid = [];
  4303. $detCntBySid = [];
  4304. if ($ids !== []) {
  4305. $idList = array_keys($ids);
  4306. try {
  4307. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4308. if (is_array($poList)) {
  4309. foreach ($poList as $po) {
  4310. if (!is_array($po)) {
  4311. continue;
  4312. }
  4313. $sid = (int)($po['scydgy_id'] ?? 0);
  4314. if ($this->isValidScydgyRowId($sid)) {
  4315. $poBySid[$sid] = $po;
  4316. }
  4317. }
  4318. }
  4319. } catch (\Throwable $e) {
  4320. }
  4321. try {
  4322. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4323. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4324. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4325. if (is_array($detRows)) {
  4326. foreach ($detRows as $dr) {
  4327. if (!is_array($dr)) {
  4328. continue;
  4329. }
  4330. $sid = (int)($dr['scydgy_id'] ?? 0);
  4331. if ($this->isValidScydgyRowId($sid)) {
  4332. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4333. }
  4334. }
  4335. }
  4336. } catch (\Throwable $e) {
  4337. }
  4338. }
  4339. foreach ($out as $r) {
  4340. $id = $this->extractScydgyRowId($r);
  4341. if (!$this->isValidScydgyRowId($id)) {
  4342. continue;
  4343. }
  4344. $po = $poBySid[$id] ?? null;
  4345. if (!is_array($po)) {
  4346. continue;
  4347. }
  4348. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4349. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4350. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4351. }
  4352. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4353. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4354. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4355. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4356. }
  4357. }
  4358. return $out;
  4359. }
  4360. /**
  4361. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4362. */
  4363. protected function maskSupplierContactFields(array $item): array
  4364. {
  4365. if (array_key_exists('email', $item)) {
  4366. $item['email'] = mask_email((string)$item['email']);
  4367. }
  4368. if (array_key_exists('phone', $item)) {
  4369. $item['phone'] = mask_phone((string)$item['phone']);
  4370. }
  4371. return $item;
  4372. }
  4373. /**
  4374. * @param array<int, array<string, mixed>> $list
  4375. * @return array<int, array<string, mixed>>
  4376. */
  4377. protected function maskSupplierContactList(array $list): array
  4378. {
  4379. $out = [];
  4380. foreach ($list as $item) {
  4381. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4382. }
  4383. return $out;
  4384. }
  4385. /**
  4386. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4387. *
  4388. * @return array<string, string>|null
  4389. */
  4390. protected function buildCustomerContactPayloadFromRow($row): ?array
  4391. {
  4392. if (!is_array($row)) {
  4393. return null;
  4394. }
  4395. $norm = [];
  4396. foreach ($row as $k => $v) {
  4397. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4398. }
  4399. $row = $norm;
  4400. $st = $row['status'] ?? '';
  4401. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4402. return null;
  4403. }
  4404. $companyName = '';
  4405. foreach (['company_name', 'name'] as $nk) {
  4406. if (!empty($row[$nk])) {
  4407. $companyName = trim((string)$row[$nk]);
  4408. break;
  4409. }
  4410. }
  4411. if ($companyName === '') {
  4412. return null;
  4413. }
  4414. $username = '';
  4415. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4416. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4417. $username = trim((string)$row[$uk]);
  4418. break;
  4419. }
  4420. }
  4421. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4422. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4423. if ($phone === '' && isset($row['account'])) {
  4424. $phone = trim((string)$row['account']);
  4425. }
  4426. if ($phone === '' && isset($row['mobile'])) {
  4427. $phone = trim((string)$row['mobile']);
  4428. }
  4429. if ($email === '' && $phone === '') {
  4430. return null;
  4431. }
  4432. $category = '';
  4433. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4434. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4435. $category = trim((string)$row[$ck]);
  4436. break;
  4437. }
  4438. }
  4439. return [
  4440. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4441. 'name' => $companyName,
  4442. 'company_name' => $companyName,
  4443. 'username' => $username,
  4444. 'email' => $email,
  4445. 'phone' => $phone,
  4446. 'category' => $category,
  4447. 'company_type' => $category,
  4448. ];
  4449. }
  4450. /**
  4451. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4452. */
  4453. protected function resolveCustomerContactById(string $id): ?array
  4454. {
  4455. $id = trim($id);
  4456. if ($id === '' || !ctype_digit($id)) {
  4457. return null;
  4458. }
  4459. try {
  4460. $row = Db::table('customer')->where('id', (int)$id)->find();
  4461. } catch (\Throwable $e) {
  4462. return null;
  4463. }
  4464. return $this->buildCustomerContactPayloadFromRow($row);
  4465. }
  4466. /**
  4467. * 按供应商名称解析联系信息(兼容旧提交数据)
  4468. */
  4469. protected function resolveCustomerContactByCompanyName(string $name): ?array
  4470. {
  4471. $name = trim($name);
  4472. if ($name === '') {
  4473. return null;
  4474. }
  4475. try {
  4476. $row = Db::table('customer')
  4477. ->where(function ($q) use ($name) {
  4478. $q->where('company_name', $name)->whereOr('name', $name);
  4479. })
  4480. ->order('id', 'desc')
  4481. ->find();
  4482. } catch (\Throwable $e) {
  4483. return null;
  4484. }
  4485. return $this->buildCustomerContactPayloadFromRow($row);
  4486. }
  4487. /**
  4488. * 规范化下发/确认时勾选的供应商
  4489. *
  4490. * @param array<int, mixed> $companies
  4491. * @return array<int, array<string, string>>
  4492. */
  4493. protected function normalizePickCompanies(array $companies): array
  4494. {
  4495. $out = [];
  4496. foreach ($companies as $c) {
  4497. if (!is_array($c)) {
  4498. continue;
  4499. }
  4500. $resolved = null;
  4501. $cid = trim((string)($c['id'] ?? ''));
  4502. if ($cid !== '') {
  4503. $resolved = $this->resolveCustomerContactById($cid);
  4504. }
  4505. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  4506. if ($resolved === null && $name !== '') {
  4507. $resolved = $this->resolveCustomerContactByCompanyName($name);
  4508. }
  4509. if ($resolved === null) {
  4510. continue;
  4511. }
  4512. $out[] = $resolved;
  4513. }
  4514. return $out;
  4515. }
  4516. /**
  4517. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  4518. *
  4519. * @param array<int, array<string, mixed>> $pool
  4520. * @return array<int, array<string, mixed>>
  4521. */
  4522. protected function collapseProcuremenPoolByOrder(array $pool): array
  4523. {
  4524. if ($pool === []) {
  4525. return [];
  4526. }
  4527. $groups = [];
  4528. foreach ($pool as $row) {
  4529. if (!is_array($row)) {
  4530. continue;
  4531. }
  4532. $dh = trim((string)($row['CCYDH'] ?? ''));
  4533. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  4534. if (!isset($groups[$key])) {
  4535. $groups[$key] = [];
  4536. }
  4537. $groups[$key][] = $row;
  4538. }
  4539. $out = [];
  4540. foreach ($groups as $ccydh => $rows) {
  4541. if ($rows === []) {
  4542. continue;
  4543. }
  4544. usort($rows, function ($a, $b) {
  4545. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  4546. });
  4547. $head = $rows[0];
  4548. $gymcList = [];
  4549. foreach ($rows as $r) {
  4550. $g = trim((string)($r['CGYMC'] ?? ''));
  4551. if ($g !== '' && !in_array($g, $gymcList, true)) {
  4552. $gymcList[] = $g;
  4553. }
  4554. }
  4555. $merged = $head;
  4556. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  4557. $merged['process_count'] = count($rows);
  4558. $merged['_order_merge_rows'] = $rows;
  4559. if (count($rows) > 1) {
  4560. $merged['CGYMC'] = implode('、', $gymcList);
  4561. }
  4562. $mergedPickTime = '';
  4563. foreach ($rows as $r) {
  4564. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  4565. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  4566. $mergedPickTime = $t;
  4567. }
  4568. }
  4569. if ($mergedPickTime !== '') {
  4570. $merged['pick_time'] = $mergedPickTime;
  4571. }
  4572. $out[] = $merged;
  4573. }
  4574. usort($out, function ($a, $b) {
  4575. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  4576. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  4577. if ($ta === $tb) {
  4578. $ida = (int)($a['purchase_order_id'] ?? 0);
  4579. $idb = (int)($b['purchase_order_id'] ?? 0);
  4580. if ($ida !== $idb) {
  4581. return $idb <=> $ida;
  4582. }
  4583. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  4584. }
  4585. if ($ta === '') {
  4586. return 1;
  4587. }
  4588. if ($tb === '') {
  4589. return -1;
  4590. }
  4591. return strcmp($tb, $ta);
  4592. });
  4593. return $out;
  4594. }
  4595. /**
  4596. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  4597. *
  4598. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4599. */
  4600. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  4601. {
  4602. $scydgyId = trim($scydgyId);
  4603. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4604. if ($scydgyId === '') {
  4605. return $empty;
  4606. }
  4607. try {
  4608. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4609. } catch (\Throwable $e) {
  4610. $anchor = null;
  4611. }
  4612. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  4613. return $empty;
  4614. }
  4615. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4616. if ($ccydh === '') {
  4617. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4618. }
  4619. try {
  4620. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4621. } catch (\Throwable $e) {
  4622. $pos = [$anchor];
  4623. }
  4624. if (!is_array($pos) || $pos === []) {
  4625. $pos = [$anchor];
  4626. }
  4627. return [
  4628. 'ccydh' => $ccydh,
  4629. 'pos' => $pos,
  4630. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4631. ];
  4632. }
  4633. /**
  4634. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4635. */
  4636. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4637. {
  4638. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4639. return false;
  4640. }
  4641. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4642. return false;
  4643. }
  4644. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4645. return true;
  4646. }
  4647. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4648. $sid = (int)($po['scydgy_id'] ?? 0);
  4649. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4650. }
  4651. return false;
  4652. }
  4653. /**
  4654. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4655. *
  4656. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4657. */
  4658. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4659. {
  4660. $scydgyId = trim($scydgyId);
  4661. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4662. if ($scydgyId === '') {
  4663. return $empty;
  4664. }
  4665. try {
  4666. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4667. } catch (\Throwable $e) {
  4668. $anchor = null;
  4669. }
  4670. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4671. return $empty;
  4672. }
  4673. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4674. if ($ccydh === '') {
  4675. return [
  4676. 'ccydh' => '',
  4677. 'pos' => [$anchor],
  4678. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  4679. ];
  4680. }
  4681. try {
  4682. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  4683. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  4684. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  4685. } catch (\Throwable $e) {
  4686. $pos = [$anchor];
  4687. }
  4688. if (!is_array($pos) || $pos === []) {
  4689. $pos = [$anchor];
  4690. }
  4691. $pos = array_values(array_filter($pos, function ($po) {
  4692. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  4693. }));
  4694. if ($pos === []) {
  4695. $pos = [$anchor];
  4696. }
  4697. return [
  4698. 'ccydh' => $ccydh,
  4699. 'pos' => $pos,
  4700. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4701. ];
  4702. }
  4703. /**
  4704. * @param array<int, array<string, mixed>> $purchaseOrders
  4705. * @return array<int, array<string, mixed>>
  4706. */
  4707. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  4708. {
  4709. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  4710. $byId = [];
  4711. foreach ($pool as $r) {
  4712. if (!is_array($r)) {
  4713. continue;
  4714. }
  4715. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  4716. if ($this->isValidScydgyRowId($sid)) {
  4717. $byId[$sid] = $r;
  4718. }
  4719. }
  4720. $out = [];
  4721. foreach ($purchaseOrders as $po) {
  4722. if (!is_array($po)) {
  4723. continue;
  4724. }
  4725. $sid = (int)($po['scydgy_id'] ?? 0);
  4726. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  4727. $out[] = $byId[$sid];
  4728. }
  4729. }
  4730. return $out;
  4731. }
  4732. /**
  4733. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  4734. *
  4735. * @return array<int, array<string, mixed>>
  4736. */
  4737. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  4738. {
  4739. $scydgyId = trim($scydgyId);
  4740. if ($scydgyId === '') {
  4741. return [];
  4742. }
  4743. try {
  4744. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4745. } catch (\Throwable $e) {
  4746. $anchor = null;
  4747. }
  4748. if (!is_array($anchor)) {
  4749. return [];
  4750. }
  4751. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  4752. return [];
  4753. }
  4754. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4755. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  4756. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  4757. try {
  4758. $q = Db::table('purchase_order');
  4759. if ($ccydh !== '') {
  4760. $q->where('CCYDH', $ccydh);
  4761. } else {
  4762. $q->where('scydgy_id', $scydgyId);
  4763. }
  4764. if ($isValidPick) {
  4765. $q->where('pick_time', $pickTime);
  4766. }
  4767. $pos = $q->order('scydgy_id', 'asc')->select();
  4768. } catch (\Throwable $e) {
  4769. $pos = [$anchor];
  4770. }
  4771. if (!is_array($pos) || $pos === []) {
  4772. $pos = [$anchor];
  4773. }
  4774. $pos = array_values(array_filter($pos, function ($po) {
  4775. if (!is_array($po)) {
  4776. return false;
  4777. }
  4778. $mr = $po['mod_rq'] ?? null;
  4779. if ($mr === null || $mr === '') {
  4780. return true;
  4781. }
  4782. $mrs = trim((string)$mr);
  4783. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  4784. }));
  4785. if ($pos === []) {
  4786. $pos = [$anchor];
  4787. }
  4788. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  4789. if ($rows === []) {
  4790. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  4791. }
  4792. return $rows;
  4793. }
  4794. /**
  4795. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  4796. *
  4797. * @param array<int, array<string, mixed>> $mergeRows
  4798. * @return array<int, array<string, mixed>>
  4799. */
  4800. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  4801. {
  4802. $list = array_values($mergeRows);
  4803. $n = count($list);
  4804. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  4805. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  4806. $mergeSame = $n > 1 && $orderKey0 !== '';
  4807. if ($mergeSame) {
  4808. foreach ($list as $rr) {
  4809. if (!is_array($rr)) {
  4810. $mergeSame = false;
  4811. break;
  4812. }
  4813. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  4814. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  4815. $mergeSame = false;
  4816. break;
  4817. }
  4818. }
  4819. }
  4820. $out = [];
  4821. foreach ($list as $idx => $r) {
  4822. if (!is_array($r)) {
  4823. continue;
  4824. }
  4825. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  4826. if (is_scalar($qty)) {
  4827. $qty = trim((string)$qty);
  4828. } else {
  4829. $qty = '';
  4830. }
  4831. if ($qty === '') {
  4832. $gzl = $r['NGZL'] ?? '';
  4833. if (is_scalar($gzl)) {
  4834. $qty = trim((string)$gzl);
  4835. }
  4836. }
  4837. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  4838. $sid = $this->extractScydgyRowId($r);
  4839. $out[] = [
  4840. 'seq' => $idx + 1,
  4841. 'scydgy_id' => $sid,
  4842. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  4843. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  4844. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  4845. 'CDW' => trim((string)($r['CDW'] ?? '')),
  4846. 'NGZL' => $r['NGZL'] ?? '',
  4847. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  4848. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  4849. 'CDF' => trim((string)($r['CDF'] ?? '')),
  4850. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  4851. 'show_order_cells' => !$mergeSame || $idx === 0,
  4852. 'order_rowspan' => $mergeSame ? $n : 1,
  4853. ];
  4854. }
  4855. return $out;
  4856. }
  4857. /**
  4858. * 解析金额/数量(去千分位等非数字字符)
  4859. */
  4860. protected function parseProcuremenMoneyNumber($value): ?float
  4861. {
  4862. if ($value === null || $value === '') {
  4863. return null;
  4864. }
  4865. if (is_numeric($value)) {
  4866. return (float)$value;
  4867. }
  4868. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  4869. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  4870. }
  4871. protected function formatProcuremenMoneyDisplay(?float $amount): string
  4872. {
  4873. if ($amount === null) {
  4874. return '';
  4875. }
  4876. return (string)(int)round($amount);
  4877. }
  4878. /**
  4879. * 列表/详情展示:工作量为 0 时显示空
  4880. */
  4881. protected function formatProcuremenWorkloadDisplay($value): string
  4882. {
  4883. if ($value === null || $value === '') {
  4884. return '';
  4885. }
  4886. $s = trim((string)$value);
  4887. if ($s === '') {
  4888. return '';
  4889. }
  4890. if (is_numeric($s) && (float)$s == 0) {
  4891. return '';
  4892. }
  4893. return $s;
  4894. }
  4895. /**
  4896. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  4897. */
  4898. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  4899. {
  4900. foreach ($details as $d) {
  4901. if (!is_array($d)) {
  4902. continue;
  4903. }
  4904. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  4905. $cn = trim((string)($d['company_name'] ?? ''));
  4906. if ($cn !== '') {
  4907. return $cn;
  4908. }
  4909. }
  4910. }
  4911. return trim((string)($main['pick_company_name'] ?? ''));
  4912. }
  4913. /**
  4914. * 详情报价小计:单价 × 本工序本次数量
  4915. */
  4916. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  4917. {
  4918. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  4919. if ($unit === null) {
  4920. return null;
  4921. }
  4922. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  4923. if ($qty === null || $qty <= 0) {
  4924. return null;
  4925. }
  4926. return $unit * $qty;
  4927. }
  4928. /**
  4929. * 详情页:工序小计 + 供应商分组报价与总计
  4930. *
  4931. * @param array<int, array<string, mixed>> $mergeRows
  4932. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  4933. * @return array{
  4934. * process_rows: array,
  4935. * supplier_groups: array,
  4936. * order_total_text: string,
  4937. * order_total_has: bool,
  4938. * selected_company: string
  4939. * }
  4940. */
  4941. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  4942. {
  4943. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  4944. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  4945. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  4946. $qtyBySid = [];
  4947. $gymcBySid = [];
  4948. $orderedSids = [];
  4949. foreach ($mergeRows as $mr) {
  4950. if (!is_array($mr)) {
  4951. continue;
  4952. }
  4953. $sid = $this->extractScydgyRowId($mr);
  4954. if ($sid > 0) {
  4955. $orderedSids[] = $sid;
  4956. }
  4957. $qty = trim((string)($mr['This_quantity'] ?? ''));
  4958. if ($qty === '') {
  4959. $qty = trim((string)($mr['NGZL'] ?? ''));
  4960. }
  4961. $qtyBySid[$sid] = $qty;
  4962. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  4963. }
  4964. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  4965. $detailByCompanySid = [];
  4966. foreach ($details as $d) {
  4967. if (!is_array($d)) {
  4968. continue;
  4969. }
  4970. $cn = trim((string)($d['company_name'] ?? ''));
  4971. $sid = (int)($d['scydgy_id'] ?? 0);
  4972. if ($cn === '' || $sid === 0) {
  4973. continue;
  4974. }
  4975. if (!isset($detailByCompanySid[$cn])) {
  4976. $detailByCompanySid[$cn] = [];
  4977. }
  4978. $detailByCompanySid[$cn][$sid] = $d;
  4979. }
  4980. $supplierGroups = [];
  4981. foreach ($detailByCompanySid as $cn => $bySid) {
  4982. $lines = [];
  4983. $groupTotal = 0.0;
  4984. $groupHas = false;
  4985. $groupVoid = true;
  4986. $usedSids = [];
  4987. $appendLine = function (int $sid, array $d) use (
  4988. &$lines,
  4989. &$groupTotal,
  4990. &$groupHas,
  4991. &$groupVoid,
  4992. $qtyBySid,
  4993. $gymcBySid,
  4994. $quoteVisible
  4995. ) {
  4996. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  4997. if (!$isVoid) {
  4998. $groupVoid = false;
  4999. }
  5000. $qtyStr = $qtyBySid[$sid] ?? '';
  5001. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5002. $am = trim((string)($d['amount'] ?? ''));
  5003. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5004. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5005. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5006. $sub = null;
  5007. if (!$isVoid && $amountNum !== null) {
  5008. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5009. }
  5010. $ct = $this->resolveDetailSupplierOperTime($d);
  5011. $line = [
  5012. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5013. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am,
  5014. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5015. 'delivery_ymd' => $deliveryYmd,
  5016. 'amount_filled' => $amountFilled,
  5017. 'delivery_filled' => $deliveryFilled,
  5018. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5019. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5020. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5021. 'is_void' => $isVoid,
  5022. 'oper_time_text' => $ct,
  5023. ];
  5024. if (!$quoteVisible && !$isVoid) {
  5025. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5026. } elseif ($sub !== null) {
  5027. $groupTotal += $sub;
  5028. $groupHas = true;
  5029. }
  5030. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5031. };
  5032. foreach ($orderedSids as $sid) {
  5033. if (!isset($bySid[$sid])) {
  5034. continue;
  5035. }
  5036. $usedSids[$sid] = true;
  5037. $appendLine($sid, $bySid[$sid]);
  5038. }
  5039. foreach ($bySid as $sid => $d) {
  5040. if (isset($usedSids[$sid])) {
  5041. continue;
  5042. }
  5043. $appendLine((int)$sid, $d);
  5044. }
  5045. $firstDetail = null;
  5046. foreach ($bySid as $d) {
  5047. if (is_array($d)) {
  5048. $firstDetail = $d;
  5049. break;
  5050. }
  5051. }
  5052. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5053. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5054. if ($username === '' && $ph !== '') {
  5055. $username = $this->resolveCustomerContactName($ph, $cn);
  5056. }
  5057. $lineCount = count($lines);
  5058. $supplierGroups[] = [
  5059. 'company_name' => $cn,
  5060. 'username' => $username,
  5061. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5062. 'phone' => $ph,
  5063. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5064. 'is_void' => $groupVoid,
  5065. 'lines' => $lines,
  5066. 'line_count' => $lineCount,
  5067. 'display_rowspan'=> $lineCount + ($lineCount > 0 ? 1 : 0),
  5068. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5069. 'has_total' => $lineCount > 0,
  5070. ];
  5071. }
  5072. usort($supplierGroups, function ($a, $b) {
  5073. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5074. return ($a['is_void'] ?? false) ? 1 : -1;
  5075. }
  5076. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5077. return ($a['is_selected'] ?? false) ? -1 : 1;
  5078. }
  5079. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5080. });
  5081. return [
  5082. 'process_rows' => $processRows,
  5083. 'supplier_groups' => $supplierGroups,
  5084. 'order_total_text' => '',
  5085. 'order_total_has' => false,
  5086. 'selected_company' => $selectedCompany,
  5087. ];
  5088. }
  5089. /**
  5090. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5091. */
  5092. protected function buildProcessLinesPlain(array $mergeRows): string
  5093. {
  5094. $lines = [];
  5095. $i = 1;
  5096. foreach ($mergeRows as $r) {
  5097. if (!is_array($r)) {
  5098. continue;
  5099. }
  5100. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5101. $dw = trim((string)($r['CDW'] ?? ''));
  5102. $gzl = trim((string)($r['NGZL'] ?? ''));
  5103. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5104. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5105. if ($dw !== '') {
  5106. $parts[] = '单位:' . $dw;
  5107. }
  5108. if ($gzl !== '') {
  5109. $parts[] = '工作量:' . $gzl;
  5110. }
  5111. if ($qty !== '') {
  5112. $parts[] = '本次数量:' . $qty;
  5113. }
  5114. $lines[] = implode(' ', $parts);
  5115. $i++;
  5116. }
  5117. return implode("\n", $lines);
  5118. }
  5119. /**
  5120. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5121. *
  5122. * @return array<string, string>
  5123. */
  5124. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5125. {
  5126. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5127. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5128. }
  5129. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5130. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5131. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5132. $cyjmc = '';
  5133. foreach ($mergeRows as $mr) {
  5134. if (!is_array($mr)) {
  5135. continue;
  5136. }
  5137. if ($ccydh === '') {
  5138. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5139. }
  5140. if ($cyjmc === '') {
  5141. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5142. }
  5143. }
  5144. if ($pos !== []) {
  5145. $firstPo = $pos[0];
  5146. if (is_array($firstPo)) {
  5147. if ($ccydh === '') {
  5148. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5149. }
  5150. if ($cyjmc === '') {
  5151. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5152. }
  5153. }
  5154. }
  5155. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5156. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5157. if (is_array($any)) {
  5158. if ($ccydh === '') {
  5159. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5160. }
  5161. if ($cyjmc === '') {
  5162. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5163. }
  5164. }
  5165. }
  5166. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5167. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5168. $cgymc = '';
  5169. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5170. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5171. }
  5172. return [
  5173. 'ccydh' => $ccydh,
  5174. 'cyjmc' => $cyjmc,
  5175. 'cgymc' => $cgymc,
  5176. 'process_lines' => $processLines,
  5177. 'process_lines_html' => '',
  5178. ];
  5179. }
  5180. /**
  5181. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5182. */
  5183. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5184. {
  5185. $lines = [];
  5186. if ($ccydh !== '') {
  5187. $lines[] = '订单号:' . $ccydh;
  5188. }
  5189. if ($cyjmc !== '') {
  5190. $lines[] = '印件名称:' . $cyjmc;
  5191. }
  5192. if ($processPlain !== '') {
  5193. $lines[] = $processPlain;
  5194. }
  5195. return implode("\n", $lines);
  5196. }
  5197. /**
  5198. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5199. *
  5200. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5201. */
  5202. protected function buildPlatformLinksPlain(array $detailLinks): string
  5203. {
  5204. $lines = [];
  5205. $i = 1;
  5206. foreach ($detailLinks as $lk) {
  5207. if (!is_array($lk)) {
  5208. continue;
  5209. }
  5210. $url = trim((string)($lk['url'] ?? ''));
  5211. if ($url === '') {
  5212. continue;
  5213. }
  5214. $label = trim((string)($lk['cgymc'] ?? ''));
  5215. if ($label === '') {
  5216. $label = '工序' . $i;
  5217. }
  5218. $lines[] = $label . ':' . $url;
  5219. $i++;
  5220. }
  5221. return implode("\n", $lines);
  5222. }
  5223. /**
  5224. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5225. *
  5226. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5227. */
  5228. protected function buildPlatformLinksHtml(array $detailLinks): string
  5229. {
  5230. $parts = [];
  5231. $i = 1;
  5232. foreach ($detailLinks as $lk) {
  5233. if (!is_array($lk)) {
  5234. continue;
  5235. }
  5236. $url = trim((string)($lk['url'] ?? ''));
  5237. if ($url === '') {
  5238. continue;
  5239. }
  5240. $label = trim((string)($lk['cgymc'] ?? ''));
  5241. if ($label === '') {
  5242. $label = '工序' . $i;
  5243. }
  5244. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5245. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5246. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5247. $i++;
  5248. }
  5249. return implode("<br>\n", $parts);
  5250. }
  5251. /**
  5252. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5253. *
  5254. * @return array<string, mixed>
  5255. */
  5256. protected function loadMailerConfig(): array
  5257. {
  5258. try {
  5259. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5260. } catch (\Throwable $e) {
  5261. $cfg = [];
  5262. }
  5263. return is_array($cfg) ? $cfg : [];
  5264. }
  5265. protected function loadNotifyTemplateRow(string $scene): ?array
  5266. {
  5267. try {
  5268. $row = Db::table('purchase_sms_template')
  5269. ->where('scene', $scene)
  5270. ->where(function ($q) {
  5271. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5272. })
  5273. ->order('id', 'asc')
  5274. ->find();
  5275. } catch (\Throwable $e) {
  5276. return null;
  5277. }
  5278. if (!is_array($row) || $row === []) {
  5279. return null;
  5280. }
  5281. return [
  5282. 'title' => trim((string)($row['title'] ?? '')),
  5283. 'content' => trim((string)($row['content'] ?? '')),
  5284. ];
  5285. }
  5286. /**
  5287. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5288. */
  5289. protected function buildProcessLinesHtml(array $mergeRows): string
  5290. {
  5291. if (count($mergeRows) <= 1) {
  5292. $r = $mergeRows[0] ?? [];
  5293. if (!is_array($r)) {
  5294. return '';
  5295. }
  5296. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5297. $dw = trim((string)($r['CDW'] ?? ''));
  5298. $gzl = trim((string)($r['NGZL'] ?? ''));
  5299. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5300. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5301. if ($dw !== '') {
  5302. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5303. }
  5304. if ($gzl !== '') {
  5305. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5306. }
  5307. if ($qty !== '') {
  5308. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5309. }
  5310. return $html;
  5311. }
  5312. $rows = '';
  5313. $i = 1;
  5314. foreach ($mergeRows as $r) {
  5315. if (!is_array($r)) {
  5316. continue;
  5317. }
  5318. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5319. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5320. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5321. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5322. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5323. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5324. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5325. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5326. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5327. $i++;
  5328. }
  5329. if ($rows === '') {
  5330. return '';
  5331. }
  5332. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5333. . '<thead><tr style="background:#f5f5f5;">'
  5334. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5335. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5336. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5337. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5338. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5339. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5340. }
  5341. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  5342. {
  5343. $sysRq = trim($sysRq);
  5344. if ($sysRq === '') {
  5345. if ($required) {
  5346. $this->error('请选择截止时间');
  5347. }
  5348. return '';
  5349. }
  5350. $ts = strtotime($sysRq);
  5351. if ($ts === false || $ts <= 0) {
  5352. $this->error('截止时间格式无效');
  5353. }
  5354. return date('Y-m-d H:i:s', $ts);
  5355. }
  5356. protected function formatProcuremenSysRqForInput($sysRq): string
  5357. {
  5358. $sr = trim((string)$sysRq);
  5359. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  5360. return '';
  5361. }
  5362. $ts = strtotime($sr);
  5363. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  5364. }
  5365. protected function formatProcuremenSysRqForDisplay($sysRq): string
  5366. {
  5367. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  5368. if ($sr === '') {
  5369. return '—';
  5370. }
  5371. $ts = strtotime($sr);
  5372. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  5373. }
  5374. /**
  5375. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  5376. *
  5377. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  5378. * @return array{ccydh?:string,pos:array,merge_rows:array}
  5379. */
  5380. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  5381. {
  5382. return $bundle;
  5383. }
  5384. /**
  5385. * 写入/更新 purchase_order(单道工序行)
  5386. */
  5387. protected function upsertPurchaseOrderFromRow(
  5388. array $row,
  5389. string $sysRqDb,
  5390. $wflowStatus = null,
  5391. ?string $pickTime = null,
  5392. ?array $exists = null
  5393. ): void {
  5394. $ids = $this->extractScydgyRowId($row);
  5395. if (!$this->isValidScydgyRowId($ids)) {
  5396. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  5397. }
  5398. if ($exists === null) {
  5399. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5400. }
  5401. $data = [
  5402. 'scydgy_id' => $ids,
  5403. 'CCYDH' => $row['CCYDH'] ?? null,
  5404. 'CYJMC' => $row['CYJMC'] ?? null,
  5405. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5406. 'CDXMC' => $row['CDXMC'] ?? null,
  5407. 'CGYBH' => $row['CGYBH'] ?? null,
  5408. 'CGYMC' => $row['CGYMC'] ?? null,
  5409. 'CDW' => $row['CDW'] ?? null,
  5410. 'NGZL' => $row['NGZL'] ?? null,
  5411. 'CDF' => $row['CDF'] ?? null,
  5412. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5413. 'MBZ' => $row['MBZ'] ?? null,
  5414. 'bwjg' => $row['bwjg'] ?? null,
  5415. 'iStatus' => $row['iStatus'] ?? null,
  5416. 'dStamp' => $row['dStamp'] ?? null,
  5417. 'dputrecord' => $row['dputrecord'] ?? null,
  5418. 'cywyxm' => $row['cywyxm'] ?? null,
  5419. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5420. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5421. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5422. 'sys_rq' => $sysRqDb,
  5423. ];
  5424. if ($wflowStatus !== null && $wflowStatus !== '') {
  5425. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  5426. }
  5427. if ($pickTime !== null && $pickTime !== '') {
  5428. $data['pick_time'] = $pickTime;
  5429. $data['pick_company_name'] = '';
  5430. }
  5431. if ($exists) {
  5432. $upd = $data;
  5433. unset($upd['scydgy_id']);
  5434. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5435. } else {
  5436. $data['createtime'] = date('Y-m-d H:i:s');
  5437. Db::table('purchase_order')->insert($data);
  5438. }
  5439. }
  5440. /**
  5441. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  5442. *
  5443. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  5444. */
  5445. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  5446. {
  5447. $toDb = function ($value) {
  5448. if ($value === null) {
  5449. return null;
  5450. }
  5451. if (is_scalar($value)) {
  5452. return $value;
  5453. }
  5454. return json_encode($value, JSON_UNESCAPED_UNICODE);
  5455. };
  5456. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5457. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5458. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5459. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  5460. if ($username === '') {
  5461. $username = $this->resolveCustomerContactName($phone, $companyName);
  5462. }
  5463. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5464. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  5465. }
  5466. if ($phone === '') {
  5467. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  5468. }
  5469. $detailLinks = [];
  5470. foreach ($mergeRows as $row) {
  5471. if (!is_array($row)) {
  5472. continue;
  5473. }
  5474. $sid = $this->extractScydgyRowId($row);
  5475. $detailId = 0;
  5476. if ($skipExisting) {
  5477. try {
  5478. $existsQuery = Db::table('purchase_order_detail')
  5479. ->where('scydgy_id', $sid)
  5480. ->where('company_name', $companyName);
  5481. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  5482. $exists = $existsQuery->find();
  5483. } catch (\Throwable $e) {
  5484. $exists = null;
  5485. }
  5486. if (is_array($exists)) {
  5487. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  5488. }
  5489. }
  5490. if ($detailId <= 0) {
  5491. $one = [
  5492. 'scydgy_id' => $toDb($sid),
  5493. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  5494. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  5495. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  5496. 'username' => $username !== '' ? $username : null,
  5497. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  5498. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  5499. 'createtime' => date('Y-m-d H:i:s'),
  5500. 'status' => ProcuremenStatus::POD_UNPICKED,
  5501. 'status_name' => '未提交',
  5502. ];
  5503. Db::table('purchase_order_detail')->insert($one);
  5504. $detailId = (int)Db::getLastInsID();
  5505. }
  5506. $mprocUrl = '';
  5507. if ($buildMobileLinks && $detailId > 0) {
  5508. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  5509. }
  5510. $detailLinks[] = [
  5511. 'detail_id' => $detailId,
  5512. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  5513. 'url' => $mprocUrl,
  5514. ];
  5515. }
  5516. return $detailLinks;
  5517. }
  5518. /**
  5519. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  5520. * @return array<string, mixed>
  5521. */
  5522. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  5523. {
  5524. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5525. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5526. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5527. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  5528. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  5529. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  5530. $isMerge = !empty($ctx['is_merge']);
  5531. $contactName = trim((string)($c['username'] ?? ''));
  5532. if ($contactName === '') {
  5533. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  5534. }
  5535. $notifyVars = [
  5536. 'company_name' => $companyName,
  5537. 'contact_name' => $contactName,
  5538. 'phone' => $phone,
  5539. 'email' => $toEmail,
  5540. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  5541. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  5542. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  5543. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  5544. 'deadline' => (string)($ctx['deadline'] ?? ''),
  5545. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  5546. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  5547. 'platform_url' => $platformUrl,
  5548. 'platform_links' => $platformLinksPlain,
  5549. 'platform_links_html' => $platformLinksHtml,
  5550. ];
  5551. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  5552. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  5553. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5554. return [
  5555. 'company_name' => $companyName,
  5556. 'phone' => $phone,
  5557. 'email' => $toEmail,
  5558. 'sms_content' => $smsContent,
  5559. 'mail_plain' => $mailPlain,
  5560. 'mail_body' => $mailBody,
  5561. 'notify_vars' => $notifyVars,
  5562. 'detail_links' => $detailLinks,
  5563. ];
  5564. }
  5565. /**
  5566. * @param array<string, mixed> $chosen
  5567. * @param array<int, array<string, mixed>> $mergeRows
  5568. * @param array{ccydh:string, pos:array} $bundle
  5569. */
  5570. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  5571. {
  5572. if (!$sendSms && !$sendEmail) {
  5573. return;
  5574. }
  5575. $companyName = trim((string)($chosen['name'] ?? ''));
  5576. $phone = trim((string)($chosen['phone'] ?? ''));
  5577. $toEmail = trim((string)($chosen['email'] ?? ''));
  5578. if ($companyName === '') {
  5579. throw new \Exception('供应商名称无效');
  5580. }
  5581. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  5582. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  5583. }
  5584. if ($sendSms && $phone === '') {
  5585. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  5586. }
  5587. $sids = [];
  5588. foreach ($mergeRows as $mr) {
  5589. if (!is_array($mr)) {
  5590. continue;
  5591. }
  5592. $sid = $this->extractScydgyRowId($mr);
  5593. if ($this->isValidScydgyRowId($sid)) {
  5594. $sids[$sid] = true;
  5595. }
  5596. }
  5597. if ($sids === []) {
  5598. throw new \Exception('未找到工序行,无法发送通知');
  5599. }
  5600. $sysRqNotify = '';
  5601. $pos = $bundle['pos'] ?? [];
  5602. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5603. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  5604. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  5605. $ts = strtotime($sr);
  5606. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  5607. }
  5608. }
  5609. try {
  5610. $detailsQuery = Db::table('purchase_order_detail')
  5611. ->where('scydgy_id', 'in', array_keys($sids))
  5612. ->where('company_name', $companyName);
  5613. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5614. $details = $detailsQuery->order('id', 'asc')->select();
  5615. } catch (\Throwable $e) {
  5616. $details = [];
  5617. }
  5618. if (!is_array($details) || $details === []) {
  5619. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  5620. try {
  5621. $detailsQuery = Db::table('purchase_order_detail')
  5622. ->where('scydgy_id', 'in', array_keys($sids))
  5623. ->where('company_name', $companyName);
  5624. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5625. $details = $detailsQuery->order('id', 'asc')->select();
  5626. } catch (\Throwable $e) {
  5627. $details = [];
  5628. }
  5629. }
  5630. if (!is_array($details) || $details === []) {
  5631. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  5632. }
  5633. $detailLinks = [];
  5634. foreach ($details as $d) {
  5635. if (!is_array($d)) {
  5636. continue;
  5637. }
  5638. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  5639. if ($detailId <= 0) {
  5640. continue;
  5641. }
  5642. $sid = (int)($d['scydgy_id'] ?? 0);
  5643. $gymc = '';
  5644. foreach ($mergeRows as $mr) {
  5645. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  5646. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5647. break;
  5648. }
  5649. }
  5650. $detailLinks[] = [
  5651. 'detail_id' => $detailId,
  5652. 'cgymc' => $gymc,
  5653. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  5654. ];
  5655. }
  5656. if ($detailLinks === []) {
  5657. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  5658. }
  5659. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  5660. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  5661. $notifyBundle['email_log_scene'] = $emailLogScene;
  5662. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  5663. $poIdLog = 0;
  5664. $pos = $bundle['pos'] ?? [];
  5665. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5666. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5667. }
  5668. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  5669. if ($sendEmail) {
  5670. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  5671. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  5672. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  5673. }
  5674. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  5675. $mailConfig = $this->loadMailerConfig();
  5676. if (!$this->isProcuremenNotifyDryRun()) {
  5677. if (empty($mailConfig['host'])) {
  5678. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  5679. }
  5680. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  5681. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  5682. }
  5683. }
  5684. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  5685. }
  5686. if ($sendSms) {
  5687. $this->issueSendSupplierSms($notifyBundle);
  5688. }
  5689. }
  5690. /**
  5691. * @param array<int, array<string, mixed>> $quoteGroups
  5692. * @return array<int, array<string, mixed>>
  5693. */
  5694. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  5695. {
  5696. $names = [];
  5697. if (is_string($companiesJson) && $companiesJson !== '') {
  5698. $decoded = json_decode($companiesJson, true);
  5699. if (is_array($decoded)) {
  5700. foreach ($decoded as $nm) {
  5701. $nm = trim((string)$nm);
  5702. if ($nm !== '') {
  5703. $names[] = $nm;
  5704. }
  5705. }
  5706. }
  5707. }
  5708. $names = array_values(array_unique($names));
  5709. if ($names === [] && $selectedCompany !== '') {
  5710. $names = [$selectedCompany];
  5711. }
  5712. if ($names === []) {
  5713. return $quoteGroups;
  5714. }
  5715. $targets = [];
  5716. foreach ($quoteGroups as $g) {
  5717. if (!is_array($g)) {
  5718. continue;
  5719. }
  5720. $cn = trim((string)($g['name'] ?? ''));
  5721. if ($cn !== '' && in_array($cn, $names, true)) {
  5722. $targets[] = $g;
  5723. }
  5724. }
  5725. return $targets;
  5726. }
  5727. /**
  5728. * @return array{pos:array, merge_rows:array, bundle:array}
  5729. */
  5730. protected function loadAuditResendBundle(string $scydgyId): array
  5731. {
  5732. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5733. $pos = $bundle['pos'];
  5734. $mergeRows = $bundle['merge_rows'];
  5735. if ($pos === [] || $mergeRows === []) {
  5736. $this->error('该订单不在待确认供应商状态');
  5737. }
  5738. $sysRqDb = '';
  5739. if (isset($pos[0]) && is_array($pos[0])) {
  5740. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  5741. }
  5742. foreach ($pos as $i => $poRow) {
  5743. if (is_array($pos[$i]) && $sysRqDb !== '') {
  5744. $pos[$i]['sys_rq'] = $sysRqDb;
  5745. }
  5746. }
  5747. $bundle['pos'] = $pos;
  5748. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  5749. }
  5750. /**
  5751. * @param array<int, array<string, mixed>> $targets
  5752. */
  5753. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  5754. {
  5755. if ($targets === []) {
  5756. $this->error('未找到可通知的供应商');
  5757. }
  5758. $notifyErrors = [];
  5759. try {
  5760. $this->notifyDryRunPreview = [];
  5761. foreach ($targets as $g) {
  5762. if (!is_array($g)) {
  5763. continue;
  5764. }
  5765. $cname = trim((string)($g['name'] ?? ''));
  5766. if ($cname === '') {
  5767. continue;
  5768. }
  5769. $chosen = [
  5770. 'name' => $cname,
  5771. 'company_name' => $cname,
  5772. 'email' => trim((string)($g['email'] ?? '')),
  5773. 'phone' => trim((string)($g['phone'] ?? '')),
  5774. 'username' => trim((string)($g['username'] ?? '')),
  5775. ];
  5776. try {
  5777. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  5778. } catch (\Throwable $e) {
  5779. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5780. }
  5781. }
  5782. } catch (\Throwable $e) {
  5783. $this->error('通知发送失败:' . $e->getMessage());
  5784. }
  5785. if ($notifyErrors !== []) {
  5786. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5787. }
  5788. if ($this->isProcuremenNotifyDryRun()) {
  5789. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  5790. 'notify_dry_run' => true,
  5791. 'notify_preview' => $this->notifyDryRunPreview,
  5792. ]);
  5793. }
  5794. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  5795. }
  5796. /**
  5797. * 协助下发 — 发送短信(一家供应商)
  5798. *
  5799. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  5800. */
  5801. protected function issueSendSupplierSms(array $bundle): void
  5802. {
  5803. $companyName = (string)($bundle['company_name'] ?? '');
  5804. $phone = (string)($bundle['phone'] ?? '');
  5805. $smsContent = (string)($bundle['sms_content'] ?? '');
  5806. $this->logIssueNotifyDebug('短信', [
  5807. 'company' => $companyName,
  5808. 'phone' => $phone,
  5809. 'sms_content' => $smsContent,
  5810. ]);
  5811. if ($this->isProcuremenNotifyDryRun()) {
  5812. $this->recordNotifyDryRunPreview([
  5813. 'scene' => 'issue_sms',
  5814. 'company_name' => $companyName,
  5815. 'phone' => $phone,
  5816. 'sms_content' => $smsContent,
  5817. ]);
  5818. return;
  5819. }
  5820. $this->smsbao($phone, $smsContent);
  5821. }
  5822. /**
  5823. * 协助下发 — 发送邮件(一家供应商)
  5824. *
  5825. * @param array<string, mixed> $bundle
  5826. * @param array<string, mixed> $mailConfig
  5827. */
  5828. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  5829. {
  5830. $companyName = (string)($bundle['company_name'] ?? '');
  5831. $toEmail = (string)($bundle['email'] ?? '');
  5832. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  5833. $mailBody = (string)($bundle['mail_body'] ?? '');
  5834. $this->logIssueNotifyDebug('邮件', [
  5835. 'company' => $companyName,
  5836. 'email' => $toEmail,
  5837. 'mail_subject' => $mailSubject,
  5838. 'mail_body' => $mailPlain,
  5839. ]);
  5840. if ($this->isProcuremenNotifyDryRun()) {
  5841. $this->recordNotifyDryRunPreview([
  5842. 'scene' => 'issue_email',
  5843. 'company_name' => $companyName,
  5844. 'email' => $toEmail,
  5845. 'mail_subject' => $mailSubject,
  5846. 'mail_body' => $mailPlain,
  5847. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  5848. 'notify_vars' => $bundle['notify_vars'] ?? [],
  5849. 'detail_links' => $bundle['detail_links'] ?? [],
  5850. ]);
  5851. return;
  5852. }
  5853. $mail = new PHPMailer(true);
  5854. $mail->isSMTP();
  5855. $mail->Host = $mailConfig['host'];
  5856. $mail->SMTPAuth = true;
  5857. $mail->Username = $mailConfig['addr'];
  5858. $mail->Password = $mailConfig['pass'];
  5859. $mail->SMTPSecure = $mailConfig['security'];
  5860. $mail->Port = $mailConfig['port'];
  5861. $mail->CharSet = $mailConfig['charset'];
  5862. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  5863. $mail->addAddress($toEmail, $companyName);
  5864. $mail->isHTML(true);
  5865. $mail->Subject = $mailSubject;
  5866. $mail->Body = $mailBody;
  5867. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  5868. $sendOk = true;
  5869. $failReason = '';
  5870. try {
  5871. $mail->send();
  5872. } catch (\Throwable $e) {
  5873. $sendOk = false;
  5874. $failReason = $e->getMessage();
  5875. $this->persistEmailSendLog([
  5876. 'from_email' => $fromEmail,
  5877. 'to_email' => $toEmail,
  5878. 'send_time' => date('Y-m-d H:i:s'),
  5879. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  5880. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  5881. 'company_name' => $companyName,
  5882. 'mail_subject' => $mailSubject,
  5883. 'status' => 0,
  5884. 'fail_reason' => $failReason,
  5885. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  5886. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  5887. ]);
  5888. throw $e;
  5889. }
  5890. $this->persistEmailSendLog([
  5891. 'from_email' => $fromEmail,
  5892. 'to_email' => $toEmail,
  5893. 'send_time' => date('Y-m-d H:i:s'),
  5894. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  5895. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  5896. 'company_name' => $companyName,
  5897. 'mail_subject' => $mailSubject,
  5898. 'status' => 1,
  5899. 'fail_reason' => '',
  5900. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  5901. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  5902. ]);
  5903. }
  5904. /**
  5905. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  5906. *
  5907. * @param array<int, array<string, mixed>> $mergeRows
  5908. * @return array<string, mixed>
  5909. */
  5910. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  5911. {
  5912. $head = $mergeRows[0] ?? [];
  5913. $isMerge = count($mergeRows) > 1;
  5914. return [
  5915. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  5916. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  5917. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  5918. 'is_merge' => $isMerge,
  5919. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  5920. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  5921. 'deadline' => $sysRqNotify,
  5922. ];
  5923. }
  5924. /**
  5925. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  5926. *
  5927. * @param array<string, mixed> $data
  5928. */
  5929. protected function logIssueNotifyDebug(string $type, array $data): void
  5930. {
  5931. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  5932. return;
  5933. }
  5934. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  5935. }
  5936. protected function ensurePurchaseEmailSendLogTableOnce(): void
  5937. {
  5938. try {
  5939. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  5940. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  5941. return;
  5942. } catch (\Throwable $e) {
  5943. }
  5944. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  5945. if (is_file($sqlFile)) {
  5946. $sql = file_get_contents($sqlFile);
  5947. if (is_string($sql) && $sql !== '') {
  5948. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  5949. $stmt = trim($stmt);
  5950. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  5951. continue;
  5952. }
  5953. try {
  5954. Db::execute($stmt);
  5955. } catch (\Throwable $ignore) {
  5956. }
  5957. }
  5958. }
  5959. }
  5960. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  5961. }
  5962. /**
  5963. * @param array<string, mixed> $row
  5964. */
  5965. protected function persistEmailSendLog(array $row): void
  5966. {
  5967. try {
  5968. $this->ensurePurchaseEmailSendLogTableOnce();
  5969. } catch (\Throwable $e) {
  5970. return;
  5971. }
  5972. list($adminId, $adminName) = $this->GetUseName();
  5973. $cut = function ($s, $max) {
  5974. $s = (string)$s;
  5975. if (function_exists('mb_substr')) {
  5976. return mb_substr($s, 0, $max, 'UTF-8');
  5977. }
  5978. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  5979. };
  5980. $data = [
  5981. 'from_email' => $cut($row['from_email'] ?? '', 128),
  5982. 'to_email' => $cut($row['to_email'] ?? '', 128),
  5983. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  5984. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  5985. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  5986. 'company_name' => $cut($row['company_name'] ?? '', 128),
  5987. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  5988. 'status' => !empty($row['status']) ? 1 : 0,
  5989. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  5990. 'admin_id' => (int)$adminId,
  5991. 'admin_name' => $cut($adminName, 64),
  5992. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  5993. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  5994. 'createtime' => date('Y-m-d H:i:s'),
  5995. ];
  5996. try {
  5997. Db::table('purchase_email_send_log')->insert($data);
  5998. } catch (\Throwable $e) {
  5999. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6000. }
  6001. }
  6002. protected function formatEmailLogSceneText(string $scene): string
  6003. {
  6004. $map = [
  6005. 'pick_issue' => '初选下发',
  6006. 'audit_resend' => '确认页重发',
  6007. ];
  6008. return $map[$scene] ?? $scene;
  6009. }
  6010. /**
  6011. * 邮件发送日志列表
  6012. */
  6013. public function emailLog()
  6014. {
  6015. $this->relationSearch = false;
  6016. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6017. $this->request->filter(['strip_tags', 'trim']);
  6018. $bakModel = $this->model;
  6019. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6020. if ($this->request->isAjax()) {
  6021. $this->ensurePurchaseEmailSendLogTableOnce();
  6022. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6023. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6024. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6025. $list = $this->model
  6026. ->where($where)
  6027. ->order($sortField, $orderDir)
  6028. ->paginate($limit);
  6029. $rows = [];
  6030. foreach ($list->items() as $item) {
  6031. $row = is_array($item) ? $item : $item->toArray();
  6032. $scene = trim((string)($row['scene'] ?? ''));
  6033. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6034. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6035. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6036. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6037. $rows[] = $row;
  6038. }
  6039. $this->model = $bakModel;
  6040. return json(['total' => $list->total(), 'rows' => $rows]);
  6041. }
  6042. $this->model = $bakModel;
  6043. return $this->view->fetch('procuremen/emaillog');
  6044. }
  6045. /**
  6046. * 协助下发弹窗(选多家供应商并通知)
  6047. */
  6048. public function pickReview()
  6049. {
  6050. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6051. $this->error(__('You have no permission'));
  6052. }
  6053. if ($this->request->isPost()) {
  6054. $this->error('请使用弹窗内「确认下发」提交');
  6055. }
  6056. $this->view->assign('pickMode', 1);
  6057. return $this->view->fetch('procuremen/review');
  6058. }
  6059. /**
  6060. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6061. */
  6062. public function add()
  6063. {
  6064. if ($this->request->isPost()) {
  6065. $params = $this->request->post('row/a');
  6066. if (!is_array($params)) {
  6067. $this->error(__('Parameter %s can not be empty', ''));
  6068. }
  6069. [, $adminName] = $this->GetUseName();
  6070. $params['cywyxm'] = $adminName;
  6071. try {
  6072. $sid = $this->saveManualPickOrder($params);
  6073. } catch (\InvalidArgumentException $e) {
  6074. $this->error($e->getMessage());
  6075. } catch (\Throwable $e) {
  6076. $this->error($e->getMessage());
  6077. }
  6078. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6079. }
  6080. [, $adminName] = $this->GetUseName();
  6081. $this->view->assign('adminNickname', $adminName);
  6082. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6083. return $this->view->fetch();
  6084. }
  6085. /**
  6086. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6087. */
  6088. public function rfqlist()
  6089. {
  6090. $this->relationSearch = false;
  6091. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6092. $this->request->filter(['strip_tags', 'trim']);
  6093. if ($this->request->isAjax()) {
  6094. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6095. $limit = max(10, min(500, (int)$limit));
  6096. $applyFilters = function ($query) use ($where) {
  6097. $query->where('scydgy_id', '<', 0);
  6098. $query->whereRaw(
  6099. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6100. );
  6101. if (!$this->auth->isSuperAdmin()) {
  6102. [, $adminName] = $this->GetUseName();
  6103. $query->where('cywyxm', $adminName);
  6104. }
  6105. if (!empty($where)) {
  6106. $query->where($where);
  6107. }
  6108. };
  6109. $countQuery = Db::table('purchase_order');
  6110. $applyFilters($countQuery);
  6111. $total = (int)$countQuery->count();
  6112. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6113. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6114. $listQuery = Db::table('purchase_order');
  6115. $applyFilters($listQuery);
  6116. $rows = $listQuery
  6117. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6118. ->order($sortField, $orderDir)
  6119. ->limit($offset, $limit)
  6120. ->select();
  6121. if (!is_array($rows)) {
  6122. $rows = [];
  6123. }
  6124. $out = [];
  6125. foreach ($rows as $r) {
  6126. if (!is_array($r)) {
  6127. continue;
  6128. }
  6129. $sid = (int)($r['scydgy_id'] ?? 0);
  6130. if ($sid >= 0) {
  6131. continue;
  6132. }
  6133. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6134. if ($createdText === '') {
  6135. $createdText = trim((string)($r['dStamp'] ?? ''));
  6136. }
  6137. $out[] = [
  6138. 'id' => (int)($r['id'] ?? 0),
  6139. 'scydgy_id' => $sid,
  6140. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6141. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6142. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6143. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6144. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6145. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6146. 'createtime' => $r['createtime'] ?? null,
  6147. 'createtime_text' => $createdText,
  6148. ];
  6149. }
  6150. return json(['total' => $total, 'rows' => $out]);
  6151. }
  6152. [, $adminName] = $this->GetUseName();
  6153. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6154. $this->view->assign('adminNickname', $adminName);
  6155. return $this->view->fetch('procuremen/rfqlist');
  6156. }
  6157. /**
  6158. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6159. */
  6160. public function rfqlistDetails()
  6161. {
  6162. return $this->details();
  6163. }
  6164. /**
  6165. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6166. */
  6167. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6168. {
  6169. if ($scydgyId >= 0) {
  6170. return;
  6171. }
  6172. try {
  6173. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6174. } catch (\Throwable $e) {
  6175. $po = null;
  6176. }
  6177. if (!is_array($po)) {
  6178. $this->error('订单不存在');
  6179. }
  6180. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6181. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6182. $this->error('订单不存在');
  6183. }
  6184. if ($this->auth->isSuperAdmin()) {
  6185. return;
  6186. }
  6187. [, $adminName] = $this->GetUseName();
  6188. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6189. if ($cywy !== '' && $cywy === $adminName) {
  6190. return;
  6191. }
  6192. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6193. try {
  6194. if ($this->auth->check($rule)) {
  6195. return;
  6196. }
  6197. } catch (\Throwable $e) {
  6198. }
  6199. }
  6200. $this->error('无权查看该订单');
  6201. }
  6202. /**
  6203. * 手工新增协助工序进度文案
  6204. */
  6205. protected function formatProcuremenRfqProgressText(array $row): string
  6206. {
  6207. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6208. return ProcuremenStatus::PO_COMPLETED;
  6209. }
  6210. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6211. return '待采购确认';
  6212. }
  6213. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6214. return '待确认供应商';
  6215. }
  6216. $sid = (int)($row['scydgy_id'] ?? 0);
  6217. if ($sid < 0) {
  6218. try {
  6219. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6220. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6221. $detCnt = (int)$detCntQuery->count();
  6222. if ($detCnt > 0) {
  6223. return '已下发待确认';
  6224. }
  6225. } catch (\Throwable $e) {
  6226. }
  6227. }
  6228. return '待协助下发';
  6229. }
  6230. /**
  6231. * 协助初选列表 — 批量软删除
  6232. */
  6233. public function pickDelete()
  6234. {
  6235. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6236. $this->error(__('Invalid parameters'));
  6237. }
  6238. if (!$this->procuremenCanPickDelete()) {
  6239. $this->error(__('You have no permission'));
  6240. }
  6241. $rowsRaw = $this->request->post('rows_json', '[]');
  6242. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6243. if (!is_array($rows) || $rows === []) {
  6244. $this->error('请至少勾选一条工序');
  6245. }
  6246. $done = 0;
  6247. Db::startTrans();
  6248. try {
  6249. foreach ($rows as $row) {
  6250. if (!is_array($row)) {
  6251. continue;
  6252. }
  6253. $this->softDeleteProcuremenPickRow($row);
  6254. $done++;
  6255. }
  6256. if ($done < 1) {
  6257. throw new \Exception('没有可删除的工序');
  6258. }
  6259. Db::commit();
  6260. } catch (\InvalidArgumentException $e) {
  6261. Db::rollback();
  6262. $this->error($e->getMessage());
  6263. } catch (\Throwable $e) {
  6264. Db::rollback();
  6265. $this->error($e->getMessage());
  6266. }
  6267. $this->pickHiddenScydgySetCache = null;
  6268. $this->success('已删除 ' . $done . ' 条工序');
  6269. }
  6270. /**
  6271. * 下发 — 手工新增工序(弹窗)
  6272. */
  6273. public function pickAdd()
  6274. {
  6275. if ($this->request->isPost()) {
  6276. $params = $this->request->post('row/a');
  6277. if (!is_array($params)) {
  6278. $this->error(__('Parameter %s can not be empty', ''));
  6279. }
  6280. try {
  6281. $sid = $this->saveManualPickOrder($params);
  6282. } catch (\InvalidArgumentException $e) {
  6283. $this->error($e->getMessage());
  6284. } catch (\Throwable $e) {
  6285. $this->error($e->getMessage());
  6286. }
  6287. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6288. }
  6289. return $this->view->fetch('procuremen/pick_add');
  6290. }
  6291. /**
  6292. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  6293. */
  6294. public function pickSubmit()
  6295. {
  6296. if (!$this->request->isPost()) {
  6297. $this->error(__('Invalid parameters'));
  6298. }
  6299. // ---------- 接口订单数据 ----------
  6300. $rowJson = $this->request->post('row_json', '');
  6301. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  6302. $companiesJson = $this->request->post('companies_json', '[]');
  6303. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  6304. $companies = json_decode($companiesJson, true);
  6305. if (!is_array($companies)) {
  6306. $this->error('供应商数据无效');
  6307. }
  6308. $issueCompanies = $this->normalizePickCompanies($companies);
  6309. if ($issueCompanies === []) {
  6310. $this->error('请至少选择一家合作供应商');
  6311. }
  6312. $issueNameLabels = [];
  6313. foreach ($issueCompanies as $pc) {
  6314. $issueNameLabels[] = $pc['name'];
  6315. }
  6316. $issueNamesSummary = implode('、', $issueNameLabels);
  6317. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  6318. if ($sysRq === '') {
  6319. $this->error('请选择截止时间');
  6320. }
  6321. $sysRqTs = strtotime($sysRq);
  6322. if ($sysRqTs === false || $sysRqTs <= 0) {
  6323. $this->error('截止时间格式无效');
  6324. }
  6325. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  6326. $isMerge = count($mergeRows) > 1;
  6327. $ccydhLog = '';
  6328. foreach ($mergeRows as $row) {
  6329. if (!is_array($row)) {
  6330. continue;
  6331. }
  6332. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  6333. if ($ccydhLog !== '') {
  6334. break;
  6335. }
  6336. }
  6337. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  6338. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6339. $logMsg = '下发' . $orderPart . $procPart
  6340. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  6341. $issueTime = date('Y-m-d H:i:s');
  6342. $logSidList = [];
  6343. foreach ($mergeRows as $row) {
  6344. if (!is_array($row)) {
  6345. continue;
  6346. }
  6347. $sid = $this->extractScydgyRowId($row);
  6348. if ($this->isValidScydgyRowId($sid)) {
  6349. $logSidList[$sid] = true;
  6350. }
  6351. }
  6352. $existingBySid = [];
  6353. if ($logSidList !== []) {
  6354. try {
  6355. $existingRows = Db::table('purchase_order')
  6356. ->where('scydgy_id', 'in', array_keys($logSidList))
  6357. ->select();
  6358. if (is_array($existingRows)) {
  6359. foreach ($existingRows as $poRow) {
  6360. if (!is_array($poRow)) {
  6361. continue;
  6362. }
  6363. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6364. if ($this->isValidScydgyRowId($sid)) {
  6365. $existingBySid[$sid] = $poRow;
  6366. }
  6367. }
  6368. }
  6369. } catch (\Throwable $e) {
  6370. $existingBySid = [];
  6371. }
  6372. }
  6373. Db::startTrans();
  6374. try {
  6375. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  6376. foreach ($mergeRows as $row) {
  6377. if (!is_array($row)) {
  6378. continue;
  6379. }
  6380. $sid = $this->extractScydgyRowId($row);
  6381. $this->upsertPurchaseOrderFromRow(
  6382. $row,
  6383. $sysRqDb,
  6384. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6385. $issueTime,
  6386. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  6387. );
  6388. }
  6389. foreach ($issueCompanies as $c) {
  6390. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  6391. }
  6392. Db::commit();
  6393. } catch (\Throwable $e) {
  6394. Db::rollback();
  6395. $this->error($e->getMessage());
  6396. }
  6397. $poIdBySid = [];
  6398. if ($logSidList !== []) {
  6399. try {
  6400. $poIdBySid = Db::table('purchase_order')
  6401. ->where('scydgy_id', 'in', array_keys($logSidList))
  6402. ->column('id', 'scydgy_id');
  6403. } catch (\Throwable $e) {
  6404. $poIdBySid = [];
  6405. }
  6406. }
  6407. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  6408. if ($logSidList !== []) {
  6409. list($adminId, $adminName) = $this->GetUseName();
  6410. $cut = function ($s, $max) {
  6411. if (function_exists('mb_substr')) {
  6412. return mb_substr($s, 0, $max, 'UTF-8');
  6413. }
  6414. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6415. };
  6416. $logRows = [];
  6417. $seenLogSid = [];
  6418. foreach ($mergeRows as $row) {
  6419. if (!is_array($row)) {
  6420. continue;
  6421. }
  6422. $ids = $this->extractScydgyRowId($row);
  6423. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  6424. continue;
  6425. }
  6426. $seenLogSid[$ids] = true;
  6427. $poIdLog = null;
  6428. if (isset($poIdBySid[$ids])) {
  6429. $tid = (int)$poIdBySid[$ids];
  6430. $poIdLog = $tid > 0 ? $tid : null;
  6431. }
  6432. $logRows[] = [
  6433. 'scydgy_id' => $ids,
  6434. 'purchase_order_id' => $poIdLog,
  6435. 'admin_id' => $adminId,
  6436. 'admin_name' => $cut($adminName, 64),
  6437. 'action' => $cut('issue_submit', 64),
  6438. 'content' => $cut($logMsg, 1000),
  6439. 'createtime' => ProcuremenTime::nowDateTime(),
  6440. ];
  6441. }
  6442. if ($logRows !== []) {
  6443. try {
  6444. Db::table('purchase_order_oper_log')->insertAll($logRows);
  6445. } catch (\Throwable $e) {
  6446. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  6447. }
  6448. }
  6449. }
  6450. $notifyErrors = [];
  6451. $posNotify = [];
  6452. if ($logSidList !== []) {
  6453. try {
  6454. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  6455. } catch (\Throwable $e) {
  6456. $posNotify = [];
  6457. }
  6458. }
  6459. if (!is_array($posNotify)) {
  6460. $posNotify = [];
  6461. }
  6462. foreach ($posNotify as $i => $prow) {
  6463. if (is_array($posNotify[$i])) {
  6464. $posNotify[$i]['sys_rq'] = $sysRqDb;
  6465. }
  6466. }
  6467. $ccydhPick = '';
  6468. foreach ($mergeRows as $row) {
  6469. if (!is_array($row)) {
  6470. continue;
  6471. }
  6472. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  6473. if ($ccydhPick !== '') {
  6474. break;
  6475. }
  6476. }
  6477. $notifyBundleBase = [
  6478. 'ccydh' => $ccydhPick,
  6479. 'pos' => $posNotify,
  6480. 'merge_rows' => $mergeRows,
  6481. ];
  6482. try {
  6483. $this->notifyDryRunPreview = [];
  6484. foreach ($issueCompanies as $c) {
  6485. if (!is_array($c)) {
  6486. continue;
  6487. }
  6488. $cname = trim((string)($c['name'] ?? ''));
  6489. if ($cname === '') {
  6490. continue;
  6491. }
  6492. try {
  6493. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  6494. } catch (\Throwable $e) {
  6495. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6496. }
  6497. }
  6498. } catch (\Throwable $e) {
  6499. $this->error('通知发送失败:' . $e->getMessage());
  6500. }
  6501. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  6502. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6503. }
  6504. if ($this->isProcuremenNotifyDryRun()) {
  6505. $this->success('【演练模式】已保存并生成通知预览', '', [
  6506. 'notify_dry_run' => true,
  6507. 'notify_preview' => $this->notifyDryRunPreview,
  6508. ]);
  6509. }
  6510. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  6511. }
  6512. /**
  6513. * 确认供应商弹窗
  6514. */
  6515. public function auditIssue()
  6516. {
  6517. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6518. if (is_array($ids)) {
  6519. $ids = isset($ids[0]) ? $ids[0] : '';
  6520. }
  6521. $ids = trim((string)$ids);
  6522. if ($ids === '') {
  6523. $this->error(__('Invalid parameters'));
  6524. }
  6525. if ($this->request->isPost()) {
  6526. $this->error('请使用弹窗内「确认」提交');
  6527. }
  6528. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  6529. $pos = $bundle['pos'];
  6530. if ($pos === []) {
  6531. $this->error('该订单不在待确认供应商状态');
  6532. }
  6533. $po = $pos[0];
  6534. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6535. if ($quoteGroups === []) {
  6536. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  6537. }
  6538. $pickedName = '';
  6539. foreach ($pos as $poRow) {
  6540. if (!is_array($poRow)) {
  6541. continue;
  6542. }
  6543. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6544. if ($pn !== '') {
  6545. $pickedName = $pn;
  6546. break;
  6547. }
  6548. }
  6549. $this->view->assign('po', $po);
  6550. $this->view->assign('scydgyId', $ids);
  6551. $this->view->assign('orderCcydh', $bundle['ccydh']);
  6552. $mergeRows = $bundle['merge_rows'];
  6553. $this->view->assign('processRows', $mergeRows);
  6554. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  6555. $this->view->assign('processCount', count($mergeRows));
  6556. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  6557. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  6558. $this->view->assign('pickedCompanyName', $pickedName);
  6559. $this->view->assign('sysRq', $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null));
  6560. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  6561. $this->view->assign('quoteDeadlineReached', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  6562. return $this->view->fetch('procuremen/audit_issue');
  6563. }
  6564. /**
  6565. * 开标双重验证 — 可选验证人列表
  6566. */
  6567. public function bidOpenUsers()
  6568. {
  6569. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6570. $this->error('无权限');
  6571. }
  6572. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  6573. if ($scydgyId !== '') {
  6574. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6575. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6576. $this->success('已完成开标验证', null, [
  6577. 'verified' => 1,
  6578. 'users' => [],
  6579. ]);
  6580. }
  6581. }
  6582. $this->success('', null, [
  6583. 'verified' => 0,
  6584. 'users' => $this->listBidOpenVerifierCandidates(),
  6585. ]);
  6586. }
  6587. /**
  6588. * 开标双重验证 — 向指定管理员发送短信验证码
  6589. */
  6590. public function bidOpenSendCode()
  6591. {
  6592. if (!$this->request->isPost()) {
  6593. $this->error(__('Invalid parameters'));
  6594. }
  6595. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6596. $this->error('无权限');
  6597. }
  6598. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6599. $adminId = (int)$this->request->post('admin_id', 0);
  6600. if ($scydgyId === '' || $adminId <= 0) {
  6601. $this->error('参数无效');
  6602. }
  6603. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6604. if ($bundle['pos'] === []) {
  6605. $this->error('该订单不在待确认供应商状态');
  6606. }
  6607. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6608. $this->success('已完成开标验证,无需重复发送');
  6609. }
  6610. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6611. if ($ccydh === '') {
  6612. $this->error('订单号无效');
  6613. }
  6614. $admin = $this->loadBidOpenAdminUser($adminId);
  6615. if ($admin === null) {
  6616. $this->error('验证人无效或未绑定手机号');
  6617. }
  6618. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  6619. $cd = max(30, min(120, $cd));
  6620. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  6621. $this->error('发送过于频繁,请稍后再试');
  6622. }
  6623. $code = (string)random_int(100000, 999999);
  6624. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  6625. $ttl = max(60, min(600, $ttl));
  6626. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  6627. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  6628. try {
  6629. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  6630. } catch (\Throwable $e) {
  6631. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  6632. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  6633. $this->error($e->getMessage());
  6634. }
  6635. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  6636. }
  6637. /**
  6638. * 开标双重验证 — 两人验证码校验并记录
  6639. */
  6640. public function bidOpenVerify()
  6641. {
  6642. if (!$this->request->isPost()) {
  6643. $this->error(__('Invalid parameters'));
  6644. }
  6645. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6646. $this->error('无权限');
  6647. }
  6648. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6649. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  6650. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  6651. $code1 = trim((string)$this->request->post('code1', ''));
  6652. $code2 = trim((string)$this->request->post('code2', ''));
  6653. if ($scydgyId === '') {
  6654. $this->error('参数无效');
  6655. }
  6656. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  6657. $this->error('请选择两位验证人');
  6658. }
  6659. if ($verifier1Id === $verifier2Id) {
  6660. $this->error('两位验证人不能相同');
  6661. }
  6662. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  6663. $this->error('请输入6位短信验证码');
  6664. }
  6665. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6666. if ($bundle['pos'] === []) {
  6667. $this->error('该订单不在待确认供应商状态');
  6668. }
  6669. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6670. if ($ccydh === '') {
  6671. $this->error('订单号无效');
  6672. }
  6673. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6674. $this->success('已完成开标验证');
  6675. }
  6676. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  6677. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  6678. if ($verifier1 === null || $verifier2 === null) {
  6679. $this->error('验证人无效或未绑定手机号');
  6680. }
  6681. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  6682. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  6683. }
  6684. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  6685. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  6686. }
  6687. try {
  6688. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  6689. } catch (\Throwable $e) {
  6690. $this->error($e->getMessage());
  6691. }
  6692. $this->success('开标验证成功,可查看供应商报价与交货日期');
  6693. }
  6694. /**
  6695. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  6696. */
  6697. public function auditSubmit()
  6698. {
  6699. if (!$this->request->isPost()) {
  6700. $this->error(__('Invalid parameters'));
  6701. }
  6702. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6703. if ($scydgyId === '') {
  6704. $this->error('参数无效');
  6705. }
  6706. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6707. $pos = $bundle['pos'];
  6708. $mergeRows = $bundle['merge_rows'];
  6709. if ($pos === [] || $mergeRows === []) {
  6710. $this->error('该订单不在待确认供应商状态');
  6711. }
  6712. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6713. if ($quoteGroups === []) {
  6714. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  6715. }
  6716. $companyName = trim((string)$this->request->post('selected_company', ''));
  6717. if ($companyName === '') {
  6718. $this->error('请选择一家供应商');
  6719. }
  6720. $matched = null;
  6721. foreach ($quoteGroups as $g) {
  6722. if (!is_array($g)) {
  6723. continue;
  6724. }
  6725. if (trim((string)($g['name'] ?? '')) === $companyName) {
  6726. $matched = $g;
  6727. break;
  6728. }
  6729. }
  6730. if ($matched === null) {
  6731. $this->error('所选供应商不在本单报价列表中');
  6732. }
  6733. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6734. if ($sysRqDb === '') {
  6735. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  6736. } else {
  6737. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true);
  6738. }
  6739. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6740. $this->error('请先完成开标双重验证后再确认供应商');
  6741. }
  6742. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  6743. $procCnt = count($mergeRows);
  6744. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6745. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  6746. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  6747. Db::startTrans();
  6748. try {
  6749. foreach ($pos as $poRow) {
  6750. if (!is_array($poRow)) {
  6751. continue;
  6752. }
  6753. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6754. if (!$this->isValidScydgyRowId($sid)) {
  6755. continue;
  6756. }
  6757. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  6758. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  6759. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6760. 'pick_company_name' => $companyName,
  6761. 'sys_rq' => $sysRqDb,
  6762. ]);
  6763. }
  6764. Db::commit();
  6765. } catch (\Throwable $e) {
  6766. Db::rollback();
  6767. $this->error($e->getMessage());
  6768. }
  6769. foreach ($pos as $poRow) {
  6770. if (!is_array($poRow)) {
  6771. continue;
  6772. }
  6773. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6774. if (!$this->isValidScydgyRowId($sid)) {
  6775. continue;
  6776. }
  6777. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6778. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6779. }
  6780. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  6781. }
  6782. /**
  6783. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  6784. */
  6785. public function auditResendSms()
  6786. {
  6787. if (!$this->request->isPost()) {
  6788. $this->error(__('Invalid parameters'));
  6789. }
  6790. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6791. if ($scydgyId === '') {
  6792. $this->error('参数无效');
  6793. }
  6794. $loaded = $this->loadAuditResendBundle($scydgyId);
  6795. $mergeRows = $loaded['merge_rows'];
  6796. $bundle = $loaded['bundle'];
  6797. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  6798. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6799. if ($quoteGroups === []) {
  6800. $this->error('暂无可通知的供应商');
  6801. }
  6802. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  6803. $companiesJson = (string)$this->request->post('companies_json', '');
  6804. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  6805. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  6806. }
  6807. /**
  6808. * 确认供应商 — 二次发送邮件(可选单家/批量)
  6809. */
  6810. public function auditResendEmail()
  6811. {
  6812. if (!$this->request->isPost()) {
  6813. $this->error(__('Invalid parameters'));
  6814. }
  6815. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6816. if ($scydgyId === '') {
  6817. $this->error('参数无效');
  6818. }
  6819. $loaded = $this->loadAuditResendBundle($scydgyId);
  6820. $mergeRows = $loaded['merge_rows'];
  6821. $bundle = $loaded['bundle'];
  6822. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  6823. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6824. if ($quoteGroups === []) {
  6825. $this->error('暂无可通知的供应商');
  6826. }
  6827. $companiesJson = (string)$this->request->post('companies_json', '');
  6828. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  6829. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  6830. if ($companiesJson === '' && $selectedCompany === '') {
  6831. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  6832. }
  6833. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  6834. }
  6835. /**
  6836. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  6837. *
  6838. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  6839. * @return array<int, true> 已处理的 scydgy_id 集合
  6840. */
  6841. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  6842. {
  6843. $pos = $bundle['pos'] ?? [];
  6844. if (!is_array($pos) || $pos === []) {
  6845. return [];
  6846. }
  6847. $sids = [];
  6848. foreach ($pos as $poRow) {
  6849. if (!is_array($poRow)) {
  6850. continue;
  6851. }
  6852. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6853. if ($this->isValidScydgyRowId($sid)) {
  6854. $sids[$sid] = true;
  6855. }
  6856. }
  6857. if ($sids === []) {
  6858. return [];
  6859. }
  6860. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  6861. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  6862. $suffix = trim((string)$logSuffix, ',, ');
  6863. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  6864. $logMsg .= ':从历史存证退回协助初选';
  6865. } else {
  6866. $logMsg .= ':退回协助初选';
  6867. }
  6868. Db::table('purchase_order')
  6869. ->where('scydgy_id', 'in', array_keys($sids))
  6870. ->update([
  6871. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  6872. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6873. 'pick_company_name' => '',
  6874. 'pick_time' => null,
  6875. 'sys_rq' => null,
  6876. 'mod_rq' => null,
  6877. ]);
  6878. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  6879. foreach (array_keys($sids) as $sid) {
  6880. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  6881. }
  6882. return $sids;
  6883. }
  6884. /**
  6885. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  6886. *
  6887. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6888. */
  6889. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  6890. {
  6891. $scydgyId = trim($scydgyId);
  6892. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6893. if ($scydgyId === '') {
  6894. return $empty;
  6895. }
  6896. try {
  6897. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6898. } catch (\Throwable $e) {
  6899. $anchor = null;
  6900. }
  6901. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  6902. return $empty;
  6903. }
  6904. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6905. if ($ccydh === '') {
  6906. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6907. }
  6908. try {
  6909. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6910. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  6911. $pos = $query->order('scydgy_id', 'asc')->select();
  6912. } catch (\Throwable $e) {
  6913. $pos = [$anchor];
  6914. }
  6915. if (!is_array($pos) || $pos === []) {
  6916. $pos = [$anchor];
  6917. }
  6918. return [
  6919. 'ccydh' => $ccydh,
  6920. 'pos' => $pos,
  6921. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6922. ];
  6923. }
  6924. protected function purchaseOrderRowIsCompleted(array $po): bool
  6925. {
  6926. $st = $po['status'] ?? null;
  6927. if ($st === 1 || $st === '1') {
  6928. return true;
  6929. }
  6930. if (is_string($st) && trim($st) === '1') {
  6931. return true;
  6932. }
  6933. return is_numeric($st) && (int)$st === 1;
  6934. }
  6935. /**
  6936. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  6937. */
  6938. public function auditAbandon()
  6939. {
  6940. if (!$this->request->isPost()) {
  6941. $this->error(__('Invalid parameters'));
  6942. }
  6943. $anchorIds = [];
  6944. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  6945. if ($batchRaw !== '') {
  6946. $decoded = json_decode($batchRaw, true);
  6947. if (is_array($decoded)) {
  6948. foreach ($decoded as $id) {
  6949. $s = trim((string)$id);
  6950. if ($s !== '') {
  6951. $anchorIds[] = $s;
  6952. }
  6953. }
  6954. }
  6955. }
  6956. if ($anchorIds === []) {
  6957. $single = trim((string)$this->request->post('scydgy_id', ''));
  6958. if ($single !== '') {
  6959. $anchorIds[] = $single;
  6960. }
  6961. }
  6962. if ($anchorIds === []) {
  6963. $this->error('请至少选择一条订单');
  6964. }
  6965. $processedCcydh = [];
  6966. $doneOrders = 0;
  6967. $allSids = [];
  6968. Db::startTrans();
  6969. try {
  6970. foreach ($anchorIds as $anchorId) {
  6971. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  6972. if (($bundle['pos'] ?? []) === []) {
  6973. continue;
  6974. }
  6975. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6976. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  6977. if (isset($processedCcydh[$dedupeKey])) {
  6978. continue;
  6979. }
  6980. $processedCcydh[$dedupeKey] = true;
  6981. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  6982. if ($sids === []) {
  6983. continue;
  6984. }
  6985. $doneOrders++;
  6986. foreach (array_keys($sids) as $sid) {
  6987. $allSids[(int)$sid] = true;
  6988. }
  6989. }
  6990. if ($doneOrders < 1) {
  6991. throw new \Exception('所选订单均不在待确认供应商状态');
  6992. }
  6993. Db::commit();
  6994. } catch (\Throwable $e) {
  6995. Db::rollback();
  6996. $this->error($e->getMessage());
  6997. }
  6998. $this->pickHiddenScydgySetCache = null;
  6999. $msg = $doneOrders > 1
  7000. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7001. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7002. $this->success($msg);
  7003. }
  7004. /**
  7005. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7006. */
  7007. public function archiveAbandon()
  7008. {
  7009. if (!$this->request->isPost()) {
  7010. $this->error(__('Invalid parameters'));
  7011. }
  7012. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7013. $this->error(__('You have no permission'));
  7014. }
  7015. $anchorIds = [];
  7016. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7017. if ($batchRaw !== '') {
  7018. $decoded = json_decode($batchRaw, true);
  7019. if (is_array($decoded)) {
  7020. foreach ($decoded as $id) {
  7021. $s = trim((string)$id);
  7022. if ($s !== '') {
  7023. $anchorIds[] = $s;
  7024. }
  7025. }
  7026. }
  7027. }
  7028. if ($anchorIds === []) {
  7029. $single = trim((string)$this->request->post('scydgy_id', ''));
  7030. if ($single !== '') {
  7031. $anchorIds[] = $single;
  7032. }
  7033. }
  7034. if ($anchorIds === []) {
  7035. $this->error('请至少选择一条订单');
  7036. }
  7037. $processedCcydh = [];
  7038. $doneOrders = 0;
  7039. Db::startTrans();
  7040. try {
  7041. foreach ($anchorIds as $anchorId) {
  7042. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7043. if (($bundle['pos'] ?? []) === []) {
  7044. continue;
  7045. }
  7046. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7047. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7048. if (isset($processedCcydh[$dedupeKey])) {
  7049. continue;
  7050. }
  7051. $processedCcydh[$dedupeKey] = true;
  7052. $sids = $this->abandonOrderBundleToPick(
  7053. $bundle,
  7054. 'archive_abandon',
  7055. ',从历史存证退回协助初选'
  7056. );
  7057. if ($sids === []) {
  7058. continue;
  7059. }
  7060. $doneOrders++;
  7061. }
  7062. if ($doneOrders < 1) {
  7063. throw new \Exception('所选订单均不是已完结状态');
  7064. }
  7065. Db::commit();
  7066. } catch (\Throwable $e) {
  7067. Db::rollback();
  7068. $this->error($e->getMessage());
  7069. }
  7070. $this->pickHiddenScydgySetCache = null;
  7071. $msg = $doneOrders > 1
  7072. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  7073. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7074. $this->success($msg);
  7075. }
  7076. /**
  7077. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  7078. */
  7079. public function purchaseApprovalReject()
  7080. {
  7081. if (!$this->request->isPost() || !$this->request->isAjax()) {
  7082. $this->error(__('Invalid parameters'));
  7083. }
  7084. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  7085. $this->error(__('You have no permission'));
  7086. }
  7087. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  7088. $decoded = json_decode($batchRaw, true);
  7089. if (!is_array($decoded) || $decoded === []) {
  7090. $this->error('提交数据无效');
  7091. }
  7092. $done = 0;
  7093. Db::startTrans();
  7094. try {
  7095. foreach ($decoded as $item) {
  7096. if (!is_array($item)) {
  7097. continue;
  7098. }
  7099. $sid = (int)($item['scydgy_id'] ?? 0);
  7100. if (!$this->isValidScydgyRowId($sid)) {
  7101. continue;
  7102. }
  7103. $this->runPurchaseApprovalRejectForSid($sid);
  7104. $done++;
  7105. }
  7106. if ($done < 1) {
  7107. throw new \Exception('所选订单均不在待审批状态');
  7108. }
  7109. Db::commit();
  7110. } catch (\Throwable $e) {
  7111. Db::rollback();
  7112. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  7113. }
  7114. $this->pickHiddenScydgySetCache = null;
  7115. $this->success('已驳回并退回「协助审批下发」');
  7116. }
  7117. /**
  7118. * @throws \Exception
  7119. */
  7120. protected function runPurchaseApprovalRejectForSid(int $sid): void
  7121. {
  7122. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  7123. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  7124. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  7125. $allIds = $this->purchaseOrderDetail($sid);
  7126. if ($allIds === []) {
  7127. throw new \Exception('未找到下发明细');
  7128. }
  7129. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7130. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7131. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7132. 'pick_company_name' => '',
  7133. ]);
  7134. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  7135. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  7136. $poId = 0;
  7137. try {
  7138. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  7139. if (is_array($po)) {
  7140. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7141. }
  7142. } catch (\Throwable $e) {
  7143. }
  7144. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  7145. }
  7146. /**
  7147. * 审核弹窗(旧入口,POST 已关闭)
  7148. */
  7149. public function review()
  7150. {
  7151. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  7152. $this->error(__('You have no permission'));
  7153. }
  7154. if ($this->request->isPost()) {
  7155. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  7156. }
  7157. $this->view->assign('pickMode', 0);
  7158. return $this->view->fetch('procuremen/review');
  7159. }
  7160. /**
  7161. * 审核弹窗获取公司列表
  7162. */
  7163. public function reviewCompanies()
  7164. {
  7165. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review'])) {
  7166. $this->error(__('You have no permission'));
  7167. }
  7168. if (!$this->request->isAjax()) {
  7169. $this->error(__('Invalid parameters'));
  7170. }
  7171. $list = [];
  7172. try {
  7173. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  7174. $rows = Db::table('customer')
  7175. ->where(function ($q) {
  7176. $q->where('status', 1)
  7177. ->whereOr('status', '1')
  7178. ->whereOr('status', '')
  7179. ->whereNull('status');
  7180. })
  7181. ->order('id', 'desc')
  7182. ->select();
  7183. } catch (\Throwable $e) {
  7184. $this->success('', '', []);
  7185. return;
  7186. }
  7187. if (!is_array($rows)) {
  7188. $this->success('', '', []);
  7189. return;
  7190. }
  7191. $detailColCandidates = [
  7192. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  7193. 'company_detail', 'company_desc', 'address',
  7194. ];
  7195. foreach ($rows as $row) {
  7196. if (!is_array($row)) {
  7197. continue;
  7198. }
  7199. $norm = [];
  7200. foreach ($row as $k => $v) {
  7201. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7202. }
  7203. $row = $norm;
  7204. $st = $row['status'] ?? '';
  7205. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7206. continue;
  7207. }
  7208. $payload = $this->buildCustomerContactPayloadFromRow($row);
  7209. if ($payload === null) {
  7210. continue;
  7211. }
  7212. $detail = '';
  7213. foreach ($detailColCandidates as $dk) {
  7214. if (!isset($row[$dk])) {
  7215. continue;
  7216. }
  7217. $dv = trim((string)$row[$dk]);
  7218. if ($dv !== '') {
  7219. $detail = $dv;
  7220. break;
  7221. }
  7222. }
  7223. $payload['detail'] = $detail;
  7224. $list[] = $this->maskSupplierContactFields($payload);
  7225. }
  7226. $this->success('', '', $list);
  7227. }
  7228. /**
  7229. * 采购确认-下发明细弹窗:
  7230. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  7231. */
  7232. public function outward_detail()
  7233. {
  7234. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7235. if (is_array($ids)) {
  7236. $ids = isset($ids[0]) ? $ids[0] : '';
  7237. }
  7238. $ids = trim((string)$ids);
  7239. if ($ids === '') {
  7240. $this->error(__('Invalid parameters'));
  7241. }
  7242. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  7243. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  7244. $wffTab = 'all';
  7245. }
  7246. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  7247. $purchaseOrderId = 0;
  7248. $po = null;
  7249. try {
  7250. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7251. if (is_array($po)) {
  7252. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7253. }
  7254. } catch (\Throwable $e) {
  7255. $purchaseOrderId = 0;
  7256. $po = null;
  7257. }
  7258. if (!$isPurchaseConfirm && is_array($po)) {
  7259. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  7260. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  7261. $isPurchaseConfirm = true;
  7262. }
  7263. }
  7264. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  7265. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7266. $confirmProcessCount = 1;
  7267. $confirmPickGroups = [];
  7268. $processDisplayRows = [];
  7269. $allDetailsBySid = [];
  7270. $requiredSidList = [];
  7271. $sidList = [$ids];
  7272. if ($isPurchaseConfirm) {
  7273. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  7274. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  7275. if ($mergeRows !== []) {
  7276. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7277. }
  7278. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  7279. if ($confirmBundle['pos'] !== []) {
  7280. $sidList = [];
  7281. foreach ($confirmBundle['pos'] as $poRow) {
  7282. if (!is_array($poRow)) {
  7283. continue;
  7284. }
  7285. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7286. if (!$this->isValidScydgyRowId($sid)) {
  7287. continue;
  7288. }
  7289. $sidList[] = (string)$sid;
  7290. $requiredSidList[] = $sid;
  7291. }
  7292. }
  7293. if ($sidList === []) {
  7294. $sidList = [$ids];
  7295. $requiredSidList = [(int)$ids];
  7296. }
  7297. $confirmProcessCount = max(1, count($requiredSidList));
  7298. if (is_array($po) && $purchaseOrderId <= 0) {
  7299. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7300. }
  7301. }
  7302. $rows = [];
  7303. try {
  7304. if (count($sidList) === 1) {
  7305. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  7306. } else {
  7307. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  7308. }
  7309. } catch (\Throwable $e) {
  7310. $rows = [];
  7311. }
  7312. if ($isPurchaseConfirm) {
  7313. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  7314. }
  7315. foreach ($rows as &$r) {
  7316. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  7317. $r['id'] = $r['ID'];
  7318. }
  7319. if (isset($r['createtime'])) {
  7320. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  7321. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  7322. } else {
  7323. $r['createtime_text'] = (string)$r['createtime'];
  7324. }
  7325. } else {
  7326. $r['createtime_text'] = '';
  7327. }
  7328. if (is_array($r)) {
  7329. $r = $this->maskSupplierContactFields($r);
  7330. }
  7331. }
  7332. unset($r);
  7333. $pickedCompanyName = '';
  7334. if ($isPurchaseConfirm) {
  7335. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  7336. if (!is_array($poRow)) {
  7337. continue;
  7338. }
  7339. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7340. if ($pn !== '') {
  7341. $pickedCompanyName = $pn;
  7342. break;
  7343. }
  7344. }
  7345. }
  7346. $this->view->assign('rows', $rows ?: []);
  7347. $this->view->assign('rowCount', count($rows ?: []));
  7348. $this->view->assign('scydgyId', $ids);
  7349. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  7350. $this->view->assign('headTitle', $headTitle);
  7351. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  7352. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  7353. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  7354. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  7355. $this->view->assign('processDisplayRows', $processDisplayRows);
  7356. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  7357. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  7358. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  7359. $sysRqDisplay = '—';
  7360. if ($isPurchaseConfirm) {
  7361. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  7362. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  7363. );
  7364. }
  7365. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  7366. $this->view->assign('sysRq', $isPurchaseConfirm
  7367. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  7368. : '');
  7369. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  7370. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  7371. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  7372. if ($isPurchaseConfirm) {
  7373. return $this->view->fetch();
  7374. }
  7375. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  7376. $this->view->engine->layout(false);
  7377. try {
  7378. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  7379. $this->view->assign('dialogBody', $bodyHtml);
  7380. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  7381. } finally {
  7382. if ($restoreLayout) {
  7383. $this->view->engine->layout($restoreLayout);
  7384. }
  7385. }
  7386. }
  7387. /**
  7388. * 月度导出记录表(不存在时自动创建)
  7389. */
  7390. protected function ensurePurchaseMonthExportLogTable(): void
  7391. {
  7392. try {
  7393. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  7394. } catch (\Throwable $e) {
  7395. Db::execute(
  7396. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  7397. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  7398. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  7399. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  7400. `admin_name` varchar(64) NOT NULL DEFAULT '',
  7401. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  7402. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  7403. `createtime` int(10) unsigned DEFAULT NULL,
  7404. PRIMARY KEY (`id`),
  7405. KEY `idx_ym` (`ym`),
  7406. KEY `idx_ct` (`createtime`)
  7407. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  7408. );
  7409. }
  7410. }
  7411. /**
  7412. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  7413. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  7414. */
  7415. public function export_month_outward()
  7416. {
  7417. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  7418. $this->error(__('You have no permission'));
  7419. }
  7420. $this->request->filter(['strip_tags', 'trim']);
  7421. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  7422. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  7423. $ym = date('Y-m');
  7424. }
  7425. $dbRows = [];
  7426. try {
  7427. $query = Db::table('purchase_order');
  7428. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7429. $dbRows = $query->select();
  7430. } catch (\Throwable $e) {
  7431. $dbRows = [];
  7432. }
  7433. if (!is_array($dbRows)) {
  7434. $dbRows = [];
  7435. }
  7436. $completeTsMap = [];
  7437. $sidList = [];
  7438. foreach ($dbRows as $dbRow) {
  7439. if (!is_array($dbRow)) {
  7440. continue;
  7441. }
  7442. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  7443. if ($sid > 0) {
  7444. $sidList[$sid] = true;
  7445. }
  7446. }
  7447. if ($sidList !== []) {
  7448. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  7449. }
  7450. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  7451. if (!is_array($dbRow)) {
  7452. return false;
  7453. }
  7454. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  7455. return $done['ts'] > 0 && date('Y-m', $done['ts']) === $ym;
  7456. }));
  7457. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  7458. $filtered = $pool;
  7459. $mainBySid = [];
  7460. foreach ($filtered as $rw) {
  7461. if (!is_array($rw)) {
  7462. continue;
  7463. }
  7464. $rid = (int)($rw['ID'] ?? 0);
  7465. if ($rid > 0) {
  7466. $mainBySid[$rid] = $rw;
  7467. }
  7468. }
  7469. if ($mainBySid === []) {
  7470. $detailRows = [];
  7471. } else {
  7472. try {
  7473. $detailRows = Db::table('purchase_order_detail')
  7474. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7475. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7476. ->order('status', 'desc')
  7477. ->order('CCYDH', 'asc')
  7478. ->order('company_name', 'asc')
  7479. ->order('id', 'asc')
  7480. ->select();
  7481. } catch (\Throwable $e) {
  7482. try {
  7483. $detailRows = Db::table('purchase_order_detail')
  7484. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7485. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7486. ->order('status', 'desc')
  7487. ->order('CCYDH', 'asc')
  7488. ->order('company_name', 'asc')
  7489. ->order('ID', 'asc')
  7490. ->select();
  7491. } catch (\Throwable $e2) {
  7492. $detailRows = [];
  7493. }
  7494. }
  7495. }
  7496. if (!is_array($detailRows)) {
  7497. $detailRows = [];
  7498. }
  7499. $exportLines = [];
  7500. $detailSidSeen = [];
  7501. foreach ($detailRows as $dr) {
  7502. if (!is_array($dr)) {
  7503. continue;
  7504. }
  7505. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7506. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7507. continue;
  7508. }
  7509. if (isset($detailSidSeen[$sid])) {
  7510. continue;
  7511. }
  7512. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  7513. continue;
  7514. }
  7515. $detailSidSeen[$sid] = true;
  7516. $m = $mainBySid[$sid];
  7517. $exportLines[] = [
  7518. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7519. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7520. 'company_name' => (string)($dr['company_name'] ?? ''),
  7521. 'CDF' => (string)($m['CDF'] ?? ''),
  7522. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7523. 'gx' => $this->procuremenExportGxText($m),
  7524. 'detail' => $dr,
  7525. ];
  7526. }
  7527. foreach ($detailRows as $dr) {
  7528. if (!is_array($dr)) {
  7529. continue;
  7530. }
  7531. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7532. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  7533. continue;
  7534. }
  7535. $detailSidSeen[$sid] = true;
  7536. $m = $mainBySid[$sid];
  7537. $exportLines[] = [
  7538. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7539. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7540. 'company_name' => (string)($dr['company_name'] ?? ''),
  7541. 'CDF' => (string)($m['CDF'] ?? ''),
  7542. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7543. 'gx' => $this->procuremenExportGxText($m),
  7544. 'detail' => $dr,
  7545. ];
  7546. }
  7547. foreach ($mainBySid as $sid => $m) {
  7548. if (isset($detailSidSeen[$sid])) {
  7549. continue;
  7550. }
  7551. $company = trim((string)($m['pick_company_name'] ?? ''));
  7552. $exportLines[] = [
  7553. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  7554. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  7555. 'company_name' => $company,
  7556. 'CDF' => (string)($m['CDF'] ?? ''),
  7557. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7558. 'gx' => $this->procuremenExportGxText($m),
  7559. 'detail' => [],
  7560. ];
  7561. }
  7562. $groups = [];
  7563. foreach ($exportLines as $line) {
  7564. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  7565. if (!isset($groups[$k])) {
  7566. $groups[$k] = [];
  7567. }
  7568. $groups[$k][] = $line;
  7569. }
  7570. ksort($groups, SORT_STRING);
  7571. $spreadsheet = new Spreadsheet();
  7572. $sheet = $spreadsheet->getActiveSheet();
  7573. $sheet->setTitle('外协加工明细');
  7574. $mon = (int)substr($ym, 5, 2);
  7575. $sheet->mergeCells('A1:H1');
  7576. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  7577. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  7578. $sheet->getStyle('A1')->getAlignment()
  7579. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7580. ->setVertical(Alignment::VERTICAL_CENTER);
  7581. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  7582. $col = 'A';
  7583. foreach ($headers as $h) {
  7584. $sheet->setCellValue($col . '2', $h);
  7585. $col++;
  7586. }
  7587. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  7588. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7589. $rowNum = 3;
  7590. $sumSubtotalCounts = 0;
  7591. $grandAmount = 0.0;
  7592. $globalSeq = 0;
  7593. if ($groups === []) {
  7594. $sheet->mergeCells('A3:H3');
  7595. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  7596. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7597. $rowNum = 4;
  7598. } else {
  7599. foreach ($groups as $items) {
  7600. if ($items === []) {
  7601. continue;
  7602. }
  7603. $groupLineCount = count($items);
  7604. $subAmount = 0.0;
  7605. foreach ($items as $line) {
  7606. $globalSeq++;
  7607. $dr = $line['detail'];
  7608. $amt = $this->procuremenExportAmount($dr);
  7609. $subAmount += $amt;
  7610. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  7611. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  7612. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  7613. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  7614. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  7615. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  7616. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  7617. $sheet->setCellValue('H' . $rowNum, $amt);
  7618. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  7619. $rowNum++;
  7620. }
  7621. $sumSubtotalCounts += $groupLineCount;
  7622. $grandAmount += $subAmount;
  7623. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7624. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  7625. $sheet->getStyle('G' . $rowNum)->getAlignment()
  7626. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  7627. ->setVertical(Alignment::VERTICAL_CENTER);
  7628. $rowNum++;
  7629. }
  7630. }
  7631. $sheet->setCellValue('A' . $rowNum, '总计');
  7632. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  7633. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7634. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  7635. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  7636. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  7637. $lastRow = $rowNum;
  7638. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  7639. 'borders' => [
  7640. 'allBorders' => [
  7641. 'borderStyle' => Border::BORDER_THIN,
  7642. 'color' => ['rgb' => '000000'],
  7643. ],
  7644. ],
  7645. ]);
  7646. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  7647. if ($lastRow >= 3) {
  7648. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7649. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7650. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7651. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7652. }
  7653. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  7654. $sheet->getColumnDimension('A')->setWidth(7);
  7655. $sheet->getColumnDimension('B')->setWidth(16);
  7656. $sheet->getColumnDimension('C')->setWidth(52);
  7657. $sheet->getColumnDimension('D')->setWidth(32);
  7658. $sheet->getColumnDimension('E')->setWidth(12);
  7659. $sheet->getColumnDimension('F')->setWidth(44);
  7660. $sheet->getColumnDimension('G')->setWidth(26);
  7661. $sheet->getColumnDimension('H')->setWidth(13);
  7662. $sheet->getRowDimension(1)->setRowHeight(28);
  7663. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  7664. $quoteStartRow = $lastRow + 3;
  7665. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
  7666. if ($quoteLastRow >= $quoteStartRow) {
  7667. $sheet->getColumnDimension('E')->setWidth(28);
  7668. }
  7669. $ymCompact = str_replace('-', '', $ym);
  7670. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  7671. $filename = $fileBase . '.xlsx';
  7672. try {
  7673. $this->ensurePurchaseMonthExportLogTable();
  7674. list($adminId, $adminName) = $this->GetUseName();
  7675. Db::table('purchase_month_export_log')->insert([
  7676. 'ym' => $ym,
  7677. 'admin_id' => (int)$adminId,
  7678. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  7679. 'row_count' => count($exportLines),
  7680. 'total_amount' => round($grandAmount, 2),
  7681. 'createtime' => time(),
  7682. ]);
  7683. } catch (\Throwable $e) {
  7684. Log::write('month export log: ' . $e->getMessage(), 'error');
  7685. }
  7686. if (ob_get_length()) {
  7687. ob_end_clean();
  7688. }
  7689. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  7690. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  7691. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  7692. header('Cache-Control: max-age=0');
  7693. $writer = new Xlsx($spreadsheet);
  7694. $writer->save('php://output');
  7695. $spreadsheet->disconnectWorksheets();
  7696. unset($spreadsheet);
  7697. exit;
  7698. }
  7699. /**
  7700. * 导出用:工序列文案
  7701. */
  7702. protected function procuremenExportGxText(array $r)
  7703. {
  7704. $a = trim((string)($r['CDXMC'] ?? ''));
  7705. $b = trim((string)($r['CGYMC'] ?? ''));
  7706. if ($a !== '' && $b !== '') {
  7707. return $a . ':' . $b;
  7708. }
  7709. return $a !== '' ? $a : $b;
  7710. }
  7711. /**
  7712. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  7713. */
  7714. protected function procuremenExportAmount(array $r)
  7715. {
  7716. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  7717. if (!array_key_exists($k, $r)) {
  7718. continue;
  7719. }
  7720. $v = $r[$k];
  7721. if ($v === null || $v === '') {
  7722. continue;
  7723. }
  7724. if (is_numeric($v)) {
  7725. return (float)$v;
  7726. }
  7727. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  7728. if ($v !== '' && is_numeric($v)) {
  7729. return (float)$v;
  7730. }
  7731. }
  7732. return 0.0;
  7733. }
  7734. /**
  7735. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  7736. *
  7737. * @param array<int, array<string, mixed>> $detailRows
  7738. * @param array<int, array<string, mixed>> $mainBySid
  7739. * @return array<int, array<string, mixed>>
  7740. */
  7741. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  7742. {
  7743. $lines = [];
  7744. foreach ($detailRows as $dr) {
  7745. if (!is_array($dr)) {
  7746. continue;
  7747. }
  7748. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7749. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7750. continue;
  7751. }
  7752. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  7753. continue;
  7754. }
  7755. $cn = trim((string)($dr['company_name'] ?? ''));
  7756. if ($cn === '') {
  7757. continue;
  7758. }
  7759. $m = $mainBySid[$sid];
  7760. $am = trim((string)($dr['amount'] ?? ''));
  7761. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  7762. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  7763. $amountText = $amountFilled
  7764. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  7765. : '未填写';
  7766. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  7767. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  7768. if ($deliveryShow === '' && $deliveryRaw !== '') {
  7769. $deliveryShow = $deliveryRaw;
  7770. }
  7771. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  7772. ? $deliveryShow
  7773. : '未填写';
  7774. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  7775. $lines[] = [
  7776. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7777. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7778. 'gx' => $this->procuremenExportGxText($m),
  7779. 'company_name' => $cn,
  7780. 'amount_text' => $amountText,
  7781. 'amount_num' => $amountFilled ? $amountNum : null,
  7782. 'delivery_text' => $deliveryText,
  7783. 'picked_text' => $picked ? '中标' : '未中标',
  7784. 'picked' => $picked,
  7785. ];
  7786. }
  7787. $winnerSupplierByOrder = [];
  7788. foreach ($lines as $line) {
  7789. $dh = trim((string)($line['CCYDH'] ?? ''));
  7790. $cn = trim((string)($line['company_name'] ?? ''));
  7791. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  7792. $winnerSupplierByOrder[$dh][$cn] = true;
  7793. }
  7794. }
  7795. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  7796. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  7797. if ($c !== 0) {
  7798. return $c;
  7799. }
  7800. $dh = trim((string)($a['CCYDH'] ?? ''));
  7801. $aCn = trim((string)($a['company_name'] ?? ''));
  7802. $bCn = trim((string)($b['company_name'] ?? ''));
  7803. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  7804. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  7805. if ($aSupplierWin !== $bSupplierWin) {
  7806. return $aSupplierWin ? -1 : 1;
  7807. }
  7808. $c = strcmp($aCn, $bCn);
  7809. if ($c !== 0) {
  7810. return $c;
  7811. }
  7812. if (!empty($a['picked']) !== !empty($b['picked'])) {
  7813. return !empty($a['picked']) ? -1 : 1;
  7814. }
  7815. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  7816. if ($c !== 0) {
  7817. return $c;
  7818. }
  7819. return 0;
  7820. });
  7821. return $lines;
  7822. }
  7823. /**
  7824. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  7825. *
  7826. * @param array<int, array<string, mixed>> $quoteLines
  7827. */
  7828. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  7829. {
  7830. $mon = (int)substr($ym, 5, 2);
  7831. $titleRow = $startRow;
  7832. $headerRow = $startRow + 1;
  7833. $dataStartRow = $startRow + 2;
  7834. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  7835. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  7836. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  7837. $sheet->getStyle('A' . $titleRow)->getAlignment()
  7838. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7839. ->setVertical(Alignment::VERTICAL_CENTER);
  7840. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  7841. $col = 'A';
  7842. foreach ($headers as $h) {
  7843. $sheet->setCellValue($col . $headerRow, $h);
  7844. $col++;
  7845. }
  7846. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  7847. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7848. $rowNum = $dataStartRow;
  7849. if ($quoteLines === []) {
  7850. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  7851. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  7852. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7853. $rowNum = $dataStartRow + 1;
  7854. } else {
  7855. $i = 0;
  7856. foreach ($quoteLines as $line) {
  7857. $i++;
  7858. $sheet->setCellValue('A' . $rowNum, $i);
  7859. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  7860. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  7861. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  7862. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  7863. if ($line['amount_num'] !== null) {
  7864. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  7865. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  7866. } else {
  7867. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  7868. }
  7869. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  7870. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  7871. if (!empty($line['picked'])) {
  7872. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  7873. }
  7874. $rowNum++;
  7875. }
  7876. }
  7877. $lastRow = $rowNum - 1;
  7878. if ($lastRow >= $headerRow) {
  7879. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  7880. 'borders' => [
  7881. 'allBorders' => [
  7882. 'borderStyle' => Border::BORDER_THIN,
  7883. 'color' => ['rgb' => '000000'],
  7884. ],
  7885. ],
  7886. ]);
  7887. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  7888. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7889. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7890. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7891. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  7892. if ($lastRow >= $dataStartRow) {
  7893. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  7894. }
  7895. }
  7896. return $lastRow;
  7897. }
  7898. /**
  7899. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  7900. */
  7901. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  7902. {
  7903. if ($lastRow < $dataStartRow || $headerRow < 1) {
  7904. return;
  7905. }
  7906. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  7907. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7908. ->setVertical(Alignment::VERTICAL_CENTER);
  7909. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  7910. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7911. ->setVertical(Alignment::VERTICAL_CENTER);
  7912. if ($lastCol > 'B') {
  7913. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  7914. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  7915. ->setVertical(Alignment::VERTICAL_CENTER);
  7916. }
  7917. }
  7918. /**
  7919. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  7920. */
  7921. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  7922. {
  7923. $s = trim($ccydh);
  7924. if ($s === '') {
  7925. return 'ORDER';
  7926. }
  7927. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  7928. $s = trim($s, '._-');
  7929. if ($s === '') {
  7930. return 'ORDER';
  7931. }
  7932. if (function_exists('mb_substr')) {
  7933. return mb_substr($s, 0, 80, 'UTF-8');
  7934. }
  7935. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  7936. }
  7937. /**
  7938. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  7939. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  7940. *
  7941. * @return array{objectKey: string, webPath: string}
  7942. */
  7943. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  7944. {
  7945. $sid = (int)$scydgyId;
  7946. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  7947. $y = date('Y');
  7948. $m = date('m');
  7949. $d = date('d');
  7950. $basename = $safeOrder . '_' . $sid . '.pdf';
  7951. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  7952. return [
  7953. 'objectKey' => $objectKey,
  7954. 'webPath' => '/' . $objectKey,
  7955. ];
  7956. }
  7957. /**
  7958. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  7959. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  7960. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  7961. *
  7962. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  7963. */
  7964. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  7965. {
  7966. if (!$this->isValidScydgyRowId($scydgyId)) {
  7967. return '';
  7968. }
  7969. $ids = trim((string)$scydgyId);
  7970. $prep = $this->prepareProcuremenDetailsView($ids);
  7971. if (!$prep['ok']) {
  7972. return '';
  7973. }
  7974. $ccydh = $prep['ccydh'];
  7975. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  7976. $objectKey = $paths['objectKey'];
  7977. $webPath = $paths['webPath'];
  7978. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  7979. $this->view->assign([
  7980. 'pdf_export' => 1,
  7981. 'pdfMetaLine' => $meta,
  7982. ]);
  7983. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  7984. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  7985. $this->view->engine->layout(false);
  7986. try {
  7987. $html = $this->view->fetch('procuremen/details_pdf_shell');
  7988. } catch (\Throwable $e) {
  7989. if ($restoreLayout) {
  7990. $this->view->engine->layout($restoreLayout);
  7991. }
  7992. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  7993. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  7994. return '';
  7995. }
  7996. if ($restoreLayout) {
  7997. $this->view->engine->layout($restoreLayout);
  7998. }
  7999. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8000. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  8001. if (!is_dir($tempDir)) {
  8002. @mkdir($tempDir, 0755, true);
  8003. }
  8004. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  8005. try {
  8006. $mpdf = new \Mpdf\Mpdf([
  8007. 'mode' => 'utf-8',
  8008. 'format' => 'A4',
  8009. 'margin_left' => 12,
  8010. 'margin_right' => 12,
  8011. 'margin_top' => 14,
  8012. 'margin_bottom' => 14,
  8013. 'tempDir' => $tempDir,
  8014. 'autoScriptToLang' => true,
  8015. 'autoLangToFont' => true,
  8016. ]);
  8017. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  8018. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  8019. $mpdf->SetBasePath('http://127.0.0.1/');
  8020. $mpdf->WriteHTML($html);
  8021. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  8022. } catch (\Throwable $e) {
  8023. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  8024. if (is_file($tempPdf)) {
  8025. @unlink($tempPdf);
  8026. }
  8027. return '';
  8028. }
  8029. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  8030. if ($ossUrl !== '') {
  8031. @unlink($tempPdf);
  8032. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8033. return $ossUrl;
  8034. }
  8035. $pi = pathinfo($objectKey);
  8036. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  8037. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  8038. if ($baseFile === '') {
  8039. @unlink($tempPdf);
  8040. return '';
  8041. }
  8042. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  8043. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  8044. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  8045. @unlink($tempPdf);
  8046. return '';
  8047. }
  8048. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  8049. if (!@copy($tempPdf, $fullPath)) {
  8050. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  8051. @unlink($tempPdf);
  8052. return '';
  8053. }
  8054. @unlink($tempPdf);
  8055. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8056. return $webPath;
  8057. }
  8058. /**
  8059. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  8060. */
  8061. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  8062. {
  8063. if ($scydgyId <= 0 || $webPath === '') {
  8064. return;
  8065. }
  8066. try {
  8067. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  8068. } catch (\Throwable $e) {
  8069. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  8070. }
  8071. }
  8072. /**
  8073. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  8074. *
  8075. * @param array<string, string> $vars
  8076. * @return array<string, string>
  8077. */
  8078. protected function normalizeSmsTemplateVars(array $vars): array
  8079. {
  8080. $out = [];
  8081. foreach ($vars as $k => $v) {
  8082. $out[(string)$k] = trim((string)$v);
  8083. }
  8084. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  8085. $out['contact_name'] = $out['company_name'];
  8086. }
  8087. return $out;
  8088. }
  8089. /**
  8090. * 按手机号或公司名称查 customer 表联系人姓名
  8091. */
  8092. protected function resolveCustomerContactName(string $phone, string $companyName): string
  8093. {
  8094. $phone = trim($phone);
  8095. $companyName = trim($companyName);
  8096. try {
  8097. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  8098. $row = Db::table('customer')
  8099. ->where(function ($q) use ($phone) {
  8100. $q->where('phone', $phone)->whereOr('account', $phone);
  8101. })
  8102. ->order('id', 'asc')
  8103. ->find();
  8104. if (is_array($row)) {
  8105. $nm = trim((string)($row['username'] ?? ''));
  8106. if ($nm !== '') {
  8107. return $nm;
  8108. }
  8109. }
  8110. }
  8111. if ($companyName !== '') {
  8112. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  8113. if (is_array($row)) {
  8114. return trim((string)($row['username'] ?? ''));
  8115. }
  8116. }
  8117. } catch (\Throwable $e) {
  8118. }
  8119. return '';
  8120. }
  8121. /**
  8122. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  8123. */
  8124. protected function plainTextToHtmlEmailBody(string $text): string
  8125. {
  8126. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  8127. $parts = explode("\n", $text);
  8128. $out = [];
  8129. foreach ($parts as $line) {
  8130. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  8131. $out[] = $line;
  8132. } else {
  8133. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  8134. }
  8135. }
  8136. return implode("<br>\n", $out);
  8137. }
  8138. /**
  8139. * 短信场景:去掉链接类变量,避免误填 URL
  8140. *
  8141. * @param array<string, string> $vars
  8142. * @return array<string, string>
  8143. */
  8144. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  8145. {
  8146. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  8147. return $vars;
  8148. }
  8149. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  8150. $vars[$k] = '';
  8151. }
  8152. return $vars;
  8153. }
  8154. /**
  8155. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  8156. *
  8157. * @param array<string, string> $vars
  8158. */
  8159. protected function renderNotifyTemplate(string $scene, array $vars): string
  8160. {
  8161. $vars = $this->normalizeSmsTemplateVars($vars);
  8162. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  8163. $row = $this->loadNotifyTemplateRow($scene);
  8164. if ($row === null) {
  8165. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8166. }
  8167. $tpl = trim((string)($row['content'] ?? ''));
  8168. if ($tpl === '') {
  8169. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8170. }
  8171. foreach ($vars as $k => $v) {
  8172. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  8173. }
  8174. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  8175. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  8176. return $tpl;
  8177. }
  8178. protected function resolveProcuremenEmailSubject(string $scene): string
  8179. {
  8180. $map = [
  8181. 'review_email' => '您有新的协助加工订单',
  8182. ];
  8183. $subject = trim((string)($map[$scene] ?? ''));
  8184. if ($subject === '') {
  8185. $this->error('未配置邮件主题:' . $scene);
  8186. }
  8187. return $subject;
  8188. }
  8189. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  8190. {
  8191. $map = [
  8192. 'review_email' => '协助下发-邮箱',
  8193. 'review_sms' => '协助下发-短信',
  8194. 'confirm_ok' => '采购确认-通过',
  8195. 'confirm_fail' => '采购确认-未通过',
  8196. 'bid_open' => '开标双重验证',
  8197. ];
  8198. $label = $map[$scene] ?? $scene;
  8199. if ($titleRequired) {
  8200. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  8201. }
  8202. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  8203. }
  8204. /**
  8205. * 是否开启协助通知演练(不发真实短信/邮件)
  8206. */
  8207. protected function isProcuremenNotifyDryRun(): bool
  8208. {
  8209. return (bool)Config::get('procuremen_notify_dry_run');
  8210. }
  8211. /**
  8212. * @param array<string, mixed> $payload
  8213. */
  8214. protected function recordNotifyDryRunPreview(array $payload): void
  8215. {
  8216. $this->notifyDryRunPreview[] = $payload;
  8217. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8218. }
  8219. /**
  8220. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  8221. * @throws \Exception
  8222. */
  8223. protected function smsbao($phone, $content)
  8224. {
  8225. if ($this->isProcuremenNotifyDryRun()) {
  8226. $this->recordNotifyDryRunPreview([
  8227. 'scene' => 'sms_only',
  8228. 'phone' => $phone,
  8229. 'sms_content' => $content,
  8230. ]);
  8231. return;
  8232. }
  8233. $statusStr = [
  8234. '0' => '短信发送成功',
  8235. '-1' => '参数不全',
  8236. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  8237. '30' => '密码错误',
  8238. '40' => '账号不存在',
  8239. '41' => '余额不足',
  8240. '42' => '帐户已过期',
  8241. '43' => 'IP地址限制',
  8242. '50' => '内容含有敏感词',
  8243. ];
  8244. $smsapi = 'http://api.smsbao.com/';
  8245. $user = 'zhuwei123';
  8246. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  8247. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  8248. $result = @file_get_contents($sendurl);
  8249. if ($result === false) {
  8250. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  8251. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  8252. }
  8253. $result = trim((string)$result);
  8254. if ($result !== '0') {
  8255. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  8256. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  8257. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  8258. }
  8259. }
  8260. }