Procuremen.php 332 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899
  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{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1759. */
  1760. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1761. {
  1762. $sysRq = $this->resolveBundleSysRq($bundle);
  1763. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1764. $this->error('未到截止时间');
  1765. }
  1766. }
  1767. /**
  1768. * 截止时间前:隐藏单价/交期真实值,统一展示文案
  1769. *
  1770. * @param array<string, mixed> $line
  1771. */
  1772. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  1773. {
  1774. $amountFilled = !empty($line['amount_filled']);
  1775. $deliveryFilled = !empty($line['delivery_filled']);
  1776. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  1777. $line['amount_show'] = '';
  1778. if (array_key_exists('amount_text', $line)) {
  1779. $line['amount_text'] = $line['unit_price_text'];
  1780. }
  1781. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  1782. $line['delivery_show'] = $deliveryText;
  1783. if (array_key_exists('delivery_text', $line)) {
  1784. $line['delivery_text'] = $deliveryText;
  1785. }
  1786. $line['delivery_ymd'] = '';
  1787. $line['subtotal_text'] = $amountFilled ? '' : '';
  1788. $line['subtotal_num'] = null;
  1789. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  1790. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  1791. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled) ? 1 : 0;
  1792. $line['amount_filled'] = false;
  1793. $line['delivery_filled'] = false;
  1794. $line['is_quoted'] = false;
  1795. if (array_key_exists('quote_label', $line)) {
  1796. $line['quote_label'] = ($amountFilled || $deliveryFilled) ? '未开标验证' : '未报价';
  1797. }
  1798. }
  1799. protected function ensurePurchaseOrderBidOpenTable(): void
  1800. {
  1801. try {
  1802. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  1803. } catch (\Throwable $e) {
  1804. Db::execute(
  1805. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  1806. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  1807. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  1808. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  1809. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  1810. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  1811. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  1812. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  1813. `operator_name` varchar(64) NOT NULL DEFAULT '',
  1814. `createtime` datetime DEFAULT NULL,
  1815. PRIMARY KEY (`id`),
  1816. UNIQUE KEY `uk_ccydh` (`ccydh`)
  1817. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  1818. );
  1819. }
  1820. }
  1821. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  1822. {
  1823. $ccydh = trim($ccydh);
  1824. if ($ccydh === '') {
  1825. return false;
  1826. }
  1827. $this->ensurePurchaseOrderBidOpenTable();
  1828. try {
  1829. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1830. return is_array($row);
  1831. } catch (\Throwable $e) {
  1832. return false;
  1833. }
  1834. }
  1835. /**
  1836. * @param array{ccydh?:string} $bundle
  1837. */
  1838. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  1839. {
  1840. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  1841. }
  1842. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  1843. {
  1844. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  1845. }
  1846. protected function loadBidOpenAdminUser(int $adminId): ?array
  1847. {
  1848. if ($adminId <= 0) {
  1849. return null;
  1850. }
  1851. try {
  1852. $row = Db::name('admin')->where('id', $adminId)->find();
  1853. } catch (\Throwable $e) {
  1854. return null;
  1855. }
  1856. if (!is_array($row)) {
  1857. return null;
  1858. }
  1859. $status = strtolower(trim((string)($row['status'] ?? '')));
  1860. if ($status !== '' && $status !== 'normal') {
  1861. return null;
  1862. }
  1863. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  1864. return null;
  1865. }
  1866. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  1867. if (!preg_match('/^1\d{10}$/', $phone)) {
  1868. return null;
  1869. }
  1870. $name = trim((string)($row['nickname'] ?? ''));
  1871. if ($name === '') {
  1872. $name = trim((string)($row['username'] ?? ''));
  1873. }
  1874. return [
  1875. 'id' => (int)$row['id'],
  1876. 'username' => trim((string)($row['username'] ?? '')),
  1877. 'nickname' => $name,
  1878. 'mobile' => $phone,
  1879. ];
  1880. }
  1881. /**
  1882. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  1883. */
  1884. protected function bidOpenVerifierAuthGroupRootId(): int
  1885. {
  1886. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  1887. return $id > 0 ? $id : 10;
  1888. }
  1889. /**
  1890. * @return int[]
  1891. */
  1892. protected function loadBidOpenVerifierAuthGroupIds(): array
  1893. {
  1894. static $memo = [];
  1895. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  1896. if (isset($memo[$rootId])) {
  1897. return $memo[$rootId];
  1898. }
  1899. try {
  1900. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  1901. } catch (\Throwable $e) {
  1902. $memo[$rootId] = [$rootId];
  1903. return $memo[$rootId];
  1904. }
  1905. if (!is_array($groups) || $groups === []) {
  1906. $memo[$rootId] = [$rootId];
  1907. return $memo[$rootId];
  1908. }
  1909. $groupList = [];
  1910. foreach ($groups as $g) {
  1911. if (is_array($g)) {
  1912. $groupList[] = $g;
  1913. }
  1914. }
  1915. if ($groupList === []) {
  1916. $memo[$rootId] = [$rootId];
  1917. return $memo[$rootId];
  1918. }
  1919. $tree = \fast\Tree::instance();
  1920. $tree->init($groupList);
  1921. $ids = $tree->getChildrenIds($rootId, true);
  1922. if (!is_array($ids) || $ids === []) {
  1923. $memo[$rootId] = [$rootId];
  1924. return $memo[$rootId];
  1925. }
  1926. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  1927. return $memo[$rootId];
  1928. }
  1929. protected function isBidOpenVerifierAdmin(int $adminId): bool
  1930. {
  1931. if ($adminId <= 0) {
  1932. return false;
  1933. }
  1934. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  1935. if ($groupIds === []) {
  1936. return false;
  1937. }
  1938. try {
  1939. return (bool)Db::name('auth_group_access')
  1940. ->where('uid', $adminId)
  1941. ->where('group_id', 'in', $groupIds)
  1942. ->count();
  1943. } catch (\Throwable $e) {
  1944. return false;
  1945. }
  1946. }
  1947. /**
  1948. * @return array<int, array<string, mixed>>
  1949. */
  1950. protected function listBidOpenVerifierCandidates(): array
  1951. {
  1952. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  1953. if ($groupIds === []) {
  1954. return [];
  1955. }
  1956. try {
  1957. $adminIds = Db::name('auth_group_access')
  1958. ->where('group_id', 'in', $groupIds)
  1959. ->column('uid');
  1960. } catch (\Throwable $e) {
  1961. $adminIds = [];
  1962. }
  1963. $adminIds = is_array($adminIds)
  1964. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  1965. : [];
  1966. if ($adminIds === []) {
  1967. return [];
  1968. }
  1969. try {
  1970. $rows = Db::name('admin')
  1971. ->where('status', 'normal')
  1972. ->where('id', 'in', $adminIds)
  1973. ->where('mobile', '<>', '')
  1974. ->order('id', 'asc')
  1975. ->select();
  1976. } catch (\Throwable $e) {
  1977. return [];
  1978. }
  1979. if (!is_array($rows)) {
  1980. return [];
  1981. }
  1982. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  1983. $out = [];
  1984. foreach ($rows as $row) {
  1985. if (!is_array($row)) {
  1986. continue;
  1987. }
  1988. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  1989. if ($one === null) {
  1990. continue;
  1991. }
  1992. $out[] = [
  1993. 'id' => $one['id'],
  1994. 'username' => $one['username'],
  1995. 'nickname' => $one['nickname'],
  1996. 'group_name' => $groupNameMap[$one['id']] ?? '',
  1997. 'mobile' => mask_phone($one['mobile']),
  1998. ];
  1999. }
  2000. return $out;
  2001. }
  2002. /**
  2003. * @param int[] $adminIds
  2004. * @return array<int, string>
  2005. */
  2006. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2007. {
  2008. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2009. if ($adminIds === []) {
  2010. return [];
  2011. }
  2012. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2013. try {
  2014. $rows = Db::name('auth_group_access')
  2015. ->alias('aga')
  2016. ->join('auth_group ag', 'aga.group_id = ag.id')
  2017. ->where('aga.uid', 'in', $adminIds)
  2018. ->where('aga.group_id', 'in', $groupIds)
  2019. ->field('aga.uid,ag.name')
  2020. ->order('aga.uid', 'asc')
  2021. ->order('aga.group_id', 'asc')
  2022. ->select();
  2023. } catch (\Throwable $e) {
  2024. return [];
  2025. }
  2026. if (!is_array($rows)) {
  2027. return [];
  2028. }
  2029. $out = [];
  2030. foreach ($rows as $row) {
  2031. if (!is_array($row)) {
  2032. continue;
  2033. }
  2034. $uid = (int)($row['uid'] ?? 0);
  2035. $name = trim((string)($row['name'] ?? ''));
  2036. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2037. continue;
  2038. }
  2039. $out[$uid] = $name;
  2040. }
  2041. return $out;
  2042. }
  2043. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2044. {
  2045. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2046. }
  2047. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2048. {
  2049. return 'procuremen_bidopen_wait_' . $adminId;
  2050. }
  2051. protected function renderBidOpenVerifySms(string $code): string
  2052. {
  2053. $tpl = '';
  2054. try {
  2055. $row = $this->loadNotifyTemplateRow('bid_open');
  2056. if (is_array($row)) {
  2057. $tpl = trim((string)($row['content'] ?? ''));
  2058. }
  2059. } catch (\Throwable $e) {
  2060. $tpl = '';
  2061. }
  2062. if ($tpl === '') {
  2063. $tpl = '【可集达】您的短信验证码是{code}';
  2064. }
  2065. return str_replace('{code}', $code, $tpl);
  2066. }
  2067. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2068. {
  2069. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2070. }
  2071. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2072. {
  2073. $code = trim($code);
  2074. if (!preg_match('/^\d{6}$/', $code)) {
  2075. return false;
  2076. }
  2077. $mock = Config::get('mproc.mock_sms_code');
  2078. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2079. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2080. return true;
  2081. }
  2082. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2083. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2084. return false;
  2085. }
  2086. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2087. return true;
  2088. }
  2089. /**
  2090. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2091. */
  2092. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2093. {
  2094. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2095. if ($ccydh === '') {
  2096. throw new \InvalidArgumentException('订单号无效');
  2097. }
  2098. $this->ensurePurchaseOrderBidOpenTable();
  2099. list($operatorId, $operatorName) = $this->GetUseName();
  2100. $now = date('Y-m-d H:i:s');
  2101. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2102. $payload = [
  2103. 'ccydh' => $ccydh,
  2104. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2105. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2106. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2107. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2108. 'operator_id' => (int)$operatorId,
  2109. 'operator_name' => trim((string)$operatorName),
  2110. 'createtime' => $now,
  2111. ];
  2112. if (is_array($exists)) {
  2113. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2114. } else {
  2115. Db::table('purchase_order_bid_open')->insert($payload);
  2116. }
  2117. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2118. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2119. $orderPart = '(订单' . $ccydh . ')';
  2120. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2121. $seenSid = [];
  2122. foreach ($bundle['pos'] ?? [] as $poRow) {
  2123. if (!is_array($poRow)) {
  2124. continue;
  2125. }
  2126. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2127. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2128. continue;
  2129. }
  2130. $seenSid[$sid] = true;
  2131. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2132. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2133. }
  2134. if ($seenSid === []) {
  2135. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2136. if ($this->isValidScydgyRowId($anchor)) {
  2137. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2138. }
  2139. }
  2140. }
  2141. /**
  2142. * 报价行展示字段默认值(模板安全访问)
  2143. *
  2144. * @param array<string, mixed> $line
  2145. * @return array<string, mixed>
  2146. */
  2147. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2148. {
  2149. if (!array_key_exists('amount_quote_pending', $line)) {
  2150. $line['amount_quote_pending'] = 0;
  2151. }
  2152. if (!array_key_exists('delivery_quote_pending', $line)) {
  2153. $line['delivery_quote_pending'] = 0;
  2154. }
  2155. if (!array_key_exists('quote_before_deadline', $line)) {
  2156. $line['quote_before_deadline'] = 0;
  2157. }
  2158. if (!array_key_exists('amount_filled', $line)) {
  2159. $line['amount_filled'] = 0;
  2160. }
  2161. if (!array_key_exists('delivery_filled', $line)) {
  2162. $line['delivery_filled'] = 0;
  2163. }
  2164. return $line;
  2165. }
  2166. /**
  2167. * 审核弹窗:按供应商汇总报价明细
  2168. *
  2169. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2170. * @return array<int, array<string, mixed>>
  2171. */
  2172. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2173. {
  2174. $sids = [];
  2175. foreach ($bundle['pos'] ?? [] as $po) {
  2176. if (!is_array($po)) {
  2177. continue;
  2178. }
  2179. $sid = (int)($po['scydgy_id'] ?? 0);
  2180. if ($this->isValidScydgyRowId($sid)) {
  2181. $sids[$sid] = true;
  2182. }
  2183. }
  2184. if ($sids === []) {
  2185. return [];
  2186. }
  2187. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2188. $gymcMap = [];
  2189. $qtyBySid = [];
  2190. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2191. if (!is_array($mr)) {
  2192. continue;
  2193. }
  2194. $gid = $this->extractScydgyRowId($mr);
  2195. if ($this->isValidScydgyRowId($gid)) {
  2196. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2197. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2198. if ($qty === '') {
  2199. $qty = trim((string)($mr['NGZL'] ?? ''));
  2200. }
  2201. $qtyBySid[$gid] = $qty;
  2202. }
  2203. }
  2204. foreach ($bundle['pos'] ?? [] as $po) {
  2205. if (!is_array($po)) {
  2206. continue;
  2207. }
  2208. $gid = (int)($po['scydgy_id'] ?? 0);
  2209. if ($this->isValidScydgyRowId($gid)) {
  2210. $nm = trim((string)($po['CGYMC'] ?? ''));
  2211. if ($nm !== '') {
  2212. $gymcMap[$gid] = $nm;
  2213. }
  2214. }
  2215. }
  2216. try {
  2217. $detailsQuery = Db::table('purchase_order_detail')
  2218. ->where('scydgy_id', 'in', array_keys($sids));
  2219. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2220. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2221. } catch (\Throwable $e) {
  2222. try {
  2223. $detailsQuery = Db::table('purchase_order_detail')
  2224. ->where('scydgy_id', 'in', array_keys($sids));
  2225. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2226. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2227. } catch (\Throwable $e2) {
  2228. $details = [];
  2229. }
  2230. }
  2231. if (!is_array($details)) {
  2232. $details = [];
  2233. }
  2234. $byCompany = [];
  2235. foreach ($details as $d) {
  2236. if (!is_array($d)) {
  2237. continue;
  2238. }
  2239. $cn = trim((string)($d['company_name'] ?? ''));
  2240. if ($cn === '') {
  2241. continue;
  2242. }
  2243. if (!isset($byCompany[$cn])) {
  2244. $ph = trim((string)($d['phone'] ?? ''));
  2245. $username = trim((string)($d['username'] ?? ''));
  2246. if ($username === '') {
  2247. $username = $this->resolveCustomerContactName($ph, $cn);
  2248. }
  2249. $byCompany[$cn] = [
  2250. 'name' => $cn,
  2251. 'email' => trim((string)($d['email'] ?? '')),
  2252. 'phone' => $ph,
  2253. 'username' => $username,
  2254. 'has_quote' => false,
  2255. 'lines' => [],
  2256. ];
  2257. }
  2258. $sid = (int)($d['scydgy_id'] ?? 0);
  2259. $am = trim((string)($d['amount'] ?? ''));
  2260. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2261. if ($gymc === '') {
  2262. $gymc = '工序';
  2263. }
  2264. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2265. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2266. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2267. $deliveryShow = $deliveryRaw;
  2268. }
  2269. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2270. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2271. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2272. $subtotal = null;
  2273. if ($amountNum !== null) {
  2274. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2275. }
  2276. $unitPriceText = $amountFilled
  2277. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2278. : '未填写';
  2279. $lineRow = [
  2280. 'cgymc' => $gymc,
  2281. 'amount' => $am,
  2282. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2283. 'amount_filled' => $amountFilled,
  2284. 'unit_price_text' => $unitPriceText,
  2285. 'delivery' => $deliveryRaw,
  2286. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2287. 'delivery_filled' => $deliveryFilled,
  2288. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2289. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2290. 'subtotal_num' => $subtotal,
  2291. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2292. 'is_quoted' => $amountFilled,
  2293. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2294. ];
  2295. if (!$quoteVisible) {
  2296. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2297. }
  2298. $byCompany[$cn]['lines'][] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2299. }
  2300. foreach ($byCompany as $cn => $g) {
  2301. $total = count($g['lines']);
  2302. $quoted = 0;
  2303. $groupTotal = 0.0;
  2304. $groupHasTotal = false;
  2305. if ($quoteVisible) {
  2306. foreach ($g['lines'] as $ln) {
  2307. $am = trim((string)($ln['amount'] ?? ''));
  2308. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2309. $quoted++;
  2310. }
  2311. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2312. $groupTotal += (float)$ln['subtotal_num'];
  2313. $groupHasTotal = true;
  2314. }
  2315. }
  2316. }
  2317. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2318. $byCompany[$cn]['line_count'] = $total;
  2319. $byCompany[$cn]['has_total'] = $total > 0;
  2320. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2321. $byCompany[$cn]['display_rowspan'] = $total + ($total > 0 ? 1 : 0);
  2322. }
  2323. return array_values($byCompany);
  2324. }
  2325. /**
  2326. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2327. *
  2328. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2329. * @return array<int, array<string, mixed>>
  2330. */
  2331. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2332. {
  2333. $sids = [];
  2334. $poIdMap = [];
  2335. foreach ($bundle['pos'] ?? [] as $po) {
  2336. if (!is_array($po)) {
  2337. continue;
  2338. }
  2339. $sid = (int)($po['scydgy_id'] ?? 0);
  2340. if ($this->isValidScydgyRowId($sid)) {
  2341. $sids[$sid] = true;
  2342. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2343. }
  2344. }
  2345. if ($sids === []) {
  2346. return [];
  2347. }
  2348. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2349. $gymcMap = [];
  2350. $qtyBySid = [];
  2351. $orderedSids = [];
  2352. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2353. if (!is_array($mr)) {
  2354. continue;
  2355. }
  2356. $gid = $this->extractScydgyRowId($mr);
  2357. if ($this->isValidScydgyRowId($gid)) {
  2358. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2359. $orderedSids[] = $gid;
  2360. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2361. if ($qty === '') {
  2362. $qty = trim((string)($mr['NGZL'] ?? ''));
  2363. }
  2364. $qtyBySid[$gid] = $qty;
  2365. }
  2366. }
  2367. foreach ($bundle['pos'] ?? [] as $po) {
  2368. if (!is_array($po)) {
  2369. continue;
  2370. }
  2371. $gid = (int)($po['scydgy_id'] ?? 0);
  2372. if ($this->isValidScydgyRowId($gid)) {
  2373. $nm = trim((string)($po['CGYMC'] ?? ''));
  2374. if ($nm !== '') {
  2375. $gymcMap[$gid] = $nm;
  2376. }
  2377. }
  2378. }
  2379. try {
  2380. $details = Db::table('purchase_order_detail')
  2381. ->where('scydgy_id', 'in', array_keys($sids))
  2382. ->order('company_name', 'asc')
  2383. ->order('id', 'asc')
  2384. ->select();
  2385. } catch (\Throwable $e) {
  2386. try {
  2387. $details = Db::table('purchase_order_detail')
  2388. ->where('scydgy_id', 'in', array_keys($sids))
  2389. ->order('company_name', 'asc')
  2390. ->order('ID', 'asc')
  2391. ->select();
  2392. } catch (\Throwable $e2) {
  2393. $details = [];
  2394. }
  2395. }
  2396. if (!is_array($details)) {
  2397. $details = [];
  2398. }
  2399. $byCompany = [];
  2400. foreach ($details as $d) {
  2401. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2402. continue;
  2403. }
  2404. $cn = trim((string)($d['company_name'] ?? ''));
  2405. if ($cn === '') {
  2406. continue;
  2407. }
  2408. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2409. $sid = (int)($d['scydgy_id'] ?? 0);
  2410. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2411. continue;
  2412. }
  2413. if (!isset($byCompany[$cn])) {
  2414. $ph = trim((string)($d['phone'] ?? ''));
  2415. $username = trim((string)($d['username'] ?? ''));
  2416. if ($username === '') {
  2417. $username = $this->resolveCustomerContactName($ph, $cn);
  2418. }
  2419. $byCompany[$cn] = [
  2420. 'name' => $cn,
  2421. 'email' => trim((string)($d['email'] ?? '')),
  2422. 'phone' => $ph,
  2423. 'username' => $username,
  2424. 'pick_lines' => [],
  2425. 'detail_picks' => [],
  2426. ];
  2427. }
  2428. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2429. if ($gymc === '') {
  2430. $gymc = '工序';
  2431. }
  2432. $am = trim((string)($d['amount'] ?? ''));
  2433. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2434. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2435. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2436. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2437. $deliveryShow = $deliveryRaw;
  2438. }
  2439. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2440. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2441. $subtotal = null;
  2442. if ($amountNum !== null) {
  2443. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2444. }
  2445. $unitPriceText = $amountFilled
  2446. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2447. : '未填写';
  2448. $pickLine = [
  2449. 'cgymc' => $gymc,
  2450. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2451. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2452. 'amount_filled' => $amountFilled,
  2453. 'delivery_filled' => $deliveryFilled,
  2454. 'unit_price_text' => $unitPriceText,
  2455. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2456. 'subtotal_num' => $subtotal,
  2457. 'is_quoted' => $amountFilled,
  2458. ];
  2459. if (!$quoteVisible) {
  2460. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2461. }
  2462. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2463. $byCompany[$cn]['detail_picks'][$sid] = [
  2464. 'scydgy_id' => $sid,
  2465. 'detail_id' => $detailId,
  2466. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2467. 'cgymc' => $gymc,
  2468. ];
  2469. }
  2470. $out = [];
  2471. foreach ($byCompany as $g) {
  2472. $pickLinesMap = $g['pick_lines'] ?? [];
  2473. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2474. continue;
  2475. }
  2476. $pickLines = [];
  2477. $usedLineSids = [];
  2478. foreach ($orderedSids as $sid) {
  2479. if (!isset($pickLinesMap[$sid])) {
  2480. continue;
  2481. }
  2482. $pickLines[] = $pickLinesMap[$sid];
  2483. $usedLineSids[$sid] = true;
  2484. }
  2485. foreach ($pickLinesMap as $sid => $ln) {
  2486. if (isset($usedLineSids[$sid])) {
  2487. continue;
  2488. }
  2489. $pickLines[] = $ln;
  2490. }
  2491. $groupTotal = 0.0;
  2492. $groupHasTotal = false;
  2493. if ($quoteVisible) {
  2494. foreach ($pickLines as $ln) {
  2495. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2496. $groupTotal += (float)$ln['subtotal_num'];
  2497. $groupHasTotal = true;
  2498. }
  2499. }
  2500. }
  2501. $lineCount = count($pickLines);
  2502. $g['pick_lines'] = $pickLines;
  2503. $g['line_count'] = $lineCount;
  2504. $g['has_total'] = $lineCount > 0;
  2505. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2506. $g['display_rowspan'] = $lineCount + ($lineCount > 0 ? 1 : 0);
  2507. $detailPicks = $g['detail_picks'] ?? [];
  2508. $g['detail_picks'] = array_values(is_array($detailPicks) ? $detailPicks : []);
  2509. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2510. unset($g['detail_picks']);
  2511. $out[] = $g;
  2512. }
  2513. return $out;
  2514. }
  2515. /**
  2516. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2517. * @return array<int, int[]> scydgy_id => detail_id[]
  2518. */
  2519. protected function mapDetailIdsByScydgyId(array $details): array
  2520. {
  2521. $out = [];
  2522. foreach ($details as $d) {
  2523. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2524. continue;
  2525. }
  2526. $sid = (int)($d['scydgy_id'] ?? 0);
  2527. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2528. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2529. continue;
  2530. }
  2531. if (!isset($out[$sid])) {
  2532. $out[$sid] = [];
  2533. }
  2534. $out[$sid][] = $pk;
  2535. }
  2536. foreach ($out as $sid => $ids) {
  2537. $out[$sid] = array_values(array_unique($ids));
  2538. }
  2539. return $out;
  2540. }
  2541. /**
  2542. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2543. *
  2544. * @param array<string, mixed> $dbRow
  2545. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2546. */
  2547. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2548. {
  2549. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2550. $r = [
  2551. 'ID' => $sid,
  2552. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2553. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2554. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2555. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2556. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2557. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2558. 'CDW' => $dbRow['CDW'] ?? '',
  2559. 'NGZL' => $dbRow['NGZL'] ?? '',
  2560. 'CDF' => $dbRow['CDF'] ?? '',
  2561. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2562. 'MBZ' => $dbRow['MBZ'] ?? '',
  2563. 'bwjg' => $dbRow['bwjg'] ?? '',
  2564. 'iStatus' => $dbRow['iStatus'] ?? '',
  2565. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2566. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2567. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2568. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2569. 'dStamp' => $dbRow['dStamp'] ?? '',
  2570. 'pick_time' => $dbRow['pick_time'] ?? '',
  2571. ];
  2572. if ($sid > 0 && isset($dStampMap[$sid])) {
  2573. $t = trim((string)$dStampMap[$sid]);
  2574. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2575. $r['dStamp'] = $dStampMap[$sid];
  2576. }
  2577. }
  2578. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2579. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2580. $ct = $dbRow['createtime'];
  2581. if (is_numeric($ct) && (int)$ct > 946684800) {
  2582. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2583. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2584. $r['dStamp'] = trim($ct);
  2585. }
  2586. }
  2587. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2588. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2589. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2590. $fallback = trim((string)($r['dStamp'] ?? ''));
  2591. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2592. $r['dputrecord'] = $fallback;
  2593. }
  2594. }
  2595. if (array_key_exists('id', $dbRow)) {
  2596. $r['purchase_order_id'] = (int)$dbRow['id'];
  2597. }
  2598. if ($sid < 0) {
  2599. $r['_is_manual'] = 1;
  2600. }
  2601. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2602. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2603. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2604. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2605. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2606. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2607. $r['pick_time'] = $pickFallback;
  2608. break;
  2609. }
  2610. }
  2611. }
  2612. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2613. if ($pickNm !== '') {
  2614. $r['pick_company_name'] = $pickNm;
  2615. $r['picked_supplier_name'] = $pickNm;
  2616. }
  2617. return $r;
  2618. }
  2619. /**
  2620. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2621. *
  2622. * @return array<int, array<string, mixed>>
  2623. */
  2624. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2625. {
  2626. $pool = [];
  2627. if (!is_array($dbRows) || $dbRows === []) {
  2628. return $pool;
  2629. }
  2630. $dStampMap = [];
  2631. $sidList = [];
  2632. foreach ($dbRows as $tmpRow) {
  2633. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2634. $sid = (int)$tmpRow['scydgy_id'];
  2635. if ($sid > 0) {
  2636. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2637. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2638. $sidList[$sid] = true;
  2639. }
  2640. }
  2641. }
  2642. }
  2643. if ($sidList !== []) {
  2644. try {
  2645. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2646. } catch (\Throwable $e) {
  2647. $dStampMap = [];
  2648. }
  2649. }
  2650. foreach ($dbRows as $dbRow) {
  2651. if (!is_array($dbRow)) {
  2652. continue;
  2653. }
  2654. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2655. }
  2656. return $pool;
  2657. }
  2658. /**
  2659. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2660. *
  2661. * @param int[] $scydgyIds
  2662. * @return array<int, array<string, mixed>>
  2663. */
  2664. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2665. {
  2666. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2667. if ($scydgyIds === []) {
  2668. return [];
  2669. }
  2670. try {
  2671. $list = Db::table('purchase_order_detail')
  2672. ->where('scydgy_id', 'in', $scydgyIds)
  2673. ->field('scydgy_id,company_name,amount,delivery')
  2674. ->select();
  2675. } catch (\Throwable $e) {
  2676. $list = [];
  2677. }
  2678. return is_array($list) ? $list : [];
  2679. }
  2680. /**
  2681. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2682. *
  2683. * @param int[] $scydgyIds
  2684. * @param array<int, array<string, mixed>> $allRows
  2685. * @return array{cnt:int, amt:int, deliv:int}
  2686. */
  2687. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2688. {
  2689. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2690. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2691. if ($scydgyIds === [] || $allRows === []) {
  2692. return $out;
  2693. }
  2694. $idSet = array_flip($scydgyIds);
  2695. $all = [];
  2696. $withAmt = [];
  2697. $withDeliv = [];
  2698. foreach ($allRows as $r) {
  2699. if (!is_array($r)) {
  2700. continue;
  2701. }
  2702. $sid = (int)($r['scydgy_id'] ?? 0);
  2703. if (!isset($idSet[$sid])) {
  2704. continue;
  2705. }
  2706. $cn = trim((string)($r['company_name'] ?? ''));
  2707. if ($cn === '') {
  2708. continue;
  2709. }
  2710. $all[$cn] = true;
  2711. $am = $r['amount'] ?? null;
  2712. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2713. $withAmt[$cn] = true;
  2714. }
  2715. $dv = $r['delivery'] ?? null;
  2716. if ($dv !== null && trim((string)$dv) !== '') {
  2717. $withDeliv[$cn] = true;
  2718. }
  2719. }
  2720. return [
  2721. 'cnt' => count($all),
  2722. 'amt' => count($withAmt),
  2723. 'deliv' => count($withDeliv),
  2724. ];
  2725. }
  2726. /**
  2727. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2728. *
  2729. * @param int[] $scydgyIds
  2730. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2731. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2732. */
  2733. protected function OrderDetailSummary(array $scydgyIds)
  2734. {
  2735. $out = [];
  2736. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2737. if ($scydgyIds === []) {
  2738. return $out;
  2739. }
  2740. $list = [];
  2741. try {
  2742. $list = Db::table('purchase_order_detail')
  2743. ->where('scydgy_id', 'in', $scydgyIds)
  2744. ->field('id,scydgy_id,amount,delivery')
  2745. ->select();
  2746. } catch (\Throwable $e) {
  2747. $list = [];
  2748. }
  2749. if (!is_array($list)) {
  2750. return $out;
  2751. }
  2752. foreach ($list as $r) {
  2753. if (!is_array($r)) {
  2754. continue;
  2755. }
  2756. $ids = (int)($r['scydgy_id'] ?? 0);
  2757. if (!$this->isValidScydgyRowId($ids)) {
  2758. continue;
  2759. }
  2760. if (!isset($out[$ids])) {
  2761. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2762. }
  2763. $out[$ids]['cnt']++;
  2764. $am = $r['amount'] ?? null;
  2765. if ($am !== null && $am !== '') {
  2766. if (!(is_string($am) && trim($am) === '')) {
  2767. $out[$ids]['amt']++;
  2768. }
  2769. }
  2770. $dv = $r['delivery'] ?? null;
  2771. if ($dv !== null && trim((string)$dv) !== '') {
  2772. $out[$ids]['deliv']++;
  2773. }
  2774. }
  2775. return $out;
  2776. }
  2777. /**
  2778. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  2779. *
  2780. * @return array
  2781. */
  2782. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  2783. {
  2784. $strContains = function ($haystack, $needle) {
  2785. if ($needle === '') {
  2786. return false;
  2787. }
  2788. $haystack = (string)$haystack;
  2789. if (function_exists('mb_stripos')) {
  2790. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  2791. }
  2792. return stripos($haystack, $needle) !== false;
  2793. };
  2794. $stripAlias = function ($f) {
  2795. return preg_replace('/^[ab]\./i', '', (string)$f);
  2796. };
  2797. $searchColNames = [];
  2798. foreach (explode(',', $this->searchFields) as $colRaw) {
  2799. $c = $stripAlias(trim($colRaw));
  2800. if ($c !== '') {
  2801. $searchColNames[] = $c;
  2802. }
  2803. }
  2804. $filtered = [];
  2805. foreach ($pool as $r) {
  2806. if (!is_array($r)) {
  2807. continue;
  2808. }
  2809. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  2810. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  2811. if (!$isManual) {
  2812. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  2813. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  2814. continue;
  2815. }
  2816. if ($applyMonthRange) {
  2817. $mo = (int)$m[2];
  2818. if ($mo < 1 || $mo > 12) {
  2819. continue;
  2820. }
  2821. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2822. $rowMonthStart = $ymRow . '-01 00:00:00';
  2823. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2824. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2825. continue;
  2826. }
  2827. }
  2828. } elseif ($applyMonthRange) {
  2829. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  2830. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2831. $ds = $listTime;
  2832. }
  2833. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  2834. continue;
  2835. }
  2836. $mo = (int)$m[2];
  2837. if ($mo < 1 || $mo > 12) {
  2838. continue;
  2839. }
  2840. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2841. $rowMonthStart = $ymRow . '-01 00:00:00';
  2842. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2843. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2844. continue;
  2845. }
  2846. }
  2847. if ($search !== '') {
  2848. $hitSearch = false;
  2849. foreach ($searchColNames as $c) {
  2850. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  2851. if ($cell !== '' && $strContains($cell, $search)) {
  2852. $hitSearch = true;
  2853. break;
  2854. }
  2855. }
  2856. if (!$hitSearch) {
  2857. continue;
  2858. }
  2859. }
  2860. foreach ($filterArr as $fk => $fv) {
  2861. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  2862. continue;
  2863. }
  2864. if (is_array($fv)) {
  2865. continue;
  2866. }
  2867. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  2868. continue;
  2869. }
  2870. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  2871. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  2872. $field = $stripAlias($fk);
  2873. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  2874. $cellStr = trim((string)$cell);
  2875. switch ($sym) {
  2876. case '=':
  2877. if ((string)$cell !== (string)$fv) {
  2878. continue 3;
  2879. }
  2880. break;
  2881. case '<>':
  2882. if ((string)$cell === (string)$fv) {
  2883. continue 3;
  2884. }
  2885. break;
  2886. case 'LIKE':
  2887. case 'NOT LIKE':
  2888. $needle = trim((string)$fv);
  2889. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  2890. if ($sym === 'LIKE' && !$hit) {
  2891. continue 3;
  2892. }
  2893. if ($sym === 'NOT LIKE' && $hit) {
  2894. continue 3;
  2895. }
  2896. break;
  2897. case '>':
  2898. case '>=':
  2899. case '<':
  2900. case '<=':
  2901. if (!is_numeric($cell) && $cellStr === '') {
  2902. continue 3;
  2903. }
  2904. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  2905. $vv = (float)$fv;
  2906. if ($sym === '>' && !($cv > $vv)) {
  2907. continue 3;
  2908. }
  2909. if ($sym === '>=' && !($cv >= $vv)) {
  2910. continue 3;
  2911. }
  2912. if ($sym === '<' && !($cv < $vv)) {
  2913. continue 3;
  2914. }
  2915. if ($sym === '<=' && !($cv <= $vv)) {
  2916. continue 3;
  2917. }
  2918. break;
  2919. case 'RANGE':
  2920. case 'NOT RANGE':
  2921. case 'BETWEEN':
  2922. case 'NOT BETWEEN':
  2923. case 'BETWEEN TIME':
  2924. case 'NOT BETWEEN TIME':
  2925. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  2926. $rawR = str_replace(' - ', ',', $rawR);
  2927. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  2928. if (count($arr) < 2) {
  2929. break;
  2930. }
  2931. $lo = $arr[0];
  2932. $hi = $arr[1];
  2933. if ($lo === '' && $hi === '') {
  2934. break;
  2935. }
  2936. $isNot = (strpos($sym, 'NOT') !== false);
  2937. if ($lo === '') {
  2938. $in = ($cellStr !== '' && $cellStr <= $hi);
  2939. if ($isNot ? $in : !$in) {
  2940. continue 3;
  2941. }
  2942. break;
  2943. }
  2944. if ($hi === '') {
  2945. $in = ($cellStr !== '' && $cellStr >= $lo);
  2946. if ($isNot ? $in : !$in) {
  2947. continue 3;
  2948. }
  2949. break;
  2950. }
  2951. $in = ($cellStr >= $lo && $cellStr <= $hi);
  2952. if ($isNot ? $in : !$in) {
  2953. continue 3;
  2954. }
  2955. break;
  2956. case 'NULL':
  2957. case 'IS NULL':
  2958. if ($cell !== null && $cell !== '') {
  2959. continue 3;
  2960. }
  2961. break;
  2962. case 'NOT NULL':
  2963. case 'IS NOT NULL':
  2964. if ($cell === null || $cell === '') {
  2965. continue 3;
  2966. }
  2967. break;
  2968. default:
  2969. break;
  2970. }
  2971. }
  2972. $filtered[] = $r;
  2973. }
  2974. return $filtered;
  2975. }
  2976. /**
  2977. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  2978. */
  2979. public function snapshotToProcure()
  2980. {
  2981. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2982. $this->error(__('Invalid parameters'));
  2983. }
  2984. $row = json_decode($this->request->post('row_json', ''), true);
  2985. if (!is_array($row)) {
  2986. $this->error(__('Invalid parameters'));
  2987. }
  2988. try {
  2989. $ids = $this->extractScydgyRowId($row);
  2990. if (!$this->isValidScydgyRowId($ids)) {
  2991. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2992. }
  2993. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2994. $data = [
  2995. 'scydgy_id' => $ids,
  2996. 'CCYDH' => $row['CCYDH'] ?? null,
  2997. 'CYJMC' => $row['CYJMC'] ?? null,
  2998. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2999. 'CDXMC' => $row['CDXMC'] ?? null,
  3000. 'CGYBH' => $row['CGYBH'] ?? null,
  3001. 'CGYMC' => $row['CGYMC'] ?? null,
  3002. 'CDW' => $row['CDW'] ?? null,
  3003. 'NGZL' => $row['NGZL'] ?? null,
  3004. 'CDF' => $row['CDF'] ?? null,
  3005. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3006. 'MBZ' => $row['MBZ'] ?? null,
  3007. 'bwjg' => $row['bwjg'] ?? null,
  3008. 'iStatus' => $row['iStatus'] ?? null,
  3009. 'dStamp' => $row['dStamp'] ?? null,
  3010. 'dputrecord' => $row['dputrecord'] ?? null,
  3011. 'cywyxm' => $row['cywyxm'] ?? null,
  3012. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3013. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3014. ];
  3015. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3016. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3017. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3018. $this->success('操作成功');
  3019. return;
  3020. }
  3021. if ($exists) {
  3022. $upd = $data;
  3023. unset($upd['scydgy_id'], $upd['status']);
  3024. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3025. } else {
  3026. // 新增:不写 status(空/走库默认);仅写创建时间
  3027. $data['createtime'] = date('Y-m-d H:i:s');
  3028. Db::table('purchase_order')->insert($data);
  3029. }
  3030. } catch (\Throwable $e) {
  3031. $this->error($e->getMessage());
  3032. }
  3033. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3034. $this->success('操作成功');
  3035. }
  3036. /**
  3037. * 未发列表
  3038. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3039. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3040. */
  3041. public function completeDirectly()
  3042. {
  3043. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3044. $this->error(__('参数错误'));
  3045. }
  3046. if (!$this->procuremenCanComplete()) {
  3047. $this->error(__('You have no permission'));
  3048. }
  3049. $row = json_decode($this->request->post('row_json', ''), true);
  3050. if (!is_array($row)) {
  3051. $this->error(__('Invalid parameters'));
  3052. }
  3053. $finishRaw = $this->request->post('finish', '1');
  3054. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3055. $poIdLog = null;
  3056. try {
  3057. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3058. $ids = $this->extractScydgyRowId($row);
  3059. if (!$this->isValidScydgyRowId($ids)) {
  3060. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3061. }
  3062. if ($asComplete) {
  3063. $this->assertPickRowCanComplete($ids, $row);
  3064. }
  3065. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3066. $data = [
  3067. 'scydgy_id' => $ids,
  3068. 'CCYDH' => $row['CCYDH'] ?? null,
  3069. 'CYJMC' => $row['CYJMC'] ?? null,
  3070. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3071. 'CDXMC' => $row['CDXMC'] ?? null,
  3072. 'CGYBH' => $row['CGYBH'] ?? null,
  3073. 'CGYMC' => $row['CGYMC'] ?? null,
  3074. 'CDW' => $row['CDW'] ?? null,
  3075. 'NGZL' => $row['NGZL'] ?? null,
  3076. 'CDF' => $row['CDF'] ?? null,
  3077. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3078. 'MBZ' => $row['MBZ'] ?? null,
  3079. 'bwjg' => $row['bwjg'] ?? null,
  3080. 'iStatus' => $row['iStatus'] ?? null,
  3081. 'dStamp' => $row['dStamp'] ?? null,
  3082. 'dputrecord' => $row['dputrecord'] ?? null,
  3083. 'cywyxm' => $row['cywyxm'] ?? null,
  3084. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3085. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3086. ];
  3087. if ($asComplete) {
  3088. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3089. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3090. }
  3091. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3092. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3093. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3094. $this->success('操作成功');
  3095. return;
  3096. }
  3097. if ($exists) {
  3098. $upd = $data;
  3099. unset($upd['scydgy_id']);
  3100. if (!$asComplete) {
  3101. unset($upd['status']);
  3102. }
  3103. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3104. } else {
  3105. // 新增:不写 status;完结时 $data 已含 status=1
  3106. $data['createtime'] = date('Y-m-d H:i:s');
  3107. Db::table('purchase_order')->insert($data);
  3108. }
  3109. } catch (\Throwable $e) {
  3110. $this->error($e->getMessage());
  3111. }
  3112. try {
  3113. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3114. if (is_array($rpo)) {
  3115. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3116. $poIdLog = $tid > 0 ? $tid : null;
  3117. }
  3118. } catch (\Throwable $e) {
  3119. $poIdLog = null;
  3120. }
  3121. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3122. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3123. if ($asComplete) {
  3124. $this->addOrderLog(
  3125. $ids,
  3126. 'mark_complete',
  3127. '点击「完结」,已标记为已完结',
  3128. $poIdLog
  3129. );
  3130. try {
  3131. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3132. if ($pdfPublicPath === '') {
  3133. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3134. }
  3135. } catch (\Throwable $e) {
  3136. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3137. }
  3138. } else {
  3139. $this->addOrderLog(
  3140. $ids,
  3141. 'save_qty_price',
  3142. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3143. $poIdLog
  3144. );
  3145. }
  3146. $this->pickHiddenScydgySetCache = null;
  3147. $this->success("操作成功");
  3148. }
  3149. /**
  3150. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3151. *
  3152. * @param array<int, array> $rows 引用传递当前页行
  3153. */
  3154. protected function mergePurchaseOrder(array &$rows)
  3155. {
  3156. if ($rows === []) {
  3157. return;
  3158. }
  3159. $ids = [];
  3160. foreach ($rows as $rw) {
  3161. if (!is_array($rw)) {
  3162. continue;
  3163. }
  3164. $id = (int)($rw['ID'] ?? 0);
  3165. if ($id > 0) {
  3166. $ids[$id] = true;
  3167. }
  3168. }
  3169. $idList = array_keys($ids);
  3170. if ($idList === []) {
  3171. return;
  3172. }
  3173. try {
  3174. $list = Db::table('purchase_order')
  3175. ->where('scydgy_id', 'in', $idList)
  3176. ->field('scydgy_id,This_quantity,ceilingPrice')
  3177. ->select();
  3178. } catch (\Throwable $e) {
  3179. return;
  3180. }
  3181. if (!is_array($list)) {
  3182. return;
  3183. }
  3184. $byId = [];
  3185. foreach ($list as $dbRow) {
  3186. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3187. continue;
  3188. }
  3189. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3190. }
  3191. foreach ($rows as &$rw) {
  3192. if (!is_array($rw)) {
  3193. continue;
  3194. }
  3195. $sid = (int)($rw['ID'] ?? 0);
  3196. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3197. continue;
  3198. }
  3199. $db = $byId[$sid];
  3200. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  3201. if (array_key_exists('This_quantity', $db)) {
  3202. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  3203. }
  3204. if (array_key_exists('ceilingPrice', $db)) {
  3205. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  3206. } elseif (array_key_exists('ceiling_price', $db)) {
  3207. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  3208. }
  3209. }
  3210. unset($rw);
  3211. }
  3212. /**
  3213. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3214. */
  3215. public function purchaseConfirmPick()
  3216. {
  3217. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3218. $this->error(__('Invalid parameters'));
  3219. }
  3220. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3221. $this->error(__('You have no permission'));
  3222. }
  3223. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3224. if ($batchRaw !== '') {
  3225. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3226. return;
  3227. }
  3228. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3229. $sid = (int)$scydgyId;
  3230. if (!$this->isValidScydgyRowId($sid)) {
  3231. $this->error('参数无效');
  3232. }
  3233. $parseIdList = function ($raw) {
  3234. if (is_array($raw)) {
  3235. $arr = $raw;
  3236. } else {
  3237. $decoded = json_decode((string)$raw, true);
  3238. $arr = is_array($decoded) ? $decoded : [];
  3239. }
  3240. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3241. };
  3242. $selectedRaw = $this->request->post('selected_ids', null);
  3243. if ($selectedRaw === null || $selectedRaw === '') {
  3244. $legacy = (int)$this->request->post('selected_id', 0);
  3245. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3246. } else {
  3247. $selectedIds = $parseIdList($selectedRaw);
  3248. }
  3249. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3250. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3251. try {
  3252. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3253. } catch (\InvalidArgumentException $e) {
  3254. $this->error($e->getMessage());
  3255. } catch (\Throwable $e) {
  3256. $this->error($e->getMessage());
  3257. }
  3258. $this->pickHiddenScydgySetCache = null;
  3259. $this->success('操作成功', '', $result);
  3260. }
  3261. /**
  3262. * 整单采购确认(多道工序一次提交)
  3263. */
  3264. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3265. {
  3266. $decoded = json_decode($batchRaw, true);
  3267. if (!is_array($decoded) || $decoded === []) {
  3268. $this->error('提交数据无效');
  3269. }
  3270. $picks = [];
  3271. foreach ($decoded as $item) {
  3272. if (!is_array($item)) {
  3273. continue;
  3274. }
  3275. $sid = (int)($item['scydgy_id'] ?? 0);
  3276. if (!$this->isValidScydgyRowId($sid)) {
  3277. continue;
  3278. }
  3279. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3280. if (!is_array($sel)) {
  3281. $sel = [(int)$sel];
  3282. }
  3283. $unsel = $item['unselected_ids'] ?? [];
  3284. if (!is_array($unsel)) {
  3285. $unsel = json_decode((string)$unsel, true);
  3286. $unsel = is_array($unsel) ? $unsel : [];
  3287. }
  3288. $picks[] = [
  3289. 'scydgy_id' => $sid,
  3290. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3291. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3292. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3293. ];
  3294. }
  3295. if ($picks === []) {
  3296. $this->error('提交数据无效');
  3297. }
  3298. Db::startTrans();
  3299. $results = [];
  3300. try {
  3301. foreach ($picks as $pick) {
  3302. $results[] = $this->runPurchaseConfirmPick(
  3303. (int)$pick['scydgy_id'],
  3304. $pick['selected_ids'],
  3305. $pick['unselected_ids'],
  3306. (int)$pick['purchase_order_id'],
  3307. false,
  3308. false
  3309. );
  3310. }
  3311. Db::commit();
  3312. } catch (\Throwable $e) {
  3313. Db::rollback();
  3314. $msg = $e->getMessage();
  3315. $this->error($msg !== '' ? $msg : '提交失败');
  3316. }
  3317. try {
  3318. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3319. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3320. } catch (\Throwable $e) {
  3321. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3322. }
  3323. $this->pickHiddenScydgySetCache = null;
  3324. $this->success('操作成功', '', ['batch' => $results]);
  3325. }
  3326. /**
  3327. * @return array<string, mixed>
  3328. */
  3329. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3330. {
  3331. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3332. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3333. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3334. $scydgyId = (string)$sid;
  3335. if ($selectedIds === []) {
  3336. throw new \InvalidArgumentException('请至少勾选一条明细');
  3337. }
  3338. $inter = array_intersect($selectedIds, $unselectedIds);
  3339. if ($inter !== []) {
  3340. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3341. }
  3342. $allIds = $this->purchaseOrderDetail($sid);
  3343. if ($allIds === []) {
  3344. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3345. }
  3346. foreach ($selectedIds as $id) {
  3347. if (!in_array($id, $allIds, true)) {
  3348. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3349. }
  3350. }
  3351. foreach ($unselectedIds as $id) {
  3352. if (!in_array($id, $allIds, true)) {
  3353. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3354. }
  3355. }
  3356. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3357. sort($union, SORT_NUMERIC);
  3358. $expect = $allIds;
  3359. sort($expect, SORT_NUMERIC);
  3360. if ($union !== $expect) {
  3361. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3362. }
  3363. if ($manageTransaction) {
  3364. Db::startTrans();
  3365. }
  3366. try {
  3367. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3368. $aff = 0;
  3369. try {
  3370. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3371. } catch (\Throwable $e) {
  3372. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3373. }
  3374. if ($aff < 1) {
  3375. throw new \Exception('更新选中状态失败');
  3376. }
  3377. $poPayload = [
  3378. 'status' => ProcuremenStatus::PO_COMPLETED,
  3379. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3380. ];
  3381. if ($purchaseOrderId > 0) {
  3382. $poAff = (int)Db::table('purchase_order')
  3383. ->where('id', $purchaseOrderId)
  3384. ->where('scydgy_id', $sid)
  3385. ->update($poPayload);
  3386. if ($poAff < 1) {
  3387. throw new \Exception('主表订单不存在或与工序行不匹配');
  3388. }
  3389. } else {
  3390. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3391. if ($poAff < 1) {
  3392. throw new \Exception('未找到');
  3393. }
  3394. }
  3395. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3396. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3397. if ($manageTransaction) {
  3398. Db::commit();
  3399. }
  3400. } catch (\Throwable $e) {
  3401. if ($manageTransaction) {
  3402. Db::rollback();
  3403. }
  3404. throw $e;
  3405. }
  3406. $poIdFinal = $purchaseOrderId;
  3407. if ($poIdFinal <= 0) {
  3408. try {
  3409. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3410. if (is_array($rpo)) {
  3411. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3412. }
  3413. } catch (\Throwable $e) {
  3414. $poIdFinal = 0;
  3415. }
  3416. }
  3417. $pickNames = [];
  3418. foreach ($selectedIds as $pid) {
  3419. $dr = $this->purchaseOrderDetai($sid, $pid);
  3420. $nm = trim((string)($dr['company_name'] ?? ''));
  3421. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3422. }
  3423. $this->addOrderLog(
  3424. $sid,
  3425. 'purchase_confirm',
  3426. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3427. $poIdFinal > 0 ? $poIdFinal : null
  3428. );
  3429. if ($sendNotifications) {
  3430. try {
  3431. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3432. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3433. 'scydgy_id' => $sid,
  3434. 'selected_ids' => $selectedIds,
  3435. 'unselected_ids' => $unselectedIds,
  3436. 'purchase_order_id' => $purchaseOrderId,
  3437. ]]);
  3438. } catch (\Throwable $e) {
  3439. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3440. }
  3441. }
  3442. Log::write(sprintf(
  3443. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3444. $scydgyId,
  3445. $purchaseOrderId,
  3446. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3447. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3448. ), 'notice');
  3449. $pdfPublicPath = '';
  3450. try {
  3451. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3452. } catch (\Throwable $e) {
  3453. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3454. }
  3455. return [
  3456. 'scydgy_id' => $scydgyId,
  3457. 'purchase_order_id' => $purchaseOrderId,
  3458. 'selected_ids' => $selectedIds,
  3459. 'unselected_ids' => $unselectedIds,
  3460. 'purchase_confirm_pdf' => $pdfPublicPath,
  3461. ];
  3462. }
  3463. /**
  3464. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3465. *
  3466. * @param int[]|string[] $scydgyIds
  3467. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3468. */
  3469. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3470. {
  3471. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3472. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3473. if ($scydgyIds === []) {
  3474. return $empty;
  3475. }
  3476. $pos = [];
  3477. try {
  3478. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3479. } catch (\Throwable $e) {
  3480. $rows = [];
  3481. }
  3482. if (is_array($rows)) {
  3483. foreach ($rows as $po) {
  3484. if (is_array($po)) {
  3485. $pos[] = $po;
  3486. }
  3487. }
  3488. }
  3489. if ($pos === []) {
  3490. return $empty;
  3491. }
  3492. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3493. return [
  3494. 'ccydh' => $ccydh,
  3495. 'pos' => $pos,
  3496. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3497. ];
  3498. }
  3499. /**
  3500. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3501. *
  3502. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3503. * @param array<int, array<string, mixed>> $picks
  3504. */
  3505. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3506. {
  3507. if ($picks === []) {
  3508. return;
  3509. }
  3510. $fallbackDetailId = 0;
  3511. $winners = [];
  3512. $losers = [];
  3513. foreach ($picks as $pick) {
  3514. if (!is_array($pick)) {
  3515. continue;
  3516. }
  3517. $sid = (int)($pick['scydgy_id'] ?? 0);
  3518. if (!$this->isValidScydgyRowId($sid)) {
  3519. continue;
  3520. }
  3521. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3522. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3523. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3524. $fallbackDetailId = (int)$selectedIds[0];
  3525. }
  3526. foreach ($selectedIds as $pid) {
  3527. $dr = $this->purchaseOrderDetai($sid, $pid);
  3528. if (!is_array($dr)) {
  3529. continue;
  3530. }
  3531. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3532. }
  3533. foreach ($unselectedIds as $pid) {
  3534. $dr = $this->purchaseOrderDetai($sid, $pid);
  3535. if (!is_array($dr)) {
  3536. continue;
  3537. }
  3538. $key = $this->notifySupplierDedupeKey($dr);
  3539. if (!isset($winners[$key])) {
  3540. $losers[$key] = $dr;
  3541. }
  3542. }
  3543. }
  3544. if ($winners === [] && $losers === []) {
  3545. return;
  3546. }
  3547. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3548. $sendSmsSafe = function ($phone, $content) {
  3549. $phone = trim((string)$phone);
  3550. if ($phone === '') {
  3551. return;
  3552. }
  3553. try {
  3554. $this->smsbao($phone, $content);
  3555. } catch (\Throwable $e) {
  3556. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3557. }
  3558. };
  3559. foreach ($winners as $dr) {
  3560. $cname = trim((string)($dr['company_name'] ?? ''));
  3561. $ph = trim((string)($dr['phone'] ?? ''));
  3562. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3563. 'company_name' => $cname,
  3564. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3565. 'phone' => $ph,
  3566. ]));
  3567. $sendSmsSafe($ph, $sms);
  3568. }
  3569. foreach ($losers as $dr) {
  3570. $cname = trim((string)($dr['company_name'] ?? ''));
  3571. $ph = trim((string)($dr['phone'] ?? ''));
  3572. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3573. 'company_name' => $cname,
  3574. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3575. 'phone' => $ph,
  3576. ]));
  3577. $sendSmsSafe($ph, $sms);
  3578. }
  3579. }
  3580. /**
  3581. * 短信去重键:优先手机号,否则公司名
  3582. */
  3583. protected function notifySupplierDedupeKey(array $detailRow): string
  3584. {
  3585. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  3586. if ($ph !== '') {
  3587. return 'p:' . $ph;
  3588. }
  3589. $cn = trim((string)($detailRow['company_name'] ?? ''));
  3590. return 'c:' . $cn;
  3591. }
  3592. /**
  3593. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3594. *
  3595. * @param int[] $detailIds
  3596. */
  3597. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3598. {
  3599. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3600. if ($detailIds === []) {
  3601. return;
  3602. }
  3603. $payload = ['status_name' => $statusName];
  3604. try {
  3605. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3606. } catch (\Throwable $e) {
  3607. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3608. }
  3609. }
  3610. /**
  3611. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3612. */
  3613. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3614. {
  3615. try {
  3616. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3617. } catch (\Throwable $e) {
  3618. return;
  3619. }
  3620. if (!is_array($rows)) {
  3621. return;
  3622. }
  3623. foreach ($rows as $dr) {
  3624. if (!is_array($dr)) {
  3625. continue;
  3626. }
  3627. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3628. if ($id <= 0) {
  3629. continue;
  3630. }
  3631. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3632. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3633. try {
  3634. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3635. } catch (\Throwable $e) {
  3636. }
  3637. }
  3638. }
  3639. /**
  3640. * @param array<string, mixed> $detailRow
  3641. */
  3642. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3643. {
  3644. $am = $detailRow['amount'] ?? null;
  3645. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3646. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3647. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3648. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3649. }
  3650. /**
  3651. * @return int[]
  3652. */
  3653. protected function purchaseOrderDetail(int $scydgyId): array
  3654. {
  3655. if (!$this->isValidScydgyRowId($scydgyId)) {
  3656. return [];
  3657. }
  3658. try {
  3659. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3660. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3661. $list = $listQuery->select();
  3662. } catch (\Throwable $e) {
  3663. return [];
  3664. }
  3665. if (!is_array($list)) {
  3666. return [];
  3667. }
  3668. $ids = [];
  3669. foreach ($list as $r) {
  3670. if (!is_array($r)) {
  3671. continue;
  3672. }
  3673. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3674. if ($pk > 0) {
  3675. $ids[] = $pk;
  3676. }
  3677. }
  3678. return array_values(array_unique($ids));
  3679. }
  3680. /**
  3681. * 获取当前登录用户信息 [id, 展示名]
  3682. */
  3683. protected function GetUseName(): array
  3684. {
  3685. $id = 0;
  3686. $name = '';
  3687. try {
  3688. if ($this->auth && $this->auth->isLogin()) {
  3689. $u = $this->auth->getUserInfo();
  3690. if (is_array($u)) {
  3691. $id = (int)($u['id'] ?? 0);
  3692. $name = trim((string)($u['nickname'] ?? ''));
  3693. if ($name === '') {
  3694. $name = trim((string)($u['username'] ?? ''));
  3695. }
  3696. }
  3697. }
  3698. } catch (\Throwable $e) {
  3699. }
  3700. if ($name === '') {
  3701. $name = '未知用户';
  3702. }
  3703. return [$id, $name];
  3704. }
  3705. /**
  3706. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3707. */
  3708. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3709. {
  3710. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3711. }
  3712. /**
  3713. * 按主键取一条
  3714. */
  3715. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3716. {
  3717. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3718. return [];
  3719. }
  3720. try {
  3721. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3722. if (is_array($one)) {
  3723. return $one;
  3724. }
  3725. } catch (\Throwable $e) {
  3726. }
  3727. try {
  3728. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3729. if (is_array($one)) {
  3730. return $one;
  3731. }
  3732. } catch (\Throwable $e) {
  3733. }
  3734. return [];
  3735. }
  3736. /**
  3737. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3738. */
  3739. protected function formatProcuremenDetailTime($v): string
  3740. {
  3741. if ($v === null || $v === '') {
  3742. return '';
  3743. }
  3744. if (is_numeric($v) && (int)$v > 946684800) {
  3745. return date('Y-m-d H:i:s', (int)$v);
  3746. }
  3747. return ProcuremenTime::formatDisplayDateTime($v);
  3748. }
  3749. /**
  3750. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3751. */
  3752. protected function formatDeliveryYmd($v): string
  3753. {
  3754. if ($v === null || $v === '') {
  3755. return '';
  3756. }
  3757. $s = trim((string)$v);
  3758. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3759. return '';
  3760. }
  3761. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  3762. return $m[1];
  3763. }
  3764. $ts = strtotime($s);
  3765. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  3766. }
  3767. /**
  3768. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  3769. */
  3770. protected function detailRowSupplierOperated(array $r): bool
  3771. {
  3772. $am = $r['amount'] ?? null;
  3773. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3774. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3775. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3776. return $okAmt || $okDel;
  3777. }
  3778. /**
  3779. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  3780. */
  3781. protected function resolveDetailSupplierOperTime(array $r): string
  3782. {
  3783. if (!$this->detailRowSupplierOperated($r)) {
  3784. return '';
  3785. }
  3786. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  3787. if ($t !== '') {
  3788. return $t;
  3789. }
  3790. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  3791. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  3792. continue;
  3793. }
  3794. $t = $this->formatProcuremenDetailTime($r[$col]);
  3795. if ($t !== '') {
  3796. return $t;
  3797. }
  3798. }
  3799. return '';
  3800. }
  3801. /**
  3802. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  3803. */
  3804. protected function detailRowSupplierAccepted(array $r): bool
  3805. {
  3806. $am = $r['amount'] ?? null;
  3807. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3808. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3809. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3810. return $okAmt && $okDel;
  3811. }
  3812. /**
  3813. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  3814. */
  3815. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  3816. {
  3817. if ($detailCount > 0) {
  3818. return true;
  3819. }
  3820. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  3821. return true;
  3822. }
  3823. $pickTime = trim((string)($main['pick_time'] ?? ''));
  3824. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  3825. return true;
  3826. }
  3827. return false;
  3828. }
  3829. /**
  3830. * 下发时间:优先 pick_time,其次首条下发明细时间
  3831. */
  3832. protected function resolveProcuremenIssueTime(array $main, array $details): string
  3833. {
  3834. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  3835. if ($issueTime !== '') {
  3836. return $issueTime;
  3837. }
  3838. foreach ($details as $dr) {
  3839. if (!is_array($dr)) {
  3840. continue;
  3841. }
  3842. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3843. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  3844. $issueTime = $t;
  3845. }
  3846. }
  3847. if ($issueTime !== '') {
  3848. return $issueTime;
  3849. }
  3850. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3851. }
  3852. /**
  3853. * 直接点「完结」时间:优先操作记录 mark_complete
  3854. */
  3855. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  3856. {
  3857. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  3858. }
  3859. /**
  3860. * 操作记录时间(取指定 action 最近一条)
  3861. *
  3862. * @param string|array<int, string> $actions
  3863. */
  3864. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  3865. {
  3866. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  3867. }
  3868. /**
  3869. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  3870. *
  3871. * @param array $main purchase_order 一行
  3872. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  3873. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  3874. */
  3875. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  3876. {
  3877. $issueCnt = count($details);
  3878. $acceptCnt = 0;
  3879. $pickedName = '';
  3880. $pickedTime = '';
  3881. foreach ($details as $dr) {
  3882. if (!is_array($dr)) {
  3883. continue;
  3884. }
  3885. if ($this->detailRowSupplierAccepted($dr)) {
  3886. $acceptCnt++;
  3887. }
  3888. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3889. if ($pickedName === '') {
  3890. $pickedName = trim((string)($dr['company_name'] ?? ''));
  3891. }
  3892. if ($pickedTime === '') {
  3893. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  3894. if ($pickedTime === '') {
  3895. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3896. }
  3897. }
  3898. }
  3899. }
  3900. $hasMain = $main !== [];
  3901. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  3902. if ($poTime === '') {
  3903. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  3904. }
  3905. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  3906. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  3907. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  3908. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  3909. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  3910. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  3911. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  3912. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  3913. $supplierTime = '';
  3914. if ($acceptCnt > 0) {
  3915. foreach ($details as $dr) {
  3916. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  3917. continue;
  3918. }
  3919. $t = $this->resolveDetailSupplierOperTime($dr);
  3920. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  3921. $supplierTime = $t;
  3922. }
  3923. }
  3924. }
  3925. $directComplete = ($mainCompleted && !$issued);
  3926. $doneTime = '';
  3927. if ($mainCompleted) {
  3928. if ($directComplete) {
  3929. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  3930. }
  3931. if ($doneTime === '') {
  3932. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3933. }
  3934. if ($doneTime === '') {
  3935. foreach ($details as $dr) {
  3936. if (!is_array($dr)) {
  3937. continue;
  3938. }
  3939. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  3940. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  3941. $doneTime = $t;
  3942. }
  3943. }
  3944. }
  3945. if ($doneTime === '') {
  3946. $doneTime = $poTime;
  3947. }
  3948. if ($confirmApproveTime !== '') {
  3949. $doneTime = $confirmApproveTime;
  3950. }
  3951. }
  3952. if ($directComplete) {
  3953. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  3954. $step1Done = $hasMain;
  3955. $step2Done = false;
  3956. $step3Done = false;
  3957. $step4Done = false;
  3958. $step5Done = false;
  3959. $step6Done = true;
  3960. } else {
  3961. $step1Done = $issued;
  3962. $step2Done = $issued;
  3963. $step3Done = $acceptCnt > 0;
  3964. $step4Done = $wflowPendingApproval;
  3965. if (!$step4Done) {
  3966. foreach ($details as $dr) {
  3967. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3968. $step4Done = true;
  3969. break;
  3970. }
  3971. }
  3972. }
  3973. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  3974. $step6Done = $mainCompleted;
  3975. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  3976. if ($mainCompleted && $issued) {
  3977. $step3Done = true;
  3978. $step4Done = true;
  3979. $step5Done = true;
  3980. if ($supplierTime === '') {
  3981. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3982. if ($fillT !== '') {
  3983. $supplierTime = $fillT;
  3984. }
  3985. }
  3986. if ($pickedTime === '') {
  3987. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3988. if ($fillT !== '') {
  3989. $pickedTime = $fillT;
  3990. }
  3991. }
  3992. if ($auditSelectTime === '') {
  3993. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3994. if ($fillT !== '') {
  3995. $auditSelectTime = $fillT;
  3996. }
  3997. }
  3998. if ($confirmApproveTime === '') {
  3999. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4000. if ($fillT !== '') {
  4001. $confirmApproveTime = $fillT;
  4002. }
  4003. }
  4004. }
  4005. }
  4006. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4007. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4008. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4009. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4010. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4011. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4012. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4013. $steps = [
  4014. [
  4015. 'title' => '未发',
  4016. 'subtitle' => '',
  4017. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  4018. 'done' => $step1Done,
  4019. ],
  4020. [
  4021. 'title' => '下发',
  4022. 'subtitle' => '',
  4023. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  4024. 'done' => $step2Done,
  4025. ],
  4026. [
  4027. 'title' => '供应商接单',
  4028. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4029. 'time' => '',
  4030. 'done' => $step3Done,
  4031. ],
  4032. [
  4033. 'title' => '待确认',
  4034. 'subtitle' => $step4Done
  4035. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4036. : ($issued ? '待选供应商' : ''),
  4037. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  4038. 'done' => $step4Done,
  4039. ],
  4040. [
  4041. 'title' => '待审批',
  4042. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4043. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  4044. 'done' => $step5Done,
  4045. ],
  4046. [
  4047. 'title' => '已完结',
  4048. 'subtitle' => '',
  4049. 'time' => $step6Done ? $doneTime : '',
  4050. 'done' => $step6Done,
  4051. ],
  4052. ];
  4053. $currentIdx = count($steps) - 1;
  4054. if (!$directComplete) {
  4055. foreach ($steps as $i => $s) {
  4056. if (!$s['done']) {
  4057. $currentIdx = $i;
  4058. break;
  4059. }
  4060. }
  4061. }
  4062. $nSteps = count($steps);
  4063. foreach ($steps as $idx => &$s) {
  4064. $s['current'] = ($idx === $currentIdx);
  4065. if ($idx === 0) {
  4066. $s['pdf_left_bg'] = '';
  4067. } else {
  4068. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4069. }
  4070. if ($idx >= $nSteps - 1) {
  4071. $s['pdf_right_bg'] = '';
  4072. } else {
  4073. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4074. }
  4075. }
  4076. unset($s);
  4077. $labelMap = [
  4078. 'CCYDH' => '订单号',
  4079. 'CYJMC' => '印件名称',
  4080. 'CCLBMMC' => '承揽部门',
  4081. 'CGYMC' => '工序名称',
  4082. 'CDW' => '单位',
  4083. 'NGZL' => '工作量',
  4084. 'CDF' => '单价',
  4085. 'cGzzxMc' => '工作中心',
  4086. 'MBZ' => '备注',
  4087. 'This_quantity' => '本次数量',
  4088. 'ceilingPrice' => '最高限价',
  4089. ];
  4090. $orderSummary = [];
  4091. foreach ($labelMap as $key => $lab) {
  4092. if (!array_key_exists($key, $main)) {
  4093. continue;
  4094. }
  4095. $val = $main[$key];
  4096. if ($val === null) {
  4097. $val = '';
  4098. } elseif (!is_scalar($val)) {
  4099. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4100. } else {
  4101. $val = (string)$val;
  4102. }
  4103. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4104. }
  4105. $orderSummaryGrid = [];
  4106. $n = count($orderSummary);
  4107. for ($i = 0; $i < $n; $i += 2) {
  4108. $left = $orderSummary[$i];
  4109. $hasRight = ($i + 1) < $n;
  4110. $orderSummaryGrid[] = [
  4111. 'l1' => $left['label'],
  4112. 'v1' => $left['value'],
  4113. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4114. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4115. ];
  4116. }
  4117. return [
  4118. 'steps' => $steps,
  4119. 'orderSummary' => $orderSummary,
  4120. 'orderSummaryGrid' => $orderSummaryGrid,
  4121. 'detailRows' => $details,
  4122. ];
  4123. }
  4124. /**
  4125. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4126. *
  4127. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4128. */
  4129. protected function prepareProcuremenDetailsView(string $ids): array
  4130. {
  4131. $main = [];
  4132. try {
  4133. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4134. $main = is_array($one) ? $one : [];
  4135. } catch (\Throwable $e) {
  4136. $main = [];
  4137. }
  4138. $details = [];
  4139. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4140. if ($mergeRows === []) {
  4141. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4142. if ($mergeRows === [] && $main !== []) {
  4143. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4144. }
  4145. }
  4146. $detailSidList = [];
  4147. $anchorSid = (int)$ids;
  4148. if ($anchorSid !== 0) {
  4149. $detailSidList[$anchorSid] = true;
  4150. }
  4151. foreach ($mergeRows as $mr) {
  4152. if (!is_array($mr)) {
  4153. continue;
  4154. }
  4155. $sid = $this->extractScydgyRowId($mr);
  4156. if ($sid !== 0) {
  4157. $detailSidList[$sid] = true;
  4158. }
  4159. }
  4160. try {
  4161. if ($detailSidList !== []) {
  4162. $details = Db::table('purchase_order_detail')
  4163. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4164. ->order('id', 'asc')
  4165. ->select();
  4166. }
  4167. } catch (\Throwable $e) {
  4168. $details = [];
  4169. }
  4170. if (!is_array($details)) {
  4171. $details = [];
  4172. }
  4173. foreach ($details as &$r) {
  4174. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4175. $r['id'] = $r['ID'];
  4176. }
  4177. if (isset($r['createtime'])) {
  4178. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4179. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4180. } else {
  4181. $r['createtime_text'] = (string)$r['createtime'];
  4182. }
  4183. } else {
  4184. $r['createtime_text'] = '';
  4185. }
  4186. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4187. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4188. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4189. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4190. if (is_array($r)) {
  4191. $r = $this->maskSupplierContactFields($r);
  4192. }
  4193. }
  4194. unset($r);
  4195. $activeDetails = [];
  4196. foreach ($details as $r) {
  4197. if (is_array($r) && empty($r['is_void'])) {
  4198. $activeDetails[] = $r;
  4199. }
  4200. }
  4201. $operLogs = [];
  4202. try {
  4203. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  4204. } catch (\Throwable $e) {
  4205. $operLogs = [];
  4206. }
  4207. if (!is_array($operLogs)) {
  4208. $operLogs = [];
  4209. }
  4210. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4211. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4212. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4213. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4214. if ($ccydh === '') {
  4215. foreach ($details as $r) {
  4216. if (!is_array($r)) {
  4217. continue;
  4218. }
  4219. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4220. if ($ccydh !== '') {
  4221. break;
  4222. }
  4223. }
  4224. }
  4225. $this->view->assign('ccydh', $ccydh);
  4226. $this->view->assign('steps', $bundle['steps']);
  4227. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4228. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4229. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4230. $this->view->assign('processCount', count($mergeRows));
  4231. $this->view->assign('detailRows', $details);
  4232. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4233. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4234. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4235. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4236. $this->view->assign('operLogs', $operLogs);
  4237. return [
  4238. 'ok' => $main !== [] || $details !== [],
  4239. 'ccydh' => $ccydh,
  4240. ];
  4241. }
  4242. /**
  4243. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4244. */
  4245. public function details()
  4246. {
  4247. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4248. if (is_array($ids)) {
  4249. $ids = isset($ids[0]) ? $ids[0] : '';
  4250. }
  4251. $ids = trim((string)$ids);
  4252. if ($ids === '') {
  4253. $this->error(__('Invalid parameters'));
  4254. }
  4255. $this->assertManualOrderDetailsViewable((int)$ids);
  4256. $this->prepareProcuremenDetailsView($ids);
  4257. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4258. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4259. $this->view->engine->layout(false);
  4260. try {
  4261. return $this->view->fetch('procuremen/details_dialog_shell');
  4262. } finally {
  4263. if ($restoreLayout) {
  4264. $this->view->engine->layout($restoreLayout);
  4265. }
  4266. }
  4267. }
  4268. /**
  4269. * 解析合并审核工序行(订单号须一致,且均未协助)
  4270. *
  4271. * @return array<int, array<string, mixed>>
  4272. */
  4273. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4274. {
  4275. $primary = json_decode($rowJson, true);
  4276. if (!is_array($primary)) {
  4277. $this->error(__('Invalid parameters'));
  4278. }
  4279. $merge = json_decode($mergeRowsJson, true);
  4280. if (!is_array($merge) || $merge === []) {
  4281. $merge = [$primary];
  4282. }
  4283. $seen = [];
  4284. $out = [];
  4285. foreach ($merge as $r) {
  4286. if (!is_array($r)) {
  4287. continue;
  4288. }
  4289. $id = $this->extractScydgyRowId($r);
  4290. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4291. continue;
  4292. }
  4293. $seen[$id] = true;
  4294. $out[] = $r;
  4295. }
  4296. if ($out === []) {
  4297. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4298. }
  4299. $ccydh = null;
  4300. foreach ($out as $r) {
  4301. $dh = trim((string)($r['CCYDH'] ?? ''));
  4302. if ($ccydh === null) {
  4303. $ccydh = $dh;
  4304. } elseif ($dh !== $ccydh) {
  4305. $this->error('合并审核要求所选行的订单号一致');
  4306. }
  4307. }
  4308. $ids = [];
  4309. foreach ($out as $r) {
  4310. $id = $this->extractScydgyRowId($r);
  4311. if ($this->isValidScydgyRowId($id)) {
  4312. $ids[$id] = true;
  4313. }
  4314. }
  4315. $poBySid = [];
  4316. $detCntBySid = [];
  4317. if ($ids !== []) {
  4318. $idList = array_keys($ids);
  4319. try {
  4320. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4321. if (is_array($poList)) {
  4322. foreach ($poList as $po) {
  4323. if (!is_array($po)) {
  4324. continue;
  4325. }
  4326. $sid = (int)($po['scydgy_id'] ?? 0);
  4327. if ($this->isValidScydgyRowId($sid)) {
  4328. $poBySid[$sid] = $po;
  4329. }
  4330. }
  4331. }
  4332. } catch (\Throwable $e) {
  4333. }
  4334. try {
  4335. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4336. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4337. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4338. if (is_array($detRows)) {
  4339. foreach ($detRows as $dr) {
  4340. if (!is_array($dr)) {
  4341. continue;
  4342. }
  4343. $sid = (int)($dr['scydgy_id'] ?? 0);
  4344. if ($this->isValidScydgyRowId($sid)) {
  4345. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4346. }
  4347. }
  4348. }
  4349. } catch (\Throwable $e) {
  4350. }
  4351. }
  4352. foreach ($out as $r) {
  4353. $id = $this->extractScydgyRowId($r);
  4354. if (!$this->isValidScydgyRowId($id)) {
  4355. continue;
  4356. }
  4357. $po = $poBySid[$id] ?? null;
  4358. if (!is_array($po)) {
  4359. continue;
  4360. }
  4361. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4362. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4363. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4364. }
  4365. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4366. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4367. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4368. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4369. }
  4370. }
  4371. return $out;
  4372. }
  4373. /**
  4374. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4375. */
  4376. protected function maskSupplierContactFields(array $item): array
  4377. {
  4378. if (array_key_exists('email', $item)) {
  4379. $item['email'] = mask_email((string)$item['email']);
  4380. }
  4381. if (array_key_exists('phone', $item)) {
  4382. $item['phone'] = mask_phone((string)$item['phone']);
  4383. }
  4384. return $item;
  4385. }
  4386. /**
  4387. * @param array<int, array<string, mixed>> $list
  4388. * @return array<int, array<string, mixed>>
  4389. */
  4390. protected function maskSupplierContactList(array $list): array
  4391. {
  4392. $out = [];
  4393. foreach ($list as $item) {
  4394. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4395. }
  4396. return $out;
  4397. }
  4398. /**
  4399. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4400. *
  4401. * @return array<string, string>|null
  4402. */
  4403. protected function buildCustomerContactPayloadFromRow($row): ?array
  4404. {
  4405. if (!is_array($row)) {
  4406. return null;
  4407. }
  4408. $norm = [];
  4409. foreach ($row as $k => $v) {
  4410. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4411. }
  4412. $row = $norm;
  4413. $st = $row['status'] ?? '';
  4414. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4415. return null;
  4416. }
  4417. $companyName = '';
  4418. foreach (['company_name', 'name'] as $nk) {
  4419. if (!empty($row[$nk])) {
  4420. $companyName = trim((string)$row[$nk]);
  4421. break;
  4422. }
  4423. }
  4424. if ($companyName === '') {
  4425. return null;
  4426. }
  4427. $username = '';
  4428. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4429. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4430. $username = trim((string)$row[$uk]);
  4431. break;
  4432. }
  4433. }
  4434. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4435. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4436. if ($phone === '' && isset($row['account'])) {
  4437. $phone = trim((string)$row['account']);
  4438. }
  4439. if ($phone === '' && isset($row['mobile'])) {
  4440. $phone = trim((string)$row['mobile']);
  4441. }
  4442. if ($email === '' && $phone === '') {
  4443. return null;
  4444. }
  4445. $category = '';
  4446. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4447. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4448. $category = trim((string)$row[$ck]);
  4449. break;
  4450. }
  4451. }
  4452. return [
  4453. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4454. 'name' => $companyName,
  4455. 'company_name' => $companyName,
  4456. 'username' => $username,
  4457. 'email' => $email,
  4458. 'phone' => $phone,
  4459. 'category' => $category,
  4460. 'company_type' => $category,
  4461. ];
  4462. }
  4463. /**
  4464. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4465. */
  4466. protected function resolveCustomerContactById(string $id): ?array
  4467. {
  4468. $id = trim($id);
  4469. if ($id === '' || !ctype_digit($id)) {
  4470. return null;
  4471. }
  4472. try {
  4473. $row = Db::table('customer')->where('id', (int)$id)->find();
  4474. } catch (\Throwable $e) {
  4475. return null;
  4476. }
  4477. return $this->buildCustomerContactPayloadFromRow($row);
  4478. }
  4479. /**
  4480. * 按供应商名称解析联系信息(兼容旧提交数据)
  4481. */
  4482. protected function resolveCustomerContactByCompanyName(string $name): ?array
  4483. {
  4484. $name = trim($name);
  4485. if ($name === '') {
  4486. return null;
  4487. }
  4488. try {
  4489. $row = Db::table('customer')
  4490. ->where(function ($q) use ($name) {
  4491. $q->where('company_name', $name)->whereOr('name', $name);
  4492. })
  4493. ->order('id', 'desc')
  4494. ->find();
  4495. } catch (\Throwable $e) {
  4496. return null;
  4497. }
  4498. return $this->buildCustomerContactPayloadFromRow($row);
  4499. }
  4500. /**
  4501. * 规范化下发/确认时勾选的供应商
  4502. *
  4503. * @param array<int, mixed> $companies
  4504. * @return array<int, array<string, string>>
  4505. */
  4506. protected function normalizePickCompanies(array $companies): array
  4507. {
  4508. $out = [];
  4509. foreach ($companies as $c) {
  4510. if (!is_array($c)) {
  4511. continue;
  4512. }
  4513. $resolved = null;
  4514. $cid = trim((string)($c['id'] ?? ''));
  4515. if ($cid !== '') {
  4516. $resolved = $this->resolveCustomerContactById($cid);
  4517. }
  4518. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  4519. if ($resolved === null && $name !== '') {
  4520. $resolved = $this->resolveCustomerContactByCompanyName($name);
  4521. }
  4522. if ($resolved === null) {
  4523. continue;
  4524. }
  4525. $out[] = $resolved;
  4526. }
  4527. return $out;
  4528. }
  4529. /**
  4530. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  4531. *
  4532. * @param array<int, array<string, mixed>> $pool
  4533. * @return array<int, array<string, mixed>>
  4534. */
  4535. protected function collapseProcuremenPoolByOrder(array $pool): array
  4536. {
  4537. if ($pool === []) {
  4538. return [];
  4539. }
  4540. $groups = [];
  4541. foreach ($pool as $row) {
  4542. if (!is_array($row)) {
  4543. continue;
  4544. }
  4545. $dh = trim((string)($row['CCYDH'] ?? ''));
  4546. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  4547. if (!isset($groups[$key])) {
  4548. $groups[$key] = [];
  4549. }
  4550. $groups[$key][] = $row;
  4551. }
  4552. $out = [];
  4553. foreach ($groups as $ccydh => $rows) {
  4554. if ($rows === []) {
  4555. continue;
  4556. }
  4557. usort($rows, function ($a, $b) {
  4558. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  4559. });
  4560. $head = $rows[0];
  4561. $gymcList = [];
  4562. foreach ($rows as $r) {
  4563. $g = trim((string)($r['CGYMC'] ?? ''));
  4564. if ($g !== '' && !in_array($g, $gymcList, true)) {
  4565. $gymcList[] = $g;
  4566. }
  4567. }
  4568. $merged = $head;
  4569. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  4570. $merged['process_count'] = count($rows);
  4571. $merged['_order_merge_rows'] = $rows;
  4572. if (count($rows) > 1) {
  4573. $merged['CGYMC'] = implode('、', $gymcList);
  4574. }
  4575. $mergedPickTime = '';
  4576. foreach ($rows as $r) {
  4577. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  4578. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  4579. $mergedPickTime = $t;
  4580. }
  4581. }
  4582. if ($mergedPickTime !== '') {
  4583. $merged['pick_time'] = $mergedPickTime;
  4584. }
  4585. $out[] = $merged;
  4586. }
  4587. usort($out, function ($a, $b) {
  4588. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  4589. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  4590. if ($ta === $tb) {
  4591. $ida = (int)($a['purchase_order_id'] ?? 0);
  4592. $idb = (int)($b['purchase_order_id'] ?? 0);
  4593. if ($ida !== $idb) {
  4594. return $idb <=> $ida;
  4595. }
  4596. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  4597. }
  4598. if ($ta === '') {
  4599. return 1;
  4600. }
  4601. if ($tb === '') {
  4602. return -1;
  4603. }
  4604. return strcmp($tb, $ta);
  4605. });
  4606. return $out;
  4607. }
  4608. /**
  4609. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  4610. *
  4611. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4612. */
  4613. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  4614. {
  4615. $scydgyId = trim($scydgyId);
  4616. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4617. if ($scydgyId === '') {
  4618. return $empty;
  4619. }
  4620. try {
  4621. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4622. } catch (\Throwable $e) {
  4623. $anchor = null;
  4624. }
  4625. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  4626. return $empty;
  4627. }
  4628. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4629. if ($ccydh === '') {
  4630. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4631. }
  4632. try {
  4633. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4634. } catch (\Throwable $e) {
  4635. $pos = [$anchor];
  4636. }
  4637. if (!is_array($pos) || $pos === []) {
  4638. $pos = [$anchor];
  4639. }
  4640. return [
  4641. 'ccydh' => $ccydh,
  4642. 'pos' => $pos,
  4643. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4644. ];
  4645. }
  4646. /**
  4647. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4648. */
  4649. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4650. {
  4651. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4652. return false;
  4653. }
  4654. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4655. return false;
  4656. }
  4657. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4658. return true;
  4659. }
  4660. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4661. $sid = (int)($po['scydgy_id'] ?? 0);
  4662. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4663. }
  4664. return false;
  4665. }
  4666. /**
  4667. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4668. *
  4669. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4670. */
  4671. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4672. {
  4673. $scydgyId = trim($scydgyId);
  4674. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4675. if ($scydgyId === '') {
  4676. return $empty;
  4677. }
  4678. try {
  4679. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4680. } catch (\Throwable $e) {
  4681. $anchor = null;
  4682. }
  4683. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4684. return $empty;
  4685. }
  4686. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4687. if ($ccydh === '') {
  4688. return [
  4689. 'ccydh' => '',
  4690. 'pos' => [$anchor],
  4691. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  4692. ];
  4693. }
  4694. try {
  4695. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  4696. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  4697. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  4698. } catch (\Throwable $e) {
  4699. $pos = [$anchor];
  4700. }
  4701. if (!is_array($pos) || $pos === []) {
  4702. $pos = [$anchor];
  4703. }
  4704. $pos = array_values(array_filter($pos, function ($po) {
  4705. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  4706. }));
  4707. if ($pos === []) {
  4708. $pos = [$anchor];
  4709. }
  4710. return [
  4711. 'ccydh' => $ccydh,
  4712. 'pos' => $pos,
  4713. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4714. ];
  4715. }
  4716. /**
  4717. * @param array<int, array<string, mixed>> $purchaseOrders
  4718. * @return array<int, array<string, mixed>>
  4719. */
  4720. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  4721. {
  4722. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  4723. $byId = [];
  4724. foreach ($pool as $r) {
  4725. if (!is_array($r)) {
  4726. continue;
  4727. }
  4728. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  4729. if ($this->isValidScydgyRowId($sid)) {
  4730. $byId[$sid] = $r;
  4731. }
  4732. }
  4733. $out = [];
  4734. foreach ($purchaseOrders as $po) {
  4735. if (!is_array($po)) {
  4736. continue;
  4737. }
  4738. $sid = (int)($po['scydgy_id'] ?? 0);
  4739. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  4740. $out[] = $byId[$sid];
  4741. }
  4742. }
  4743. return $out;
  4744. }
  4745. /**
  4746. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  4747. *
  4748. * @return array<int, array<string, mixed>>
  4749. */
  4750. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  4751. {
  4752. $scydgyId = trim($scydgyId);
  4753. if ($scydgyId === '') {
  4754. return [];
  4755. }
  4756. try {
  4757. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4758. } catch (\Throwable $e) {
  4759. $anchor = null;
  4760. }
  4761. if (!is_array($anchor)) {
  4762. return [];
  4763. }
  4764. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  4765. return [];
  4766. }
  4767. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4768. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  4769. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  4770. try {
  4771. $q = Db::table('purchase_order');
  4772. if ($ccydh !== '') {
  4773. $q->where('CCYDH', $ccydh);
  4774. } else {
  4775. $q->where('scydgy_id', $scydgyId);
  4776. }
  4777. if ($isValidPick) {
  4778. $q->where('pick_time', $pickTime);
  4779. }
  4780. $pos = $q->order('scydgy_id', 'asc')->select();
  4781. } catch (\Throwable $e) {
  4782. $pos = [$anchor];
  4783. }
  4784. if (!is_array($pos) || $pos === []) {
  4785. $pos = [$anchor];
  4786. }
  4787. $pos = array_values(array_filter($pos, function ($po) {
  4788. if (!is_array($po)) {
  4789. return false;
  4790. }
  4791. $mr = $po['mod_rq'] ?? null;
  4792. if ($mr === null || $mr === '') {
  4793. return true;
  4794. }
  4795. $mrs = trim((string)$mr);
  4796. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  4797. }));
  4798. if ($pos === []) {
  4799. $pos = [$anchor];
  4800. }
  4801. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  4802. if ($rows === []) {
  4803. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  4804. }
  4805. return $rows;
  4806. }
  4807. /**
  4808. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  4809. *
  4810. * @param array<int, array<string, mixed>> $mergeRows
  4811. * @return array<int, array<string, mixed>>
  4812. */
  4813. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  4814. {
  4815. $list = array_values($mergeRows);
  4816. $n = count($list);
  4817. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  4818. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  4819. $mergeSame = $n > 1 && $orderKey0 !== '';
  4820. if ($mergeSame) {
  4821. foreach ($list as $rr) {
  4822. if (!is_array($rr)) {
  4823. $mergeSame = false;
  4824. break;
  4825. }
  4826. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  4827. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  4828. $mergeSame = false;
  4829. break;
  4830. }
  4831. }
  4832. }
  4833. $out = [];
  4834. foreach ($list as $idx => $r) {
  4835. if (!is_array($r)) {
  4836. continue;
  4837. }
  4838. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  4839. if (is_scalar($qty)) {
  4840. $qty = trim((string)$qty);
  4841. } else {
  4842. $qty = '';
  4843. }
  4844. if ($qty === '') {
  4845. $gzl = $r['NGZL'] ?? '';
  4846. if (is_scalar($gzl)) {
  4847. $qty = trim((string)$gzl);
  4848. }
  4849. }
  4850. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  4851. $sid = $this->extractScydgyRowId($r);
  4852. $out[] = [
  4853. 'seq' => $idx + 1,
  4854. 'scydgy_id' => $sid,
  4855. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  4856. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  4857. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  4858. 'CDW' => trim((string)($r['CDW'] ?? '')),
  4859. 'NGZL' => $r['NGZL'] ?? '',
  4860. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  4861. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  4862. 'CDF' => trim((string)($r['CDF'] ?? '')),
  4863. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  4864. 'show_order_cells' => !$mergeSame || $idx === 0,
  4865. 'order_rowspan' => $mergeSame ? $n : 1,
  4866. ];
  4867. }
  4868. return $out;
  4869. }
  4870. /**
  4871. * 解析金额/数量(去千分位等非数字字符)
  4872. */
  4873. protected function parseProcuremenMoneyNumber($value): ?float
  4874. {
  4875. if ($value === null || $value === '') {
  4876. return null;
  4877. }
  4878. if (is_numeric($value)) {
  4879. return (float)$value;
  4880. }
  4881. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  4882. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  4883. }
  4884. protected function formatProcuremenMoneyDisplay(?float $amount): string
  4885. {
  4886. if ($amount === null) {
  4887. return '';
  4888. }
  4889. return (string)(int)round($amount);
  4890. }
  4891. /**
  4892. * 列表/详情展示:工作量为 0 时显示空
  4893. */
  4894. protected function formatProcuremenWorkloadDisplay($value): string
  4895. {
  4896. if ($value === null || $value === '') {
  4897. return '';
  4898. }
  4899. $s = trim((string)$value);
  4900. if ($s === '') {
  4901. return '';
  4902. }
  4903. if (is_numeric($s) && (float)$s == 0) {
  4904. return '';
  4905. }
  4906. return $s;
  4907. }
  4908. /**
  4909. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  4910. */
  4911. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  4912. {
  4913. foreach ($details as $d) {
  4914. if (!is_array($d)) {
  4915. continue;
  4916. }
  4917. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  4918. $cn = trim((string)($d['company_name'] ?? ''));
  4919. if ($cn !== '') {
  4920. return $cn;
  4921. }
  4922. }
  4923. }
  4924. return trim((string)($main['pick_company_name'] ?? ''));
  4925. }
  4926. /**
  4927. * 详情报价小计:单价 × 本工序本次数量
  4928. */
  4929. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  4930. {
  4931. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  4932. if ($unit === null) {
  4933. return null;
  4934. }
  4935. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  4936. if ($qty === null || $qty <= 0) {
  4937. return null;
  4938. }
  4939. return $unit * $qty;
  4940. }
  4941. /**
  4942. * 详情页:工序小计 + 供应商分组报价与总计
  4943. *
  4944. * @param array<int, array<string, mixed>> $mergeRows
  4945. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  4946. * @return array{
  4947. * process_rows: array,
  4948. * supplier_groups: array,
  4949. * order_total_text: string,
  4950. * order_total_has: bool,
  4951. * selected_company: string
  4952. * }
  4953. */
  4954. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  4955. {
  4956. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  4957. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  4958. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  4959. $qtyBySid = [];
  4960. $gymcBySid = [];
  4961. $orderedSids = [];
  4962. foreach ($mergeRows as $mr) {
  4963. if (!is_array($mr)) {
  4964. continue;
  4965. }
  4966. $sid = $this->extractScydgyRowId($mr);
  4967. if ($sid > 0) {
  4968. $orderedSids[] = $sid;
  4969. }
  4970. $qty = trim((string)($mr['This_quantity'] ?? ''));
  4971. if ($qty === '') {
  4972. $qty = trim((string)($mr['NGZL'] ?? ''));
  4973. }
  4974. $qtyBySid[$sid] = $qty;
  4975. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  4976. }
  4977. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  4978. $detailByCompanySid = [];
  4979. foreach ($details as $d) {
  4980. if (!is_array($d)) {
  4981. continue;
  4982. }
  4983. $cn = trim((string)($d['company_name'] ?? ''));
  4984. $sid = (int)($d['scydgy_id'] ?? 0);
  4985. if ($cn === '' || $sid === 0) {
  4986. continue;
  4987. }
  4988. if (!isset($detailByCompanySid[$cn])) {
  4989. $detailByCompanySid[$cn] = [];
  4990. }
  4991. $detailByCompanySid[$cn][$sid] = $d;
  4992. }
  4993. $supplierGroups = [];
  4994. foreach ($detailByCompanySid as $cn => $bySid) {
  4995. $lines = [];
  4996. $groupTotal = 0.0;
  4997. $groupHas = false;
  4998. $groupVoid = true;
  4999. $usedSids = [];
  5000. $appendLine = function (int $sid, array $d) use (
  5001. &$lines,
  5002. &$groupTotal,
  5003. &$groupHas,
  5004. &$groupVoid,
  5005. $qtyBySid,
  5006. $gymcBySid,
  5007. $quoteVisible
  5008. ) {
  5009. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5010. if (!$isVoid) {
  5011. $groupVoid = false;
  5012. }
  5013. $qtyStr = $qtyBySid[$sid] ?? '';
  5014. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5015. $am = trim((string)($d['amount'] ?? ''));
  5016. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5017. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5018. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5019. $sub = null;
  5020. if (!$isVoid && $amountNum !== null) {
  5021. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5022. }
  5023. $ct = $this->resolveDetailSupplierOperTime($d);
  5024. $line = [
  5025. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5026. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am,
  5027. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5028. 'delivery_ymd' => $deliveryYmd,
  5029. 'amount_filled' => $amountFilled,
  5030. 'delivery_filled' => $deliveryFilled,
  5031. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5032. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5033. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5034. 'is_void' => $isVoid,
  5035. 'oper_time_text' => $ct,
  5036. ];
  5037. if (!$quoteVisible && !$isVoid) {
  5038. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5039. } elseif ($sub !== null) {
  5040. $groupTotal += $sub;
  5041. $groupHas = true;
  5042. }
  5043. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5044. };
  5045. foreach ($orderedSids as $sid) {
  5046. if (!isset($bySid[$sid])) {
  5047. continue;
  5048. }
  5049. $usedSids[$sid] = true;
  5050. $appendLine($sid, $bySid[$sid]);
  5051. }
  5052. foreach ($bySid as $sid => $d) {
  5053. if (isset($usedSids[$sid])) {
  5054. continue;
  5055. }
  5056. $appendLine((int)$sid, $d);
  5057. }
  5058. $firstDetail = null;
  5059. foreach ($bySid as $d) {
  5060. if (is_array($d)) {
  5061. $firstDetail = $d;
  5062. break;
  5063. }
  5064. }
  5065. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5066. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5067. if ($username === '' && $ph !== '') {
  5068. $username = $this->resolveCustomerContactName($ph, $cn);
  5069. }
  5070. $lineCount = count($lines);
  5071. $supplierGroups[] = [
  5072. 'company_name' => $cn,
  5073. 'username' => $username,
  5074. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5075. 'phone' => $ph,
  5076. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5077. 'is_void' => $groupVoid,
  5078. 'lines' => $lines,
  5079. 'line_count' => $lineCount,
  5080. 'display_rowspan'=> $lineCount + ($lineCount > 0 ? 1 : 0),
  5081. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5082. 'has_total' => $lineCount > 0,
  5083. ];
  5084. }
  5085. usort($supplierGroups, function ($a, $b) {
  5086. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5087. return ($a['is_void'] ?? false) ? 1 : -1;
  5088. }
  5089. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5090. return ($a['is_selected'] ?? false) ? -1 : 1;
  5091. }
  5092. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5093. });
  5094. return [
  5095. 'process_rows' => $processRows,
  5096. 'supplier_groups' => $supplierGroups,
  5097. 'order_total_text' => '',
  5098. 'order_total_has' => false,
  5099. 'selected_company' => $selectedCompany,
  5100. ];
  5101. }
  5102. /**
  5103. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5104. */
  5105. protected function buildProcessLinesPlain(array $mergeRows): string
  5106. {
  5107. $lines = [];
  5108. $i = 1;
  5109. foreach ($mergeRows as $r) {
  5110. if (!is_array($r)) {
  5111. continue;
  5112. }
  5113. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5114. $dw = trim((string)($r['CDW'] ?? ''));
  5115. $gzl = trim((string)($r['NGZL'] ?? ''));
  5116. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5117. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5118. if ($dw !== '') {
  5119. $parts[] = '单位:' . $dw;
  5120. }
  5121. if ($gzl !== '') {
  5122. $parts[] = '工作量:' . $gzl;
  5123. }
  5124. if ($qty !== '') {
  5125. $parts[] = '本次数量:' . $qty;
  5126. }
  5127. $lines[] = implode(' ', $parts);
  5128. $i++;
  5129. }
  5130. return implode("\n", $lines);
  5131. }
  5132. /**
  5133. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5134. *
  5135. * @return array<string, string>
  5136. */
  5137. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5138. {
  5139. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5140. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5141. }
  5142. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5143. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5144. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5145. $cyjmc = '';
  5146. foreach ($mergeRows as $mr) {
  5147. if (!is_array($mr)) {
  5148. continue;
  5149. }
  5150. if ($ccydh === '') {
  5151. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5152. }
  5153. if ($cyjmc === '') {
  5154. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5155. }
  5156. }
  5157. if ($pos !== []) {
  5158. $firstPo = $pos[0];
  5159. if (is_array($firstPo)) {
  5160. if ($ccydh === '') {
  5161. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5162. }
  5163. if ($cyjmc === '') {
  5164. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5165. }
  5166. }
  5167. }
  5168. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5169. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5170. if (is_array($any)) {
  5171. if ($ccydh === '') {
  5172. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5173. }
  5174. if ($cyjmc === '') {
  5175. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5176. }
  5177. }
  5178. }
  5179. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5180. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5181. $cgymc = '';
  5182. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5183. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5184. }
  5185. return [
  5186. 'ccydh' => $ccydh,
  5187. 'cyjmc' => $cyjmc,
  5188. 'cgymc' => $cgymc,
  5189. 'process_lines' => $processLines,
  5190. 'process_lines_html' => '',
  5191. ];
  5192. }
  5193. /**
  5194. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5195. */
  5196. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5197. {
  5198. $lines = [];
  5199. if ($ccydh !== '') {
  5200. $lines[] = '订单号:' . $ccydh;
  5201. }
  5202. if ($cyjmc !== '') {
  5203. $lines[] = '印件名称:' . $cyjmc;
  5204. }
  5205. if ($processPlain !== '') {
  5206. $lines[] = $processPlain;
  5207. }
  5208. return implode("\n", $lines);
  5209. }
  5210. /**
  5211. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5212. *
  5213. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5214. */
  5215. protected function buildPlatformLinksPlain(array $detailLinks): string
  5216. {
  5217. $lines = [];
  5218. $i = 1;
  5219. foreach ($detailLinks as $lk) {
  5220. if (!is_array($lk)) {
  5221. continue;
  5222. }
  5223. $url = trim((string)($lk['url'] ?? ''));
  5224. if ($url === '') {
  5225. continue;
  5226. }
  5227. $label = trim((string)($lk['cgymc'] ?? ''));
  5228. if ($label === '') {
  5229. $label = '工序' . $i;
  5230. }
  5231. $lines[] = $label . ':' . $url;
  5232. $i++;
  5233. }
  5234. return implode("\n", $lines);
  5235. }
  5236. /**
  5237. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5238. *
  5239. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5240. */
  5241. protected function buildPlatformLinksHtml(array $detailLinks): string
  5242. {
  5243. $parts = [];
  5244. $i = 1;
  5245. foreach ($detailLinks as $lk) {
  5246. if (!is_array($lk)) {
  5247. continue;
  5248. }
  5249. $url = trim((string)($lk['url'] ?? ''));
  5250. if ($url === '') {
  5251. continue;
  5252. }
  5253. $label = trim((string)($lk['cgymc'] ?? ''));
  5254. if ($label === '') {
  5255. $label = '工序' . $i;
  5256. }
  5257. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5258. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5259. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5260. $i++;
  5261. }
  5262. return implode("<br>\n", $parts);
  5263. }
  5264. /**
  5265. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5266. *
  5267. * @return array<string, mixed>
  5268. */
  5269. protected function loadMailerConfig(): array
  5270. {
  5271. try {
  5272. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5273. } catch (\Throwable $e) {
  5274. $cfg = [];
  5275. }
  5276. return is_array($cfg) ? $cfg : [];
  5277. }
  5278. protected function loadNotifyTemplateRow(string $scene): ?array
  5279. {
  5280. try {
  5281. $row = Db::table('purchase_sms_template')
  5282. ->where('scene', $scene)
  5283. ->where(function ($q) {
  5284. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5285. })
  5286. ->order('id', 'asc')
  5287. ->find();
  5288. } catch (\Throwable $e) {
  5289. return null;
  5290. }
  5291. if (!is_array($row) || $row === []) {
  5292. return null;
  5293. }
  5294. return [
  5295. 'title' => trim((string)($row['title'] ?? '')),
  5296. 'content' => trim((string)($row['content'] ?? '')),
  5297. ];
  5298. }
  5299. /**
  5300. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5301. */
  5302. protected function buildProcessLinesHtml(array $mergeRows): string
  5303. {
  5304. if (count($mergeRows) <= 1) {
  5305. $r = $mergeRows[0] ?? [];
  5306. if (!is_array($r)) {
  5307. return '';
  5308. }
  5309. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5310. $dw = trim((string)($r['CDW'] ?? ''));
  5311. $gzl = trim((string)($r['NGZL'] ?? ''));
  5312. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5313. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5314. if ($dw !== '') {
  5315. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5316. }
  5317. if ($gzl !== '') {
  5318. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5319. }
  5320. if ($qty !== '') {
  5321. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5322. }
  5323. return $html;
  5324. }
  5325. $rows = '';
  5326. $i = 1;
  5327. foreach ($mergeRows as $r) {
  5328. if (!is_array($r)) {
  5329. continue;
  5330. }
  5331. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5332. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5333. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5334. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5335. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5336. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5337. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5338. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5339. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5340. $i++;
  5341. }
  5342. if ($rows === '') {
  5343. return '';
  5344. }
  5345. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5346. . '<thead><tr style="background:#f5f5f5;">'
  5347. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5348. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5349. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5350. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5351. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5352. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5353. }
  5354. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  5355. {
  5356. $sysRq = trim($sysRq);
  5357. if ($sysRq === '') {
  5358. if ($required) {
  5359. $this->error('请选择截止时间');
  5360. }
  5361. return '';
  5362. }
  5363. $ts = strtotime($sysRq);
  5364. if ($ts === false || $ts <= 0) {
  5365. $this->error('截止时间格式无效');
  5366. }
  5367. return date('Y-m-d H:i:s', $ts);
  5368. }
  5369. protected function formatProcuremenSysRqForInput($sysRq): string
  5370. {
  5371. $sr = trim((string)$sysRq);
  5372. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  5373. return '';
  5374. }
  5375. $ts = strtotime($sr);
  5376. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  5377. }
  5378. protected function formatProcuremenSysRqForDisplay($sysRq): string
  5379. {
  5380. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  5381. if ($sr === '') {
  5382. return '—';
  5383. }
  5384. $ts = strtotime($sr);
  5385. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  5386. }
  5387. /**
  5388. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  5389. *
  5390. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  5391. * @return array{ccydh?:string,pos:array,merge_rows:array}
  5392. */
  5393. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  5394. {
  5395. return $bundle;
  5396. }
  5397. /**
  5398. * 写入/更新 purchase_order(单道工序行)
  5399. */
  5400. protected function upsertPurchaseOrderFromRow(
  5401. array $row,
  5402. string $sysRqDb,
  5403. $wflowStatus = null,
  5404. ?string $pickTime = null,
  5405. ?array $exists = null
  5406. ): void {
  5407. $ids = $this->extractScydgyRowId($row);
  5408. if (!$this->isValidScydgyRowId($ids)) {
  5409. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  5410. }
  5411. if ($exists === null) {
  5412. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5413. }
  5414. $data = [
  5415. 'scydgy_id' => $ids,
  5416. 'CCYDH' => $row['CCYDH'] ?? null,
  5417. 'CYJMC' => $row['CYJMC'] ?? null,
  5418. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5419. 'CDXMC' => $row['CDXMC'] ?? null,
  5420. 'CGYBH' => $row['CGYBH'] ?? null,
  5421. 'CGYMC' => $row['CGYMC'] ?? null,
  5422. 'CDW' => $row['CDW'] ?? null,
  5423. 'NGZL' => $row['NGZL'] ?? null,
  5424. 'CDF' => $row['CDF'] ?? null,
  5425. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5426. 'MBZ' => $row['MBZ'] ?? null,
  5427. 'bwjg' => $row['bwjg'] ?? null,
  5428. 'iStatus' => $row['iStatus'] ?? null,
  5429. 'dStamp' => $row['dStamp'] ?? null,
  5430. 'dputrecord' => $row['dputrecord'] ?? null,
  5431. 'cywyxm' => $row['cywyxm'] ?? null,
  5432. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5433. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5434. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5435. 'sys_rq' => $sysRqDb,
  5436. ];
  5437. if ($wflowStatus !== null && $wflowStatus !== '') {
  5438. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  5439. }
  5440. if ($pickTime !== null && $pickTime !== '') {
  5441. $data['pick_time'] = $pickTime;
  5442. $data['pick_company_name'] = '';
  5443. }
  5444. if ($exists) {
  5445. $upd = $data;
  5446. unset($upd['scydgy_id']);
  5447. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5448. } else {
  5449. $data['createtime'] = date('Y-m-d H:i:s');
  5450. Db::table('purchase_order')->insert($data);
  5451. }
  5452. }
  5453. /**
  5454. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  5455. *
  5456. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  5457. */
  5458. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  5459. {
  5460. $toDb = function ($value) {
  5461. if ($value === null) {
  5462. return null;
  5463. }
  5464. if (is_scalar($value)) {
  5465. return $value;
  5466. }
  5467. return json_encode($value, JSON_UNESCAPED_UNICODE);
  5468. };
  5469. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5470. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5471. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5472. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  5473. if ($username === '') {
  5474. $username = $this->resolveCustomerContactName($phone, $companyName);
  5475. }
  5476. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5477. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  5478. }
  5479. if ($phone === '') {
  5480. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  5481. }
  5482. $detailLinks = [];
  5483. foreach ($mergeRows as $row) {
  5484. if (!is_array($row)) {
  5485. continue;
  5486. }
  5487. $sid = $this->extractScydgyRowId($row);
  5488. $detailId = 0;
  5489. if ($skipExisting) {
  5490. try {
  5491. $existsQuery = Db::table('purchase_order_detail')
  5492. ->where('scydgy_id', $sid)
  5493. ->where('company_name', $companyName);
  5494. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  5495. $exists = $existsQuery->find();
  5496. } catch (\Throwable $e) {
  5497. $exists = null;
  5498. }
  5499. if (is_array($exists)) {
  5500. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  5501. }
  5502. }
  5503. if ($detailId <= 0) {
  5504. $one = [
  5505. 'scydgy_id' => $toDb($sid),
  5506. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  5507. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  5508. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  5509. 'username' => $username !== '' ? $username : null,
  5510. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  5511. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  5512. 'createtime' => date('Y-m-d H:i:s'),
  5513. 'status' => ProcuremenStatus::POD_UNPICKED,
  5514. 'status_name' => '未提交',
  5515. ];
  5516. Db::table('purchase_order_detail')->insert($one);
  5517. $detailId = (int)Db::getLastInsID();
  5518. }
  5519. $mprocUrl = '';
  5520. if ($buildMobileLinks && $detailId > 0) {
  5521. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  5522. }
  5523. $detailLinks[] = [
  5524. 'detail_id' => $detailId,
  5525. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  5526. 'url' => $mprocUrl,
  5527. ];
  5528. }
  5529. return $detailLinks;
  5530. }
  5531. /**
  5532. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  5533. * @return array<string, mixed>
  5534. */
  5535. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  5536. {
  5537. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5538. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5539. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5540. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  5541. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  5542. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  5543. $isMerge = !empty($ctx['is_merge']);
  5544. $contactName = trim((string)($c['username'] ?? ''));
  5545. if ($contactName === '') {
  5546. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  5547. }
  5548. $notifyVars = [
  5549. 'company_name' => $companyName,
  5550. 'contact_name' => $contactName,
  5551. 'phone' => $phone,
  5552. 'email' => $toEmail,
  5553. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  5554. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  5555. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  5556. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  5557. 'deadline' => (string)($ctx['deadline'] ?? ''),
  5558. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  5559. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  5560. 'platform_url' => $platformUrl,
  5561. 'platform_links' => $platformLinksPlain,
  5562. 'platform_links_html' => $platformLinksHtml,
  5563. ];
  5564. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  5565. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  5566. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5567. return [
  5568. 'company_name' => $companyName,
  5569. 'phone' => $phone,
  5570. 'email' => $toEmail,
  5571. 'sms_content' => $smsContent,
  5572. 'mail_plain' => $mailPlain,
  5573. 'mail_body' => $mailBody,
  5574. 'notify_vars' => $notifyVars,
  5575. 'detail_links' => $detailLinks,
  5576. ];
  5577. }
  5578. /**
  5579. * @param array<string, mixed> $chosen
  5580. * @param array<int, array<string, mixed>> $mergeRows
  5581. * @param array{ccydh:string, pos:array} $bundle
  5582. */
  5583. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  5584. {
  5585. if (!$sendSms && !$sendEmail) {
  5586. return;
  5587. }
  5588. $companyName = trim((string)($chosen['name'] ?? ''));
  5589. $phone = trim((string)($chosen['phone'] ?? ''));
  5590. $toEmail = trim((string)($chosen['email'] ?? ''));
  5591. if ($companyName === '') {
  5592. throw new \Exception('供应商名称无效');
  5593. }
  5594. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  5595. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  5596. }
  5597. if ($sendSms && $phone === '') {
  5598. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  5599. }
  5600. $sids = [];
  5601. foreach ($mergeRows as $mr) {
  5602. if (!is_array($mr)) {
  5603. continue;
  5604. }
  5605. $sid = $this->extractScydgyRowId($mr);
  5606. if ($this->isValidScydgyRowId($sid)) {
  5607. $sids[$sid] = true;
  5608. }
  5609. }
  5610. if ($sids === []) {
  5611. throw new \Exception('未找到工序行,无法发送通知');
  5612. }
  5613. $sysRqNotify = '';
  5614. $pos = $bundle['pos'] ?? [];
  5615. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5616. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  5617. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  5618. $ts = strtotime($sr);
  5619. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  5620. }
  5621. }
  5622. try {
  5623. $detailsQuery = Db::table('purchase_order_detail')
  5624. ->where('scydgy_id', 'in', array_keys($sids))
  5625. ->where('company_name', $companyName);
  5626. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5627. $details = $detailsQuery->order('id', 'asc')->select();
  5628. } catch (\Throwable $e) {
  5629. $details = [];
  5630. }
  5631. if (!is_array($details) || $details === []) {
  5632. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  5633. try {
  5634. $detailsQuery = Db::table('purchase_order_detail')
  5635. ->where('scydgy_id', 'in', array_keys($sids))
  5636. ->where('company_name', $companyName);
  5637. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5638. $details = $detailsQuery->order('id', 'asc')->select();
  5639. } catch (\Throwable $e) {
  5640. $details = [];
  5641. }
  5642. }
  5643. if (!is_array($details) || $details === []) {
  5644. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  5645. }
  5646. $detailLinks = [];
  5647. foreach ($details as $d) {
  5648. if (!is_array($d)) {
  5649. continue;
  5650. }
  5651. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  5652. if ($detailId <= 0) {
  5653. continue;
  5654. }
  5655. $sid = (int)($d['scydgy_id'] ?? 0);
  5656. $gymc = '';
  5657. foreach ($mergeRows as $mr) {
  5658. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  5659. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5660. break;
  5661. }
  5662. }
  5663. $detailLinks[] = [
  5664. 'detail_id' => $detailId,
  5665. 'cgymc' => $gymc,
  5666. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  5667. ];
  5668. }
  5669. if ($detailLinks === []) {
  5670. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  5671. }
  5672. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  5673. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  5674. $notifyBundle['email_log_scene'] = $emailLogScene;
  5675. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  5676. $poIdLog = 0;
  5677. $pos = $bundle['pos'] ?? [];
  5678. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5679. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5680. }
  5681. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  5682. if ($sendEmail) {
  5683. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  5684. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  5685. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  5686. }
  5687. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  5688. $mailConfig = $this->loadMailerConfig();
  5689. if (!$this->isProcuremenNotifyDryRun()) {
  5690. if (empty($mailConfig['host'])) {
  5691. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  5692. }
  5693. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  5694. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  5695. }
  5696. }
  5697. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  5698. }
  5699. if ($sendSms) {
  5700. $this->issueSendSupplierSms($notifyBundle);
  5701. }
  5702. }
  5703. /**
  5704. * @param array<int, array<string, mixed>> $quoteGroups
  5705. * @return array<int, array<string, mixed>>
  5706. */
  5707. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  5708. {
  5709. $names = [];
  5710. if (is_string($companiesJson) && $companiesJson !== '') {
  5711. $decoded = json_decode($companiesJson, true);
  5712. if (is_array($decoded)) {
  5713. foreach ($decoded as $nm) {
  5714. $nm = trim((string)$nm);
  5715. if ($nm !== '') {
  5716. $names[] = $nm;
  5717. }
  5718. }
  5719. }
  5720. }
  5721. $names = array_values(array_unique($names));
  5722. if ($names === [] && $selectedCompany !== '') {
  5723. $names = [$selectedCompany];
  5724. }
  5725. if ($names === []) {
  5726. return $quoteGroups;
  5727. }
  5728. $targets = [];
  5729. foreach ($quoteGroups as $g) {
  5730. if (!is_array($g)) {
  5731. continue;
  5732. }
  5733. $cn = trim((string)($g['name'] ?? ''));
  5734. if ($cn !== '' && in_array($cn, $names, true)) {
  5735. $targets[] = $g;
  5736. }
  5737. }
  5738. return $targets;
  5739. }
  5740. /**
  5741. * @return array{pos:array, merge_rows:array, bundle:array}
  5742. */
  5743. protected function loadAuditResendBundle(string $scydgyId): array
  5744. {
  5745. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5746. $pos = $bundle['pos'];
  5747. $mergeRows = $bundle['merge_rows'];
  5748. if ($pos === [] || $mergeRows === []) {
  5749. $this->error('该订单不在待确认供应商状态');
  5750. }
  5751. $sysRqDb = '';
  5752. if (isset($pos[0]) && is_array($pos[0])) {
  5753. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  5754. }
  5755. foreach ($pos as $i => $poRow) {
  5756. if (is_array($pos[$i]) && $sysRqDb !== '') {
  5757. $pos[$i]['sys_rq'] = $sysRqDb;
  5758. }
  5759. }
  5760. $bundle['pos'] = $pos;
  5761. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  5762. }
  5763. /**
  5764. * @param array<int, array<string, mixed>> $targets
  5765. */
  5766. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  5767. {
  5768. if ($targets === []) {
  5769. $this->error('未找到可通知的供应商');
  5770. }
  5771. $notifyErrors = [];
  5772. try {
  5773. $this->notifyDryRunPreview = [];
  5774. foreach ($targets as $g) {
  5775. if (!is_array($g)) {
  5776. continue;
  5777. }
  5778. $cname = trim((string)($g['name'] ?? ''));
  5779. if ($cname === '') {
  5780. continue;
  5781. }
  5782. $chosen = [
  5783. 'name' => $cname,
  5784. 'company_name' => $cname,
  5785. 'email' => trim((string)($g['email'] ?? '')),
  5786. 'phone' => trim((string)($g['phone'] ?? '')),
  5787. 'username' => trim((string)($g['username'] ?? '')),
  5788. ];
  5789. try {
  5790. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  5791. } catch (\Throwable $e) {
  5792. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5793. }
  5794. }
  5795. } catch (\Throwable $e) {
  5796. $this->error('通知发送失败:' . $e->getMessage());
  5797. }
  5798. if ($notifyErrors !== []) {
  5799. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5800. }
  5801. if ($this->isProcuremenNotifyDryRun()) {
  5802. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  5803. 'notify_dry_run' => true,
  5804. 'notify_preview' => $this->notifyDryRunPreview,
  5805. ]);
  5806. }
  5807. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  5808. }
  5809. /**
  5810. * 协助下发 — 发送短信(一家供应商)
  5811. *
  5812. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  5813. */
  5814. protected function issueSendSupplierSms(array $bundle): void
  5815. {
  5816. $companyName = (string)($bundle['company_name'] ?? '');
  5817. $phone = (string)($bundle['phone'] ?? '');
  5818. $smsContent = (string)($bundle['sms_content'] ?? '');
  5819. $this->logIssueNotifyDebug('短信', [
  5820. 'company' => $companyName,
  5821. 'phone' => $phone,
  5822. 'sms_content' => $smsContent,
  5823. ]);
  5824. if ($this->isProcuremenNotifyDryRun()) {
  5825. $this->recordNotifyDryRunPreview([
  5826. 'scene' => 'issue_sms',
  5827. 'company_name' => $companyName,
  5828. 'phone' => $phone,
  5829. 'sms_content' => $smsContent,
  5830. ]);
  5831. return;
  5832. }
  5833. $this->smsbao($phone, $smsContent);
  5834. }
  5835. /**
  5836. * 协助下发 — 发送邮件(一家供应商)
  5837. *
  5838. * @param array<string, mixed> $bundle
  5839. * @param array<string, mixed> $mailConfig
  5840. */
  5841. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  5842. {
  5843. $companyName = (string)($bundle['company_name'] ?? '');
  5844. $toEmail = (string)($bundle['email'] ?? '');
  5845. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  5846. $mailBody = (string)($bundle['mail_body'] ?? '');
  5847. $this->logIssueNotifyDebug('邮件', [
  5848. 'company' => $companyName,
  5849. 'email' => $toEmail,
  5850. 'mail_subject' => $mailSubject,
  5851. 'mail_body' => $mailPlain,
  5852. ]);
  5853. if ($this->isProcuremenNotifyDryRun()) {
  5854. $this->recordNotifyDryRunPreview([
  5855. 'scene' => 'issue_email',
  5856. 'company_name' => $companyName,
  5857. 'email' => $toEmail,
  5858. 'mail_subject' => $mailSubject,
  5859. 'mail_body' => $mailPlain,
  5860. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  5861. 'notify_vars' => $bundle['notify_vars'] ?? [],
  5862. 'detail_links' => $bundle['detail_links'] ?? [],
  5863. ]);
  5864. return;
  5865. }
  5866. $mail = new PHPMailer(true);
  5867. $mail->isSMTP();
  5868. $mail->Host = $mailConfig['host'];
  5869. $mail->SMTPAuth = true;
  5870. $mail->Username = $mailConfig['addr'];
  5871. $mail->Password = $mailConfig['pass'];
  5872. $mail->SMTPSecure = $mailConfig['security'];
  5873. $mail->Port = $mailConfig['port'];
  5874. $mail->CharSet = $mailConfig['charset'];
  5875. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  5876. $mail->addAddress($toEmail, $companyName);
  5877. $mail->isHTML(true);
  5878. $mail->Subject = $mailSubject;
  5879. $mail->Body = $mailBody;
  5880. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  5881. $sendOk = true;
  5882. $failReason = '';
  5883. try {
  5884. $mail->send();
  5885. } catch (\Throwable $e) {
  5886. $sendOk = false;
  5887. $failReason = $e->getMessage();
  5888. $this->persistEmailSendLog([
  5889. 'from_email' => $fromEmail,
  5890. 'to_email' => $toEmail,
  5891. 'send_time' => date('Y-m-d H:i:s'),
  5892. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  5893. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  5894. 'company_name' => $companyName,
  5895. 'mail_subject' => $mailSubject,
  5896. 'status' => 0,
  5897. 'fail_reason' => $failReason,
  5898. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  5899. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  5900. ]);
  5901. throw $e;
  5902. }
  5903. $this->persistEmailSendLog([
  5904. 'from_email' => $fromEmail,
  5905. 'to_email' => $toEmail,
  5906. 'send_time' => date('Y-m-d H:i:s'),
  5907. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  5908. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  5909. 'company_name' => $companyName,
  5910. 'mail_subject' => $mailSubject,
  5911. 'status' => 1,
  5912. 'fail_reason' => '',
  5913. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  5914. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  5915. ]);
  5916. }
  5917. /**
  5918. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  5919. *
  5920. * @param array<int, array<string, mixed>> $mergeRows
  5921. * @return array<string, mixed>
  5922. */
  5923. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  5924. {
  5925. $head = $mergeRows[0] ?? [];
  5926. $isMerge = count($mergeRows) > 1;
  5927. return [
  5928. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  5929. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  5930. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  5931. 'is_merge' => $isMerge,
  5932. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  5933. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  5934. 'deadline' => $sysRqNotify,
  5935. ];
  5936. }
  5937. /**
  5938. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  5939. *
  5940. * @param array<string, mixed> $data
  5941. */
  5942. protected function logIssueNotifyDebug(string $type, array $data): void
  5943. {
  5944. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  5945. return;
  5946. }
  5947. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  5948. }
  5949. protected function ensurePurchaseEmailSendLogTableOnce(): void
  5950. {
  5951. try {
  5952. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  5953. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  5954. return;
  5955. } catch (\Throwable $e) {
  5956. }
  5957. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  5958. if (is_file($sqlFile)) {
  5959. $sql = file_get_contents($sqlFile);
  5960. if (is_string($sql) && $sql !== '') {
  5961. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  5962. $stmt = trim($stmt);
  5963. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  5964. continue;
  5965. }
  5966. try {
  5967. Db::execute($stmt);
  5968. } catch (\Throwable $ignore) {
  5969. }
  5970. }
  5971. }
  5972. }
  5973. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  5974. }
  5975. /**
  5976. * @param array<string, mixed> $row
  5977. */
  5978. protected function persistEmailSendLog(array $row): void
  5979. {
  5980. try {
  5981. $this->ensurePurchaseEmailSendLogTableOnce();
  5982. } catch (\Throwable $e) {
  5983. return;
  5984. }
  5985. list($adminId, $adminName) = $this->GetUseName();
  5986. $cut = function ($s, $max) {
  5987. $s = (string)$s;
  5988. if (function_exists('mb_substr')) {
  5989. return mb_substr($s, 0, $max, 'UTF-8');
  5990. }
  5991. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  5992. };
  5993. $data = [
  5994. 'from_email' => $cut($row['from_email'] ?? '', 128),
  5995. 'to_email' => $cut($row['to_email'] ?? '', 128),
  5996. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  5997. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  5998. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  5999. 'company_name' => $cut($row['company_name'] ?? '', 128),
  6000. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6001. 'status' => !empty($row['status']) ? 1 : 0,
  6002. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6003. 'admin_id' => (int)$adminId,
  6004. 'admin_name' => $cut($adminName, 64),
  6005. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6006. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6007. 'createtime' => date('Y-m-d H:i:s'),
  6008. ];
  6009. try {
  6010. Db::table('purchase_email_send_log')->insert($data);
  6011. } catch (\Throwable $e) {
  6012. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6013. }
  6014. }
  6015. protected function formatEmailLogSceneText(string $scene): string
  6016. {
  6017. $map = [
  6018. 'pick_issue' => '初选下发',
  6019. 'audit_resend' => '确认页重发',
  6020. ];
  6021. return $map[$scene] ?? $scene;
  6022. }
  6023. /**
  6024. * 邮件发送日志列表
  6025. */
  6026. public function emailLog()
  6027. {
  6028. $this->relationSearch = false;
  6029. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6030. $this->request->filter(['strip_tags', 'trim']);
  6031. $bakModel = $this->model;
  6032. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6033. if ($this->request->isAjax()) {
  6034. $this->ensurePurchaseEmailSendLogTableOnce();
  6035. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6036. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6037. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6038. $list = $this->model
  6039. ->where($where)
  6040. ->order($sortField, $orderDir)
  6041. ->paginate($limit);
  6042. $rows = [];
  6043. foreach ($list->items() as $item) {
  6044. $row = is_array($item) ? $item : $item->toArray();
  6045. $scene = trim((string)($row['scene'] ?? ''));
  6046. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6047. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6048. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6049. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6050. $rows[] = $row;
  6051. }
  6052. $this->model = $bakModel;
  6053. return json(['total' => $list->total(), 'rows' => $rows]);
  6054. }
  6055. $this->model = $bakModel;
  6056. return $this->view->fetch('procuremen/emaillog');
  6057. }
  6058. /**
  6059. * 协助下发弹窗(选多家供应商并通知)
  6060. */
  6061. public function pickReview()
  6062. {
  6063. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6064. $this->error(__('You have no permission'));
  6065. }
  6066. if ($this->request->isPost()) {
  6067. $this->error('请使用弹窗内「确认下发」提交');
  6068. }
  6069. $this->view->assign('pickMode', 1);
  6070. return $this->view->fetch('procuremen/review');
  6071. }
  6072. /**
  6073. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6074. */
  6075. public function add()
  6076. {
  6077. if ($this->request->isPost()) {
  6078. $params = $this->request->post('row/a');
  6079. if (!is_array($params)) {
  6080. $this->error(__('Parameter %s can not be empty', ''));
  6081. }
  6082. [, $adminName] = $this->GetUseName();
  6083. $params['cywyxm'] = $adminName;
  6084. try {
  6085. $sid = $this->saveManualPickOrder($params);
  6086. } catch (\InvalidArgumentException $e) {
  6087. $this->error($e->getMessage());
  6088. } catch (\Throwable $e) {
  6089. $this->error($e->getMessage());
  6090. }
  6091. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6092. }
  6093. [, $adminName] = $this->GetUseName();
  6094. $this->view->assign('adminNickname', $adminName);
  6095. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6096. return $this->view->fetch();
  6097. }
  6098. /**
  6099. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6100. */
  6101. public function rfqlist()
  6102. {
  6103. $this->relationSearch = false;
  6104. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6105. $this->request->filter(['strip_tags', 'trim']);
  6106. if ($this->request->isAjax()) {
  6107. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6108. $limit = max(10, min(500, (int)$limit));
  6109. $applyFilters = function ($query) use ($where) {
  6110. $query->where('scydgy_id', '<', 0);
  6111. $query->whereRaw(
  6112. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6113. );
  6114. if (!$this->auth->isSuperAdmin()) {
  6115. [, $adminName] = $this->GetUseName();
  6116. $query->where('cywyxm', $adminName);
  6117. }
  6118. if (!empty($where)) {
  6119. $query->where($where);
  6120. }
  6121. };
  6122. $countQuery = Db::table('purchase_order');
  6123. $applyFilters($countQuery);
  6124. $total = (int)$countQuery->count();
  6125. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6126. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6127. $listQuery = Db::table('purchase_order');
  6128. $applyFilters($listQuery);
  6129. $rows = $listQuery
  6130. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6131. ->order($sortField, $orderDir)
  6132. ->limit($offset, $limit)
  6133. ->select();
  6134. if (!is_array($rows)) {
  6135. $rows = [];
  6136. }
  6137. $out = [];
  6138. foreach ($rows as $r) {
  6139. if (!is_array($r)) {
  6140. continue;
  6141. }
  6142. $sid = (int)($r['scydgy_id'] ?? 0);
  6143. if ($sid >= 0) {
  6144. continue;
  6145. }
  6146. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6147. if ($createdText === '') {
  6148. $createdText = trim((string)($r['dStamp'] ?? ''));
  6149. }
  6150. $out[] = [
  6151. 'id' => (int)($r['id'] ?? 0),
  6152. 'scydgy_id' => $sid,
  6153. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6154. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6155. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6156. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6157. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6158. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6159. 'createtime' => $r['createtime'] ?? null,
  6160. 'createtime_text' => $createdText,
  6161. ];
  6162. }
  6163. return json(['total' => $total, 'rows' => $out]);
  6164. }
  6165. [, $adminName] = $this->GetUseName();
  6166. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6167. $this->view->assign('adminNickname', $adminName);
  6168. return $this->view->fetch('procuremen/rfqlist');
  6169. }
  6170. /**
  6171. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6172. */
  6173. public function rfqlistDetails()
  6174. {
  6175. return $this->details();
  6176. }
  6177. /**
  6178. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6179. */
  6180. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6181. {
  6182. if ($scydgyId >= 0) {
  6183. return;
  6184. }
  6185. try {
  6186. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6187. } catch (\Throwable $e) {
  6188. $po = null;
  6189. }
  6190. if (!is_array($po)) {
  6191. $this->error('订单不存在');
  6192. }
  6193. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6194. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6195. $this->error('订单不存在');
  6196. }
  6197. if ($this->auth->isSuperAdmin()) {
  6198. return;
  6199. }
  6200. [, $adminName] = $this->GetUseName();
  6201. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6202. if ($cywy !== '' && $cywy === $adminName) {
  6203. return;
  6204. }
  6205. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6206. try {
  6207. if ($this->auth->check($rule)) {
  6208. return;
  6209. }
  6210. } catch (\Throwable $e) {
  6211. }
  6212. }
  6213. $this->error('无权查看该订单');
  6214. }
  6215. /**
  6216. * 手工新增协助工序进度文案
  6217. */
  6218. protected function formatProcuremenRfqProgressText(array $row): string
  6219. {
  6220. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6221. return ProcuremenStatus::PO_COMPLETED;
  6222. }
  6223. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6224. return '待采购确认';
  6225. }
  6226. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6227. return '待确认供应商';
  6228. }
  6229. $sid = (int)($row['scydgy_id'] ?? 0);
  6230. if ($sid < 0) {
  6231. try {
  6232. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6233. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6234. $detCnt = (int)$detCntQuery->count();
  6235. if ($detCnt > 0) {
  6236. return '已下发待确认';
  6237. }
  6238. } catch (\Throwable $e) {
  6239. }
  6240. }
  6241. return '待协助下发';
  6242. }
  6243. /**
  6244. * 协助初选列表 — 批量软删除
  6245. */
  6246. public function pickDelete()
  6247. {
  6248. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6249. $this->error(__('Invalid parameters'));
  6250. }
  6251. if (!$this->procuremenCanPickDelete()) {
  6252. $this->error(__('You have no permission'));
  6253. }
  6254. $rowsRaw = $this->request->post('rows_json', '[]');
  6255. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6256. if (!is_array($rows) || $rows === []) {
  6257. $this->error('请至少勾选一条工序');
  6258. }
  6259. $done = 0;
  6260. Db::startTrans();
  6261. try {
  6262. foreach ($rows as $row) {
  6263. if (!is_array($row)) {
  6264. continue;
  6265. }
  6266. $this->softDeleteProcuremenPickRow($row);
  6267. $done++;
  6268. }
  6269. if ($done < 1) {
  6270. throw new \Exception('没有可删除的工序');
  6271. }
  6272. Db::commit();
  6273. } catch (\InvalidArgumentException $e) {
  6274. Db::rollback();
  6275. $this->error($e->getMessage());
  6276. } catch (\Throwable $e) {
  6277. Db::rollback();
  6278. $this->error($e->getMessage());
  6279. }
  6280. $this->pickHiddenScydgySetCache = null;
  6281. $this->success('已删除 ' . $done . ' 条工序');
  6282. }
  6283. /**
  6284. * 下发 — 手工新增工序(弹窗)
  6285. */
  6286. public function pickAdd()
  6287. {
  6288. if ($this->request->isPost()) {
  6289. $params = $this->request->post('row/a');
  6290. if (!is_array($params)) {
  6291. $this->error(__('Parameter %s can not be empty', ''));
  6292. }
  6293. try {
  6294. $sid = $this->saveManualPickOrder($params);
  6295. } catch (\InvalidArgumentException $e) {
  6296. $this->error($e->getMessage());
  6297. } catch (\Throwable $e) {
  6298. $this->error($e->getMessage());
  6299. }
  6300. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6301. }
  6302. return $this->view->fetch('procuremen/pick_add');
  6303. }
  6304. /**
  6305. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  6306. */
  6307. public function pickSubmit()
  6308. {
  6309. if (!$this->request->isPost()) {
  6310. $this->error(__('Invalid parameters'));
  6311. }
  6312. // ---------- 接口订单数据 ----------
  6313. $rowJson = $this->request->post('row_json', '');
  6314. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  6315. $companiesJson = $this->request->post('companies_json', '[]');
  6316. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  6317. $companies = json_decode($companiesJson, true);
  6318. if (!is_array($companies)) {
  6319. $this->error('供应商数据无效');
  6320. }
  6321. $issueCompanies = $this->normalizePickCompanies($companies);
  6322. if ($issueCompanies === []) {
  6323. $this->error('请至少选择一家合作供应商');
  6324. }
  6325. $issueNameLabels = [];
  6326. foreach ($issueCompanies as $pc) {
  6327. $issueNameLabels[] = $pc['name'];
  6328. }
  6329. $issueNamesSummary = implode('、', $issueNameLabels);
  6330. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  6331. if ($sysRq === '') {
  6332. $this->error('请选择截止时间');
  6333. }
  6334. $sysRqTs = strtotime($sysRq);
  6335. if ($sysRqTs === false || $sysRqTs <= 0) {
  6336. $this->error('截止时间格式无效');
  6337. }
  6338. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  6339. $isMerge = count($mergeRows) > 1;
  6340. $ccydhLog = '';
  6341. foreach ($mergeRows as $row) {
  6342. if (!is_array($row)) {
  6343. continue;
  6344. }
  6345. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  6346. if ($ccydhLog !== '') {
  6347. break;
  6348. }
  6349. }
  6350. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  6351. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6352. $logMsg = '下发' . $orderPart . $procPart
  6353. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  6354. $issueTime = date('Y-m-d H:i:s');
  6355. $logSidList = [];
  6356. foreach ($mergeRows as $row) {
  6357. if (!is_array($row)) {
  6358. continue;
  6359. }
  6360. $sid = $this->extractScydgyRowId($row);
  6361. if ($this->isValidScydgyRowId($sid)) {
  6362. $logSidList[$sid] = true;
  6363. }
  6364. }
  6365. $existingBySid = [];
  6366. if ($logSidList !== []) {
  6367. try {
  6368. $existingRows = Db::table('purchase_order')
  6369. ->where('scydgy_id', 'in', array_keys($logSidList))
  6370. ->select();
  6371. if (is_array($existingRows)) {
  6372. foreach ($existingRows as $poRow) {
  6373. if (!is_array($poRow)) {
  6374. continue;
  6375. }
  6376. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6377. if ($this->isValidScydgyRowId($sid)) {
  6378. $existingBySid[$sid] = $poRow;
  6379. }
  6380. }
  6381. }
  6382. } catch (\Throwable $e) {
  6383. $existingBySid = [];
  6384. }
  6385. }
  6386. Db::startTrans();
  6387. try {
  6388. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  6389. foreach ($mergeRows as $row) {
  6390. if (!is_array($row)) {
  6391. continue;
  6392. }
  6393. $sid = $this->extractScydgyRowId($row);
  6394. $this->upsertPurchaseOrderFromRow(
  6395. $row,
  6396. $sysRqDb,
  6397. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6398. $issueTime,
  6399. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  6400. );
  6401. }
  6402. foreach ($issueCompanies as $c) {
  6403. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  6404. }
  6405. Db::commit();
  6406. } catch (\Throwable $e) {
  6407. Db::rollback();
  6408. $this->error($e->getMessage());
  6409. }
  6410. $poIdBySid = [];
  6411. if ($logSidList !== []) {
  6412. try {
  6413. $poIdBySid = Db::table('purchase_order')
  6414. ->where('scydgy_id', 'in', array_keys($logSidList))
  6415. ->column('id', 'scydgy_id');
  6416. } catch (\Throwable $e) {
  6417. $poIdBySid = [];
  6418. }
  6419. }
  6420. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  6421. if ($logSidList !== []) {
  6422. list($adminId, $adminName) = $this->GetUseName();
  6423. $cut = function ($s, $max) {
  6424. if (function_exists('mb_substr')) {
  6425. return mb_substr($s, 0, $max, 'UTF-8');
  6426. }
  6427. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6428. };
  6429. $logRows = [];
  6430. $seenLogSid = [];
  6431. foreach ($mergeRows as $row) {
  6432. if (!is_array($row)) {
  6433. continue;
  6434. }
  6435. $ids = $this->extractScydgyRowId($row);
  6436. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  6437. continue;
  6438. }
  6439. $seenLogSid[$ids] = true;
  6440. $poIdLog = null;
  6441. if (isset($poIdBySid[$ids])) {
  6442. $tid = (int)$poIdBySid[$ids];
  6443. $poIdLog = $tid > 0 ? $tid : null;
  6444. }
  6445. $logRows[] = [
  6446. 'scydgy_id' => $ids,
  6447. 'purchase_order_id' => $poIdLog,
  6448. 'admin_id' => $adminId,
  6449. 'admin_name' => $cut($adminName, 64),
  6450. 'action' => $cut('issue_submit', 64),
  6451. 'content' => $cut($logMsg, 1000),
  6452. 'createtime' => ProcuremenTime::nowDateTime(),
  6453. ];
  6454. }
  6455. if ($logRows !== []) {
  6456. try {
  6457. Db::table('purchase_order_oper_log')->insertAll($logRows);
  6458. } catch (\Throwable $e) {
  6459. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  6460. }
  6461. }
  6462. }
  6463. $notifyErrors = [];
  6464. $posNotify = [];
  6465. if ($logSidList !== []) {
  6466. try {
  6467. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  6468. } catch (\Throwable $e) {
  6469. $posNotify = [];
  6470. }
  6471. }
  6472. if (!is_array($posNotify)) {
  6473. $posNotify = [];
  6474. }
  6475. foreach ($posNotify as $i => $prow) {
  6476. if (is_array($posNotify[$i])) {
  6477. $posNotify[$i]['sys_rq'] = $sysRqDb;
  6478. }
  6479. }
  6480. $ccydhPick = '';
  6481. foreach ($mergeRows as $row) {
  6482. if (!is_array($row)) {
  6483. continue;
  6484. }
  6485. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  6486. if ($ccydhPick !== '') {
  6487. break;
  6488. }
  6489. }
  6490. $notifyBundleBase = [
  6491. 'ccydh' => $ccydhPick,
  6492. 'pos' => $posNotify,
  6493. 'merge_rows' => $mergeRows,
  6494. ];
  6495. try {
  6496. $this->notifyDryRunPreview = [];
  6497. foreach ($issueCompanies as $c) {
  6498. if (!is_array($c)) {
  6499. continue;
  6500. }
  6501. $cname = trim((string)($c['name'] ?? ''));
  6502. if ($cname === '') {
  6503. continue;
  6504. }
  6505. try {
  6506. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  6507. } catch (\Throwable $e) {
  6508. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6509. }
  6510. }
  6511. } catch (\Throwable $e) {
  6512. $this->error('通知发送失败:' . $e->getMessage());
  6513. }
  6514. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  6515. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6516. }
  6517. if ($this->isProcuremenNotifyDryRun()) {
  6518. $this->success('【演练模式】已保存并生成通知预览', '', [
  6519. 'notify_dry_run' => true,
  6520. 'notify_preview' => $this->notifyDryRunPreview,
  6521. ]);
  6522. }
  6523. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  6524. }
  6525. /**
  6526. * 确认供应商弹窗
  6527. */
  6528. public function auditIssue()
  6529. {
  6530. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6531. if (is_array($ids)) {
  6532. $ids = isset($ids[0]) ? $ids[0] : '';
  6533. }
  6534. $ids = trim((string)$ids);
  6535. if ($ids === '') {
  6536. $this->error(__('Invalid parameters'));
  6537. }
  6538. if ($this->request->isPost()) {
  6539. $this->error('请使用弹窗内「确认」提交');
  6540. }
  6541. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  6542. $pos = $bundle['pos'];
  6543. if ($pos === []) {
  6544. $this->error('该订单不在待确认供应商状态');
  6545. }
  6546. $po = $pos[0];
  6547. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6548. if ($quoteGroups === []) {
  6549. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  6550. }
  6551. $pickedName = '';
  6552. foreach ($pos as $poRow) {
  6553. if (!is_array($poRow)) {
  6554. continue;
  6555. }
  6556. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6557. if ($pn !== '') {
  6558. $pickedName = $pn;
  6559. break;
  6560. }
  6561. }
  6562. $this->view->assign('po', $po);
  6563. $this->view->assign('scydgyId', $ids);
  6564. $this->view->assign('orderCcydh', $bundle['ccydh']);
  6565. $mergeRows = $bundle['merge_rows'];
  6566. $this->view->assign('processRows', $mergeRows);
  6567. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  6568. $this->view->assign('processCount', count($mergeRows));
  6569. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  6570. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  6571. $this->view->assign('pickedCompanyName', $pickedName);
  6572. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  6573. if ($sysRqForView === '') {
  6574. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6575. }
  6576. $this->view->assign('sysRq', $sysRqForView);
  6577. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  6578. $this->view->assign('quoteDeadlineReached', $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0);
  6579. return $this->view->fetch('procuremen/audit_issue');
  6580. }
  6581. /**
  6582. * 开标双重验证 — 可选验证人列表
  6583. */
  6584. public function bidOpenUsers()
  6585. {
  6586. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6587. $this->error('无权限');
  6588. }
  6589. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  6590. if ($scydgyId !== '') {
  6591. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6592. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6593. $this->success('已完成开标验证', null, [
  6594. 'verified' => 1,
  6595. 'users' => [],
  6596. ]);
  6597. }
  6598. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6599. }
  6600. $this->success('', null, [
  6601. 'verified' => 0,
  6602. 'users' => $this->listBidOpenVerifierCandidates(),
  6603. ]);
  6604. }
  6605. /**
  6606. * 开标双重验证 — 向指定管理员发送短信验证码
  6607. */
  6608. public function bidOpenSendCode()
  6609. {
  6610. if (!$this->request->isPost()) {
  6611. $this->error(__('Invalid parameters'));
  6612. }
  6613. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6614. $this->error('无权限');
  6615. }
  6616. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6617. $adminId = (int)$this->request->post('admin_id', 0);
  6618. if ($scydgyId === '' || $adminId <= 0) {
  6619. $this->error('参数无效');
  6620. }
  6621. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6622. if ($bundle['pos'] === []) {
  6623. $this->error('该订单不在待确认供应商状态');
  6624. }
  6625. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6626. $this->success('已完成开标验证,无需重复发送');
  6627. }
  6628. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6629. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6630. if ($ccydh === '') {
  6631. $this->error('订单号无效');
  6632. }
  6633. $admin = $this->loadBidOpenAdminUser($adminId);
  6634. if ($admin === null) {
  6635. $this->error('验证人无效或未绑定手机号');
  6636. }
  6637. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  6638. $cd = max(30, min(120, $cd));
  6639. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  6640. $this->error('发送过于频繁,请稍后再试');
  6641. }
  6642. $code = (string)random_int(100000, 999999);
  6643. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  6644. $ttl = max(60, min(600, $ttl));
  6645. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  6646. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  6647. try {
  6648. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  6649. } catch (\Throwable $e) {
  6650. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  6651. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  6652. $this->error($e->getMessage());
  6653. }
  6654. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  6655. }
  6656. /**
  6657. * 开标双重验证 — 两人验证码校验并记录
  6658. */
  6659. public function bidOpenVerify()
  6660. {
  6661. if (!$this->request->isPost()) {
  6662. $this->error(__('Invalid parameters'));
  6663. }
  6664. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6665. $this->error('无权限');
  6666. }
  6667. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6668. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  6669. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  6670. $code1 = trim((string)$this->request->post('code1', ''));
  6671. $code2 = trim((string)$this->request->post('code2', ''));
  6672. if ($scydgyId === '') {
  6673. $this->error('参数无效');
  6674. }
  6675. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  6676. $this->error('请选择两位验证人');
  6677. }
  6678. if ($verifier1Id === $verifier2Id) {
  6679. $this->error('两位验证人不能相同');
  6680. }
  6681. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  6682. $this->error('请输入6位短信验证码');
  6683. }
  6684. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6685. if ($bundle['pos'] === []) {
  6686. $this->error('该订单不在待确认供应商状态');
  6687. }
  6688. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6689. if ($ccydh === '') {
  6690. $this->error('订单号无效');
  6691. }
  6692. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6693. $this->success('已完成开标验证');
  6694. }
  6695. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6696. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  6697. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  6698. if ($verifier1 === null || $verifier2 === null) {
  6699. $this->error('验证人无效或未绑定手机号');
  6700. }
  6701. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  6702. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  6703. }
  6704. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  6705. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  6706. }
  6707. try {
  6708. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  6709. } catch (\Throwable $e) {
  6710. $this->error($e->getMessage());
  6711. }
  6712. $this->success('开标验证成功,可查看供应商报价与交货日期');
  6713. }
  6714. /**
  6715. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  6716. */
  6717. public function auditSubmit()
  6718. {
  6719. if (!$this->request->isPost()) {
  6720. $this->error(__('Invalid parameters'));
  6721. }
  6722. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6723. if ($scydgyId === '') {
  6724. $this->error('参数无效');
  6725. }
  6726. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6727. $pos = $bundle['pos'];
  6728. $mergeRows = $bundle['merge_rows'];
  6729. if ($pos === [] || $mergeRows === []) {
  6730. $this->error('该订单不在待确认供应商状态');
  6731. }
  6732. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6733. if ($quoteGroups === []) {
  6734. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  6735. }
  6736. $companyName = trim((string)$this->request->post('selected_company', ''));
  6737. if ($companyName === '') {
  6738. $this->error('请选择一家供应商');
  6739. }
  6740. $matched = null;
  6741. foreach ($quoteGroups as $g) {
  6742. if (!is_array($g)) {
  6743. continue;
  6744. }
  6745. if (trim((string)($g['name'] ?? '')) === $companyName) {
  6746. $matched = $g;
  6747. break;
  6748. }
  6749. }
  6750. if ($matched === null) {
  6751. $this->error('所选供应商不在本单报价列表中');
  6752. }
  6753. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6754. if ($sysRqDb === '') {
  6755. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  6756. } else {
  6757. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true);
  6758. }
  6759. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6760. $this->error('请先完成开标双重验证后再确认供应商');
  6761. }
  6762. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  6763. $procCnt = count($mergeRows);
  6764. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6765. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  6766. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  6767. Db::startTrans();
  6768. try {
  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. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  6778. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  6779. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6780. 'pick_company_name' => $companyName,
  6781. 'sys_rq' => $sysRqDb,
  6782. ]);
  6783. }
  6784. Db::commit();
  6785. } catch (\Throwable $e) {
  6786. Db::rollback();
  6787. $this->error($e->getMessage());
  6788. }
  6789. foreach ($pos as $poRow) {
  6790. if (!is_array($poRow)) {
  6791. continue;
  6792. }
  6793. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6794. if (!$this->isValidScydgyRowId($sid)) {
  6795. continue;
  6796. }
  6797. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6798. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6799. }
  6800. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  6801. }
  6802. /**
  6803. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  6804. */
  6805. public function auditResendSms()
  6806. {
  6807. if (!$this->request->isPost()) {
  6808. $this->error(__('Invalid parameters'));
  6809. }
  6810. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6811. if ($scydgyId === '') {
  6812. $this->error('参数无效');
  6813. }
  6814. $loaded = $this->loadAuditResendBundle($scydgyId);
  6815. $mergeRows = $loaded['merge_rows'];
  6816. $bundle = $loaded['bundle'];
  6817. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  6818. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6819. if ($quoteGroups === []) {
  6820. $this->error('暂无可通知的供应商');
  6821. }
  6822. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  6823. $companiesJson = (string)$this->request->post('companies_json', '');
  6824. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  6825. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  6826. }
  6827. /**
  6828. * 确认供应商 — 二次发送邮件(可选单家/批量)
  6829. */
  6830. public function auditResendEmail()
  6831. {
  6832. if (!$this->request->isPost()) {
  6833. $this->error(__('Invalid parameters'));
  6834. }
  6835. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6836. if ($scydgyId === '') {
  6837. $this->error('参数无效');
  6838. }
  6839. $loaded = $this->loadAuditResendBundle($scydgyId);
  6840. $mergeRows = $loaded['merge_rows'];
  6841. $bundle = $loaded['bundle'];
  6842. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  6843. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6844. if ($quoteGroups === []) {
  6845. $this->error('暂无可通知的供应商');
  6846. }
  6847. $companiesJson = (string)$this->request->post('companies_json', '');
  6848. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  6849. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  6850. if ($companiesJson === '' && $selectedCompany === '') {
  6851. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  6852. }
  6853. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  6854. }
  6855. /**
  6856. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  6857. *
  6858. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  6859. * @return array<int, true> 已处理的 scydgy_id 集合
  6860. */
  6861. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  6862. {
  6863. $pos = $bundle['pos'] ?? [];
  6864. if (!is_array($pos) || $pos === []) {
  6865. return [];
  6866. }
  6867. $sids = [];
  6868. foreach ($pos as $poRow) {
  6869. if (!is_array($poRow)) {
  6870. continue;
  6871. }
  6872. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6873. if ($this->isValidScydgyRowId($sid)) {
  6874. $sids[$sid] = true;
  6875. }
  6876. }
  6877. if ($sids === []) {
  6878. return [];
  6879. }
  6880. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  6881. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  6882. $suffix = trim((string)$logSuffix, ',, ');
  6883. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  6884. $logMsg .= ':从历史存证退回协助初选';
  6885. } else {
  6886. $logMsg .= ':退回协助初选';
  6887. }
  6888. Db::table('purchase_order')
  6889. ->where('scydgy_id', 'in', array_keys($sids))
  6890. ->update([
  6891. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  6892. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6893. 'pick_company_name' => '',
  6894. 'pick_time' => null,
  6895. 'sys_rq' => null,
  6896. 'mod_rq' => null,
  6897. ]);
  6898. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  6899. foreach (array_keys($sids) as $sid) {
  6900. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  6901. }
  6902. return $sids;
  6903. }
  6904. /**
  6905. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  6906. *
  6907. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6908. */
  6909. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  6910. {
  6911. $scydgyId = trim($scydgyId);
  6912. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6913. if ($scydgyId === '') {
  6914. return $empty;
  6915. }
  6916. try {
  6917. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6918. } catch (\Throwable $e) {
  6919. $anchor = null;
  6920. }
  6921. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  6922. return $empty;
  6923. }
  6924. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6925. if ($ccydh === '') {
  6926. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6927. }
  6928. try {
  6929. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6930. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  6931. $pos = $query->order('scydgy_id', 'asc')->select();
  6932. } catch (\Throwable $e) {
  6933. $pos = [$anchor];
  6934. }
  6935. if (!is_array($pos) || $pos === []) {
  6936. $pos = [$anchor];
  6937. }
  6938. return [
  6939. 'ccydh' => $ccydh,
  6940. 'pos' => $pos,
  6941. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6942. ];
  6943. }
  6944. protected function purchaseOrderRowIsCompleted(array $po): bool
  6945. {
  6946. $st = $po['status'] ?? null;
  6947. if ($st === 1 || $st === '1') {
  6948. return true;
  6949. }
  6950. if (is_string($st) && trim($st) === '1') {
  6951. return true;
  6952. }
  6953. return is_numeric($st) && (int)$st === 1;
  6954. }
  6955. /**
  6956. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  6957. */
  6958. public function auditAbandon()
  6959. {
  6960. if (!$this->request->isPost()) {
  6961. $this->error(__('Invalid parameters'));
  6962. }
  6963. $anchorIds = [];
  6964. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  6965. if ($batchRaw !== '') {
  6966. $decoded = json_decode($batchRaw, true);
  6967. if (is_array($decoded)) {
  6968. foreach ($decoded as $id) {
  6969. $s = trim((string)$id);
  6970. if ($s !== '') {
  6971. $anchorIds[] = $s;
  6972. }
  6973. }
  6974. }
  6975. }
  6976. if ($anchorIds === []) {
  6977. $single = trim((string)$this->request->post('scydgy_id', ''));
  6978. if ($single !== '') {
  6979. $anchorIds[] = $single;
  6980. }
  6981. }
  6982. if ($anchorIds === []) {
  6983. $this->error('请至少选择一条订单');
  6984. }
  6985. $processedCcydh = [];
  6986. $doneOrders = 0;
  6987. $allSids = [];
  6988. Db::startTrans();
  6989. try {
  6990. foreach ($anchorIds as $anchorId) {
  6991. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  6992. if (($bundle['pos'] ?? []) === []) {
  6993. continue;
  6994. }
  6995. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6996. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  6997. if (isset($processedCcydh[$dedupeKey])) {
  6998. continue;
  6999. }
  7000. $processedCcydh[$dedupeKey] = true;
  7001. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  7002. if ($sids === []) {
  7003. continue;
  7004. }
  7005. $doneOrders++;
  7006. foreach (array_keys($sids) as $sid) {
  7007. $allSids[(int)$sid] = true;
  7008. }
  7009. }
  7010. if ($doneOrders < 1) {
  7011. throw new \Exception('所选订单均不在待确认供应商状态');
  7012. }
  7013. Db::commit();
  7014. } catch (\Throwable $e) {
  7015. Db::rollback();
  7016. $this->error($e->getMessage());
  7017. }
  7018. $this->pickHiddenScydgySetCache = null;
  7019. $msg = $doneOrders > 1
  7020. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7021. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7022. $this->success($msg);
  7023. }
  7024. /**
  7025. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7026. */
  7027. public function archiveAbandon()
  7028. {
  7029. if (!$this->request->isPost()) {
  7030. $this->error(__('Invalid parameters'));
  7031. }
  7032. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7033. $this->error(__('You have no permission'));
  7034. }
  7035. $anchorIds = [];
  7036. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7037. if ($batchRaw !== '') {
  7038. $decoded = json_decode($batchRaw, true);
  7039. if (is_array($decoded)) {
  7040. foreach ($decoded as $id) {
  7041. $s = trim((string)$id);
  7042. if ($s !== '') {
  7043. $anchorIds[] = $s;
  7044. }
  7045. }
  7046. }
  7047. }
  7048. if ($anchorIds === []) {
  7049. $single = trim((string)$this->request->post('scydgy_id', ''));
  7050. if ($single !== '') {
  7051. $anchorIds[] = $single;
  7052. }
  7053. }
  7054. if ($anchorIds === []) {
  7055. $this->error('请至少选择一条订单');
  7056. }
  7057. $processedCcydh = [];
  7058. $doneOrders = 0;
  7059. Db::startTrans();
  7060. try {
  7061. foreach ($anchorIds as $anchorId) {
  7062. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7063. if (($bundle['pos'] ?? []) === []) {
  7064. continue;
  7065. }
  7066. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7067. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7068. if (isset($processedCcydh[$dedupeKey])) {
  7069. continue;
  7070. }
  7071. $processedCcydh[$dedupeKey] = true;
  7072. $sids = $this->abandonOrderBundleToPick(
  7073. $bundle,
  7074. 'archive_abandon',
  7075. ',从历史存证退回协助初选'
  7076. );
  7077. if ($sids === []) {
  7078. continue;
  7079. }
  7080. $doneOrders++;
  7081. }
  7082. if ($doneOrders < 1) {
  7083. throw new \Exception('所选订单均不是已完结状态');
  7084. }
  7085. Db::commit();
  7086. } catch (\Throwable $e) {
  7087. Db::rollback();
  7088. $this->error($e->getMessage());
  7089. }
  7090. $this->pickHiddenScydgySetCache = null;
  7091. $msg = $doneOrders > 1
  7092. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  7093. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7094. $this->success($msg);
  7095. }
  7096. /**
  7097. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  7098. */
  7099. public function purchaseApprovalReject()
  7100. {
  7101. if (!$this->request->isPost() || !$this->request->isAjax()) {
  7102. $this->error(__('Invalid parameters'));
  7103. }
  7104. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  7105. $this->error(__('You have no permission'));
  7106. }
  7107. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  7108. $decoded = json_decode($batchRaw, true);
  7109. if (!is_array($decoded) || $decoded === []) {
  7110. $this->error('提交数据无效');
  7111. }
  7112. $done = 0;
  7113. Db::startTrans();
  7114. try {
  7115. foreach ($decoded as $item) {
  7116. if (!is_array($item)) {
  7117. continue;
  7118. }
  7119. $sid = (int)($item['scydgy_id'] ?? 0);
  7120. if (!$this->isValidScydgyRowId($sid)) {
  7121. continue;
  7122. }
  7123. $this->runPurchaseApprovalRejectForSid($sid);
  7124. $done++;
  7125. }
  7126. if ($done < 1) {
  7127. throw new \Exception('所选订单均不在待审批状态');
  7128. }
  7129. Db::commit();
  7130. } catch (\Throwable $e) {
  7131. Db::rollback();
  7132. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  7133. }
  7134. $this->pickHiddenScydgySetCache = null;
  7135. $this->success('已驳回并退回「协助审批下发」');
  7136. }
  7137. /**
  7138. * @throws \Exception
  7139. */
  7140. protected function runPurchaseApprovalRejectForSid(int $sid): void
  7141. {
  7142. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  7143. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  7144. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  7145. $allIds = $this->purchaseOrderDetail($sid);
  7146. if ($allIds === []) {
  7147. throw new \Exception('未找到下发明细');
  7148. }
  7149. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7150. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7151. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7152. 'pick_company_name' => '',
  7153. ]);
  7154. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  7155. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  7156. $poId = 0;
  7157. try {
  7158. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  7159. if (is_array($po)) {
  7160. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7161. }
  7162. } catch (\Throwable $e) {
  7163. }
  7164. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  7165. }
  7166. /**
  7167. * 审核弹窗(旧入口,POST 已关闭)
  7168. */
  7169. public function review()
  7170. {
  7171. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  7172. $this->error(__('You have no permission'));
  7173. }
  7174. if ($this->request->isPost()) {
  7175. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  7176. }
  7177. $this->view->assign('pickMode', 0);
  7178. return $this->view->fetch('procuremen/review');
  7179. }
  7180. /**
  7181. * 审核弹窗获取公司列表
  7182. */
  7183. public function reviewCompanies()
  7184. {
  7185. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review'])) {
  7186. $this->error(__('You have no permission'));
  7187. }
  7188. if (!$this->request->isAjax()) {
  7189. $this->error(__('Invalid parameters'));
  7190. }
  7191. $list = [];
  7192. try {
  7193. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  7194. $rows = Db::table('customer')
  7195. ->where(function ($q) {
  7196. $q->where('status', 1)
  7197. ->whereOr('status', '1')
  7198. ->whereOr('status', '')
  7199. ->whereNull('status');
  7200. })
  7201. ->order('id', 'desc')
  7202. ->select();
  7203. } catch (\Throwable $e) {
  7204. $this->success('', '', []);
  7205. return;
  7206. }
  7207. if (!is_array($rows)) {
  7208. $this->success('', '', []);
  7209. return;
  7210. }
  7211. $detailColCandidates = [
  7212. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  7213. 'company_detail', 'company_desc', 'address',
  7214. ];
  7215. foreach ($rows as $row) {
  7216. if (!is_array($row)) {
  7217. continue;
  7218. }
  7219. $norm = [];
  7220. foreach ($row as $k => $v) {
  7221. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7222. }
  7223. $row = $norm;
  7224. $st = $row['status'] ?? '';
  7225. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7226. continue;
  7227. }
  7228. $payload = $this->buildCustomerContactPayloadFromRow($row);
  7229. if ($payload === null) {
  7230. continue;
  7231. }
  7232. $detail = '';
  7233. foreach ($detailColCandidates as $dk) {
  7234. if (!isset($row[$dk])) {
  7235. continue;
  7236. }
  7237. $dv = trim((string)$row[$dk]);
  7238. if ($dv !== '') {
  7239. $detail = $dv;
  7240. break;
  7241. }
  7242. }
  7243. $payload['detail'] = $detail;
  7244. $list[] = $this->maskSupplierContactFields($payload);
  7245. }
  7246. $this->success('', '', $list);
  7247. }
  7248. /**
  7249. * 采购确认-下发明细弹窗:
  7250. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  7251. */
  7252. public function outward_detail()
  7253. {
  7254. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7255. if (is_array($ids)) {
  7256. $ids = isset($ids[0]) ? $ids[0] : '';
  7257. }
  7258. $ids = trim((string)$ids);
  7259. if ($ids === '') {
  7260. $this->error(__('Invalid parameters'));
  7261. }
  7262. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  7263. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  7264. $wffTab = 'all';
  7265. }
  7266. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  7267. $purchaseOrderId = 0;
  7268. $po = null;
  7269. try {
  7270. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7271. if (is_array($po)) {
  7272. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7273. }
  7274. } catch (\Throwable $e) {
  7275. $purchaseOrderId = 0;
  7276. $po = null;
  7277. }
  7278. if (!$isPurchaseConfirm && is_array($po)) {
  7279. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  7280. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  7281. $isPurchaseConfirm = true;
  7282. }
  7283. }
  7284. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  7285. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7286. $confirmProcessCount = 1;
  7287. $confirmPickGroups = [];
  7288. $processDisplayRows = [];
  7289. $allDetailsBySid = [];
  7290. $requiredSidList = [];
  7291. $sidList = [$ids];
  7292. if ($isPurchaseConfirm) {
  7293. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  7294. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  7295. if ($mergeRows !== []) {
  7296. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7297. }
  7298. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  7299. if ($confirmBundle['pos'] !== []) {
  7300. $sidList = [];
  7301. foreach ($confirmBundle['pos'] as $poRow) {
  7302. if (!is_array($poRow)) {
  7303. continue;
  7304. }
  7305. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7306. if (!$this->isValidScydgyRowId($sid)) {
  7307. continue;
  7308. }
  7309. $sidList[] = (string)$sid;
  7310. $requiredSidList[] = $sid;
  7311. }
  7312. }
  7313. if ($sidList === []) {
  7314. $sidList = [$ids];
  7315. $requiredSidList = [(int)$ids];
  7316. }
  7317. $confirmProcessCount = max(1, count($requiredSidList));
  7318. if (is_array($po) && $purchaseOrderId <= 0) {
  7319. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7320. }
  7321. }
  7322. $rows = [];
  7323. try {
  7324. if (count($sidList) === 1) {
  7325. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  7326. } else {
  7327. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  7328. }
  7329. } catch (\Throwable $e) {
  7330. $rows = [];
  7331. }
  7332. if ($isPurchaseConfirm) {
  7333. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  7334. }
  7335. foreach ($rows as &$r) {
  7336. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  7337. $r['id'] = $r['ID'];
  7338. }
  7339. if (isset($r['createtime'])) {
  7340. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  7341. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  7342. } else {
  7343. $r['createtime_text'] = (string)$r['createtime'];
  7344. }
  7345. } else {
  7346. $r['createtime_text'] = '';
  7347. }
  7348. if (is_array($r)) {
  7349. $r = $this->maskSupplierContactFields($r);
  7350. }
  7351. }
  7352. unset($r);
  7353. $pickedCompanyName = '';
  7354. if ($isPurchaseConfirm) {
  7355. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  7356. if (!is_array($poRow)) {
  7357. continue;
  7358. }
  7359. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7360. if ($pn !== '') {
  7361. $pickedCompanyName = $pn;
  7362. break;
  7363. }
  7364. }
  7365. }
  7366. $this->view->assign('rows', $rows ?: []);
  7367. $this->view->assign('rowCount', count($rows ?: []));
  7368. $this->view->assign('scydgyId', $ids);
  7369. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  7370. $this->view->assign('headTitle', $headTitle);
  7371. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  7372. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  7373. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  7374. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  7375. $this->view->assign('processDisplayRows', $processDisplayRows);
  7376. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  7377. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  7378. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  7379. $sysRqDisplay = '—';
  7380. if ($isPurchaseConfirm) {
  7381. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  7382. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  7383. );
  7384. }
  7385. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  7386. $this->view->assign('sysRq', $isPurchaseConfirm
  7387. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  7388. : '');
  7389. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  7390. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  7391. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  7392. if ($isPurchaseConfirm) {
  7393. return $this->view->fetch();
  7394. }
  7395. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  7396. $this->view->engine->layout(false);
  7397. try {
  7398. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  7399. $this->view->assign('dialogBody', $bodyHtml);
  7400. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  7401. } finally {
  7402. if ($restoreLayout) {
  7403. $this->view->engine->layout($restoreLayout);
  7404. }
  7405. }
  7406. }
  7407. /**
  7408. * 月度导出记录表(不存在时自动创建)
  7409. */
  7410. protected function ensurePurchaseMonthExportLogTable(): void
  7411. {
  7412. try {
  7413. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  7414. } catch (\Throwable $e) {
  7415. Db::execute(
  7416. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  7417. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  7418. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  7419. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  7420. `admin_name` varchar(64) NOT NULL DEFAULT '',
  7421. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  7422. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  7423. `createtime` int(10) unsigned DEFAULT NULL,
  7424. PRIMARY KEY (`id`),
  7425. KEY `idx_ym` (`ym`),
  7426. KEY `idx_ct` (`createtime`)
  7427. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  7428. );
  7429. }
  7430. }
  7431. /**
  7432. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  7433. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  7434. */
  7435. public function export_month_outward()
  7436. {
  7437. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  7438. $this->error(__('You have no permission'));
  7439. }
  7440. $this->request->filter(['strip_tags', 'trim']);
  7441. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  7442. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  7443. $ym = date('Y-m');
  7444. }
  7445. $dbRows = [];
  7446. try {
  7447. $query = Db::table('purchase_order');
  7448. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7449. $dbRows = $query->select();
  7450. } catch (\Throwable $e) {
  7451. $dbRows = [];
  7452. }
  7453. if (!is_array($dbRows)) {
  7454. $dbRows = [];
  7455. }
  7456. $completeTsMap = [];
  7457. $sidList = [];
  7458. foreach ($dbRows as $dbRow) {
  7459. if (!is_array($dbRow)) {
  7460. continue;
  7461. }
  7462. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  7463. if ($sid > 0) {
  7464. $sidList[$sid] = true;
  7465. }
  7466. }
  7467. if ($sidList !== []) {
  7468. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  7469. }
  7470. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  7471. if (!is_array($dbRow)) {
  7472. return false;
  7473. }
  7474. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  7475. return $done['ts'] > 0 && date('Y-m', $done['ts']) === $ym;
  7476. }));
  7477. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  7478. $filtered = $pool;
  7479. $mainBySid = [];
  7480. foreach ($filtered as $rw) {
  7481. if (!is_array($rw)) {
  7482. continue;
  7483. }
  7484. $rid = (int)($rw['ID'] ?? 0);
  7485. if ($rid > 0) {
  7486. $mainBySid[$rid] = $rw;
  7487. }
  7488. }
  7489. if ($mainBySid === []) {
  7490. $detailRows = [];
  7491. } else {
  7492. try {
  7493. $detailRows = Db::table('purchase_order_detail')
  7494. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7495. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7496. ->order('status', 'desc')
  7497. ->order('CCYDH', 'asc')
  7498. ->order('company_name', 'asc')
  7499. ->order('id', 'asc')
  7500. ->select();
  7501. } catch (\Throwable $e) {
  7502. try {
  7503. $detailRows = Db::table('purchase_order_detail')
  7504. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7505. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7506. ->order('status', 'desc')
  7507. ->order('CCYDH', 'asc')
  7508. ->order('company_name', 'asc')
  7509. ->order('ID', 'asc')
  7510. ->select();
  7511. } catch (\Throwable $e2) {
  7512. $detailRows = [];
  7513. }
  7514. }
  7515. }
  7516. if (!is_array($detailRows)) {
  7517. $detailRows = [];
  7518. }
  7519. $exportLines = [];
  7520. $detailSidSeen = [];
  7521. foreach ($detailRows as $dr) {
  7522. if (!is_array($dr)) {
  7523. continue;
  7524. }
  7525. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7526. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7527. continue;
  7528. }
  7529. if (isset($detailSidSeen[$sid])) {
  7530. continue;
  7531. }
  7532. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  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 ($detailRows as $dr) {
  7548. if (!is_array($dr)) {
  7549. continue;
  7550. }
  7551. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7552. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  7553. continue;
  7554. }
  7555. $detailSidSeen[$sid] = true;
  7556. $m = $mainBySid[$sid];
  7557. $exportLines[] = [
  7558. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7559. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7560. 'company_name' => (string)($dr['company_name'] ?? ''),
  7561. 'CDF' => (string)($m['CDF'] ?? ''),
  7562. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7563. 'gx' => $this->procuremenExportGxText($m),
  7564. 'detail' => $dr,
  7565. ];
  7566. }
  7567. foreach ($mainBySid as $sid => $m) {
  7568. if (isset($detailSidSeen[$sid])) {
  7569. continue;
  7570. }
  7571. $company = trim((string)($m['pick_company_name'] ?? ''));
  7572. $exportLines[] = [
  7573. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  7574. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  7575. 'company_name' => $company,
  7576. 'CDF' => (string)($m['CDF'] ?? ''),
  7577. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7578. 'gx' => $this->procuremenExportGxText($m),
  7579. 'detail' => [],
  7580. ];
  7581. }
  7582. $groups = [];
  7583. foreach ($exportLines as $line) {
  7584. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  7585. if (!isset($groups[$k])) {
  7586. $groups[$k] = [];
  7587. }
  7588. $groups[$k][] = $line;
  7589. }
  7590. ksort($groups, SORT_STRING);
  7591. $spreadsheet = new Spreadsheet();
  7592. $sheet = $spreadsheet->getActiveSheet();
  7593. $sheet->setTitle('外协加工明细');
  7594. $mon = (int)substr($ym, 5, 2);
  7595. $sheet->mergeCells('A1:H1');
  7596. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  7597. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  7598. $sheet->getStyle('A1')->getAlignment()
  7599. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7600. ->setVertical(Alignment::VERTICAL_CENTER);
  7601. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  7602. $col = 'A';
  7603. foreach ($headers as $h) {
  7604. $sheet->setCellValue($col . '2', $h);
  7605. $col++;
  7606. }
  7607. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  7608. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7609. $rowNum = 3;
  7610. $sumSubtotalCounts = 0;
  7611. $grandAmount = 0.0;
  7612. $globalSeq = 0;
  7613. if ($groups === []) {
  7614. $sheet->mergeCells('A3:H3');
  7615. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  7616. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7617. $rowNum = 4;
  7618. } else {
  7619. foreach ($groups as $items) {
  7620. if ($items === []) {
  7621. continue;
  7622. }
  7623. $groupLineCount = count($items);
  7624. $subAmount = 0.0;
  7625. foreach ($items as $line) {
  7626. $globalSeq++;
  7627. $dr = $line['detail'];
  7628. $amt = $this->procuremenExportAmount($dr);
  7629. $subAmount += $amt;
  7630. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  7631. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  7632. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  7633. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  7634. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  7635. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  7636. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  7637. $sheet->setCellValue('H' . $rowNum, $amt);
  7638. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  7639. $rowNum++;
  7640. }
  7641. $sumSubtotalCounts += $groupLineCount;
  7642. $grandAmount += $subAmount;
  7643. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7644. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  7645. $sheet->getStyle('G' . $rowNum)->getAlignment()
  7646. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  7647. ->setVertical(Alignment::VERTICAL_CENTER);
  7648. $rowNum++;
  7649. }
  7650. }
  7651. $sheet->setCellValue('A' . $rowNum, '总计');
  7652. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  7653. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7654. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  7655. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  7656. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  7657. $lastRow = $rowNum;
  7658. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  7659. 'borders' => [
  7660. 'allBorders' => [
  7661. 'borderStyle' => Border::BORDER_THIN,
  7662. 'color' => ['rgb' => '000000'],
  7663. ],
  7664. ],
  7665. ]);
  7666. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  7667. if ($lastRow >= 3) {
  7668. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7669. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7670. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7671. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7672. }
  7673. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  7674. $sheet->getColumnDimension('A')->setWidth(7);
  7675. $sheet->getColumnDimension('B')->setWidth(16);
  7676. $sheet->getColumnDimension('C')->setWidth(52);
  7677. $sheet->getColumnDimension('D')->setWidth(32);
  7678. $sheet->getColumnDimension('E')->setWidth(12);
  7679. $sheet->getColumnDimension('F')->setWidth(44);
  7680. $sheet->getColumnDimension('G')->setWidth(26);
  7681. $sheet->getColumnDimension('H')->setWidth(13);
  7682. $sheet->getRowDimension(1)->setRowHeight(28);
  7683. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  7684. $quoteStartRow = $lastRow + 3;
  7685. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
  7686. if ($quoteLastRow >= $quoteStartRow) {
  7687. $sheet->getColumnDimension('E')->setWidth(28);
  7688. }
  7689. $ymCompact = str_replace('-', '', $ym);
  7690. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  7691. $filename = $fileBase . '.xlsx';
  7692. try {
  7693. $this->ensurePurchaseMonthExportLogTable();
  7694. list($adminId, $adminName) = $this->GetUseName();
  7695. Db::table('purchase_month_export_log')->insert([
  7696. 'ym' => $ym,
  7697. 'admin_id' => (int)$adminId,
  7698. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  7699. 'row_count' => count($exportLines),
  7700. 'total_amount' => round($grandAmount, 2),
  7701. 'createtime' => time(),
  7702. ]);
  7703. } catch (\Throwable $e) {
  7704. Log::write('month export log: ' . $e->getMessage(), 'error');
  7705. }
  7706. if (ob_get_length()) {
  7707. ob_end_clean();
  7708. }
  7709. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  7710. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  7711. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  7712. header('Cache-Control: max-age=0');
  7713. $writer = new Xlsx($spreadsheet);
  7714. $writer->save('php://output');
  7715. $spreadsheet->disconnectWorksheets();
  7716. unset($spreadsheet);
  7717. exit;
  7718. }
  7719. /**
  7720. * 导出用:工序列文案
  7721. */
  7722. protected function procuremenExportGxText(array $r)
  7723. {
  7724. $a = trim((string)($r['CDXMC'] ?? ''));
  7725. $b = trim((string)($r['CGYMC'] ?? ''));
  7726. if ($a !== '' && $b !== '') {
  7727. return $a . ':' . $b;
  7728. }
  7729. return $a !== '' ? $a : $b;
  7730. }
  7731. /**
  7732. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  7733. */
  7734. protected function procuremenExportAmount(array $r)
  7735. {
  7736. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  7737. if (!array_key_exists($k, $r)) {
  7738. continue;
  7739. }
  7740. $v = $r[$k];
  7741. if ($v === null || $v === '') {
  7742. continue;
  7743. }
  7744. if (is_numeric($v)) {
  7745. return (float)$v;
  7746. }
  7747. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  7748. if ($v !== '' && is_numeric($v)) {
  7749. return (float)$v;
  7750. }
  7751. }
  7752. return 0.0;
  7753. }
  7754. /**
  7755. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  7756. *
  7757. * @param array<int, array<string, mixed>> $detailRows
  7758. * @param array<int, array<string, mixed>> $mainBySid
  7759. * @return array<int, array<string, mixed>>
  7760. */
  7761. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  7762. {
  7763. $lines = [];
  7764. foreach ($detailRows as $dr) {
  7765. if (!is_array($dr)) {
  7766. continue;
  7767. }
  7768. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7769. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7770. continue;
  7771. }
  7772. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  7773. continue;
  7774. }
  7775. $cn = trim((string)($dr['company_name'] ?? ''));
  7776. if ($cn === '') {
  7777. continue;
  7778. }
  7779. $m = $mainBySid[$sid];
  7780. $am = trim((string)($dr['amount'] ?? ''));
  7781. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  7782. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  7783. $amountText = $amountFilled
  7784. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  7785. : '未填写';
  7786. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  7787. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  7788. if ($deliveryShow === '' && $deliveryRaw !== '') {
  7789. $deliveryShow = $deliveryRaw;
  7790. }
  7791. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  7792. ? $deliveryShow
  7793. : '未填写';
  7794. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  7795. $lines[] = [
  7796. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7797. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7798. 'gx' => $this->procuremenExportGxText($m),
  7799. 'company_name' => $cn,
  7800. 'amount_text' => $amountText,
  7801. 'amount_num' => $amountFilled ? $amountNum : null,
  7802. 'delivery_text' => $deliveryText,
  7803. 'picked_text' => $picked ? '中标' : '未中标',
  7804. 'picked' => $picked,
  7805. ];
  7806. }
  7807. $winnerSupplierByOrder = [];
  7808. foreach ($lines as $line) {
  7809. $dh = trim((string)($line['CCYDH'] ?? ''));
  7810. $cn = trim((string)($line['company_name'] ?? ''));
  7811. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  7812. $winnerSupplierByOrder[$dh][$cn] = true;
  7813. }
  7814. }
  7815. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  7816. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  7817. if ($c !== 0) {
  7818. return $c;
  7819. }
  7820. $dh = trim((string)($a['CCYDH'] ?? ''));
  7821. $aCn = trim((string)($a['company_name'] ?? ''));
  7822. $bCn = trim((string)($b['company_name'] ?? ''));
  7823. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  7824. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  7825. if ($aSupplierWin !== $bSupplierWin) {
  7826. return $aSupplierWin ? -1 : 1;
  7827. }
  7828. $c = strcmp($aCn, $bCn);
  7829. if ($c !== 0) {
  7830. return $c;
  7831. }
  7832. if (!empty($a['picked']) !== !empty($b['picked'])) {
  7833. return !empty($a['picked']) ? -1 : 1;
  7834. }
  7835. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  7836. if ($c !== 0) {
  7837. return $c;
  7838. }
  7839. return 0;
  7840. });
  7841. return $lines;
  7842. }
  7843. /**
  7844. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  7845. *
  7846. * @param array<int, array<string, mixed>> $quoteLines
  7847. */
  7848. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  7849. {
  7850. $mon = (int)substr($ym, 5, 2);
  7851. $titleRow = $startRow;
  7852. $headerRow = $startRow + 1;
  7853. $dataStartRow = $startRow + 2;
  7854. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  7855. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  7856. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  7857. $sheet->getStyle('A' . $titleRow)->getAlignment()
  7858. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7859. ->setVertical(Alignment::VERTICAL_CENTER);
  7860. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  7861. $col = 'A';
  7862. foreach ($headers as $h) {
  7863. $sheet->setCellValue($col . $headerRow, $h);
  7864. $col++;
  7865. }
  7866. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  7867. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7868. $rowNum = $dataStartRow;
  7869. if ($quoteLines === []) {
  7870. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  7871. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  7872. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7873. $rowNum = $dataStartRow + 1;
  7874. } else {
  7875. $i = 0;
  7876. foreach ($quoteLines as $line) {
  7877. $i++;
  7878. $sheet->setCellValue('A' . $rowNum, $i);
  7879. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  7880. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  7881. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  7882. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  7883. if ($line['amount_num'] !== null) {
  7884. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  7885. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  7886. } else {
  7887. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  7888. }
  7889. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  7890. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  7891. if (!empty($line['picked'])) {
  7892. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  7893. }
  7894. $rowNum++;
  7895. }
  7896. }
  7897. $lastRow = $rowNum - 1;
  7898. if ($lastRow >= $headerRow) {
  7899. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  7900. 'borders' => [
  7901. 'allBorders' => [
  7902. 'borderStyle' => Border::BORDER_THIN,
  7903. 'color' => ['rgb' => '000000'],
  7904. ],
  7905. ],
  7906. ]);
  7907. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  7908. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7909. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7910. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7911. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  7912. if ($lastRow >= $dataStartRow) {
  7913. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  7914. }
  7915. }
  7916. return $lastRow;
  7917. }
  7918. /**
  7919. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  7920. */
  7921. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  7922. {
  7923. if ($lastRow < $dataStartRow || $headerRow < 1) {
  7924. return;
  7925. }
  7926. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  7927. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7928. ->setVertical(Alignment::VERTICAL_CENTER);
  7929. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  7930. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7931. ->setVertical(Alignment::VERTICAL_CENTER);
  7932. if ($lastCol > 'B') {
  7933. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  7934. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  7935. ->setVertical(Alignment::VERTICAL_CENTER);
  7936. }
  7937. }
  7938. /**
  7939. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  7940. */
  7941. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  7942. {
  7943. $s = trim($ccydh);
  7944. if ($s === '') {
  7945. return 'ORDER';
  7946. }
  7947. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  7948. $s = trim($s, '._-');
  7949. if ($s === '') {
  7950. return 'ORDER';
  7951. }
  7952. if (function_exists('mb_substr')) {
  7953. return mb_substr($s, 0, 80, 'UTF-8');
  7954. }
  7955. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  7956. }
  7957. /**
  7958. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  7959. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  7960. *
  7961. * @return array{objectKey: string, webPath: string}
  7962. */
  7963. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  7964. {
  7965. $sid = (int)$scydgyId;
  7966. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  7967. $y = date('Y');
  7968. $m = date('m');
  7969. $d = date('d');
  7970. $basename = $safeOrder . '_' . $sid . '.pdf';
  7971. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  7972. return [
  7973. 'objectKey' => $objectKey,
  7974. 'webPath' => '/' . $objectKey,
  7975. ];
  7976. }
  7977. /**
  7978. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  7979. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  7980. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  7981. *
  7982. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  7983. */
  7984. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  7985. {
  7986. if (!$this->isValidScydgyRowId($scydgyId)) {
  7987. return '';
  7988. }
  7989. $ids = trim((string)$scydgyId);
  7990. $prep = $this->prepareProcuremenDetailsView($ids);
  7991. if (!$prep['ok']) {
  7992. return '';
  7993. }
  7994. $ccydh = $prep['ccydh'];
  7995. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  7996. $objectKey = $paths['objectKey'];
  7997. $webPath = $paths['webPath'];
  7998. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  7999. $this->view->assign([
  8000. 'pdf_export' => 1,
  8001. 'pdfMetaLine' => $meta,
  8002. ]);
  8003. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  8004. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8005. $this->view->engine->layout(false);
  8006. try {
  8007. $html = $this->view->fetch('procuremen/details_pdf_shell');
  8008. } catch (\Throwable $e) {
  8009. if ($restoreLayout) {
  8010. $this->view->engine->layout($restoreLayout);
  8011. }
  8012. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  8013. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8014. return '';
  8015. }
  8016. if ($restoreLayout) {
  8017. $this->view->engine->layout($restoreLayout);
  8018. }
  8019. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8020. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  8021. if (!is_dir($tempDir)) {
  8022. @mkdir($tempDir, 0755, true);
  8023. }
  8024. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  8025. try {
  8026. $mpdf = new \Mpdf\Mpdf([
  8027. 'mode' => 'utf-8',
  8028. 'format' => 'A4',
  8029. 'margin_left' => 12,
  8030. 'margin_right' => 12,
  8031. 'margin_top' => 14,
  8032. 'margin_bottom' => 14,
  8033. 'tempDir' => $tempDir,
  8034. 'autoScriptToLang' => true,
  8035. 'autoLangToFont' => true,
  8036. ]);
  8037. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  8038. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  8039. $mpdf->SetBasePath('http://127.0.0.1/');
  8040. $mpdf->WriteHTML($html);
  8041. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  8042. } catch (\Throwable $e) {
  8043. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  8044. if (is_file($tempPdf)) {
  8045. @unlink($tempPdf);
  8046. }
  8047. return '';
  8048. }
  8049. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  8050. if ($ossUrl !== '') {
  8051. @unlink($tempPdf);
  8052. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8053. return $ossUrl;
  8054. }
  8055. $pi = pathinfo($objectKey);
  8056. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  8057. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  8058. if ($baseFile === '') {
  8059. @unlink($tempPdf);
  8060. return '';
  8061. }
  8062. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  8063. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  8064. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  8065. @unlink($tempPdf);
  8066. return '';
  8067. }
  8068. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  8069. if (!@copy($tempPdf, $fullPath)) {
  8070. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  8071. @unlink($tempPdf);
  8072. return '';
  8073. }
  8074. @unlink($tempPdf);
  8075. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8076. return $webPath;
  8077. }
  8078. /**
  8079. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  8080. */
  8081. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  8082. {
  8083. if ($scydgyId <= 0 || $webPath === '') {
  8084. return;
  8085. }
  8086. try {
  8087. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  8088. } catch (\Throwable $e) {
  8089. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  8090. }
  8091. }
  8092. /**
  8093. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  8094. *
  8095. * @param array<string, string> $vars
  8096. * @return array<string, string>
  8097. */
  8098. protected function normalizeSmsTemplateVars(array $vars): array
  8099. {
  8100. $out = [];
  8101. foreach ($vars as $k => $v) {
  8102. $out[(string)$k] = trim((string)$v);
  8103. }
  8104. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  8105. $out['contact_name'] = $out['company_name'];
  8106. }
  8107. return $out;
  8108. }
  8109. /**
  8110. * 按手机号或公司名称查 customer 表联系人姓名
  8111. */
  8112. protected function resolveCustomerContactName(string $phone, string $companyName): string
  8113. {
  8114. $phone = trim($phone);
  8115. $companyName = trim($companyName);
  8116. try {
  8117. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  8118. $row = Db::table('customer')
  8119. ->where(function ($q) use ($phone) {
  8120. $q->where('phone', $phone)->whereOr('account', $phone);
  8121. })
  8122. ->order('id', 'asc')
  8123. ->find();
  8124. if (is_array($row)) {
  8125. $nm = trim((string)($row['username'] ?? ''));
  8126. if ($nm !== '') {
  8127. return $nm;
  8128. }
  8129. }
  8130. }
  8131. if ($companyName !== '') {
  8132. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  8133. if (is_array($row)) {
  8134. return trim((string)($row['username'] ?? ''));
  8135. }
  8136. }
  8137. } catch (\Throwable $e) {
  8138. }
  8139. return '';
  8140. }
  8141. /**
  8142. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  8143. */
  8144. protected function plainTextToHtmlEmailBody(string $text): string
  8145. {
  8146. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  8147. $parts = explode("\n", $text);
  8148. $out = [];
  8149. foreach ($parts as $line) {
  8150. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  8151. $out[] = $line;
  8152. } else {
  8153. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  8154. }
  8155. }
  8156. return implode("<br>\n", $out);
  8157. }
  8158. /**
  8159. * 短信场景:去掉链接类变量,避免误填 URL
  8160. *
  8161. * @param array<string, string> $vars
  8162. * @return array<string, string>
  8163. */
  8164. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  8165. {
  8166. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  8167. return $vars;
  8168. }
  8169. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  8170. $vars[$k] = '';
  8171. }
  8172. return $vars;
  8173. }
  8174. /**
  8175. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  8176. *
  8177. * @param array<string, string> $vars
  8178. */
  8179. protected function renderNotifyTemplate(string $scene, array $vars): string
  8180. {
  8181. $vars = $this->normalizeSmsTemplateVars($vars);
  8182. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  8183. $row = $this->loadNotifyTemplateRow($scene);
  8184. if ($row === null) {
  8185. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8186. }
  8187. $tpl = trim((string)($row['content'] ?? ''));
  8188. if ($tpl === '') {
  8189. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8190. }
  8191. foreach ($vars as $k => $v) {
  8192. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  8193. }
  8194. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  8195. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  8196. return $tpl;
  8197. }
  8198. protected function resolveProcuremenEmailSubject(string $scene): string
  8199. {
  8200. $map = [
  8201. 'review_email' => '您有新的协助加工订单',
  8202. ];
  8203. $subject = trim((string)($map[$scene] ?? ''));
  8204. if ($subject === '') {
  8205. $this->error('未配置邮件主题:' . $scene);
  8206. }
  8207. return $subject;
  8208. }
  8209. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  8210. {
  8211. $map = [
  8212. 'review_email' => '协助下发-邮箱',
  8213. 'review_sms' => '协助下发-短信',
  8214. 'confirm_ok' => '采购确认-通过',
  8215. 'confirm_fail' => '采购确认-未通过',
  8216. 'bid_open' => '开标双重验证',
  8217. ];
  8218. $label = $map[$scene] ?? $scene;
  8219. if ($titleRequired) {
  8220. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  8221. }
  8222. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  8223. }
  8224. /**
  8225. * 是否开启协助通知演练(不发真实短信/邮件)
  8226. */
  8227. protected function isProcuremenNotifyDryRun(): bool
  8228. {
  8229. return (bool)Config::get('procuremen_notify_dry_run');
  8230. }
  8231. /**
  8232. * @param array<string, mixed> $payload
  8233. */
  8234. protected function recordNotifyDryRunPreview(array $payload): void
  8235. {
  8236. $this->notifyDryRunPreview[] = $payload;
  8237. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8238. }
  8239. /**
  8240. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  8241. * @throws \Exception
  8242. */
  8243. protected function smsbao($phone, $content)
  8244. {
  8245. if ($this->isProcuremenNotifyDryRun()) {
  8246. $this->recordNotifyDryRunPreview([
  8247. 'scene' => 'sms_only',
  8248. 'phone' => $phone,
  8249. 'sms_content' => $content,
  8250. ]);
  8251. return;
  8252. }
  8253. $statusStr = [
  8254. '0' => '短信发送成功',
  8255. '-1' => '参数不全',
  8256. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  8257. '30' => '密码错误',
  8258. '40' => '账号不存在',
  8259. '41' => '余额不足',
  8260. '42' => '帐户已过期',
  8261. '43' => 'IP地址限制',
  8262. '50' => '内容含有敏感词',
  8263. ];
  8264. $smsapi = 'http://api.smsbao.com/';
  8265. $user = 'zhuwei123';
  8266. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  8267. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  8268. $result = @file_get_contents($sendurl);
  8269. if ($result === false) {
  8270. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  8271. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  8272. }
  8273. $result = trim((string)$result);
  8274. if ($result !== '0') {
  8275. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  8276. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  8277. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  8278. }
  8279. }
  8280. }