Procuremen.php 364 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730
  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\ProcuremenSupplierScore;
  9. use app\common\library\ProcuremenTime;
  10. use PHPMailer\PHPMailer\PHPMailer;
  11. use think\Config;
  12. use think\Cache;
  13. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  14. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  15. use PhpOffice\PhpSpreadsheet\Style\Border;
  16. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  17. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  18. use think\Db;
  19. use think\Log;
  20. class Procuremen extends Backend
  21. {
  22. /**
  23. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  24. */
  25. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  26. /**
  27. * Procuremen模型对象
  28. * @var \app\admin\model\Procuremen
  29. */
  30. protected $model = null;
  31. /**
  32. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  33. */
  34. protected $notifyDryRunPreview = [];
  35. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  36. protected $procuremenRedisCache = null;
  37. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  38. protected $pickHiddenScydgySetCache = null;
  39. /** 邮件发送日志表结构已就绪缓存键 */
  40. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  41. /**
  42. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  43. * @var array
  44. */
  45. protected $noNeedRight = [
  46. 'pickreview', 'review', 'reviewcompanies',
  47. ];
  48. public function _initialize()
  49. {
  50. parent::_initialize();
  51. $this->model = new \app\admin\model\Procuremen;
  52. $this->maybeMigrateLegacyWflowStatusText();
  53. $this->assignProcuremenAuthConfig();
  54. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  55. $this->ensurePurchaseEmailSendLogTableOnce();
  56. }
  57. }
  58. /**
  59. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  60. */
  61. protected function maybeMigrateLegacyWflowStatusText(): void
  62. {
  63. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  64. if (is_file($flagFile)) {
  65. return;
  66. }
  67. $map = [
  68. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  69. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  70. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  71. '3' => ProcuremenStatus::WFLOW_APPROVED,
  72. ];
  73. try {
  74. foreach ($map as $num => $text) {
  75. Db::table('purchase_order')
  76. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  77. ->update(['wflow_status' => $text]);
  78. }
  79. @file_put_contents($flagFile, date('c'));
  80. } catch (\Throwable $e) {
  81. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  82. }
  83. }
  84. /**
  85. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  86. *
  87. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  88. */
  89. protected function hasProcuremenPerm(array $actions): bool
  90. {
  91. foreach ($actions as $action) {
  92. $action = strtolower(trim((string)$action));
  93. if ($action === '') {
  94. continue;
  95. }
  96. if (strpos($action, 'procuremen/') !== 0) {
  97. $action = 'procuremen/' . $action;
  98. }
  99. if ($this->auth->check($action)) {
  100. return true;
  101. }
  102. }
  103. $suffixes = [];
  104. foreach ($actions as $action) {
  105. $action = strtolower(trim((string)$action));
  106. $action = preg_replace('#^procuremen/#', '', $action);
  107. if ($action !== '') {
  108. $suffixes[$action] = true;
  109. }
  110. }
  111. if ($suffixes === []) {
  112. return false;
  113. }
  114. try {
  115. foreach ($this->auth->getRuleList() as $rule) {
  116. $rule = strtolower((string)$rule);
  117. if (strpos($rule, 'procuremen/') !== 0) {
  118. continue;
  119. }
  120. foreach (array_keys($suffixes) as $suffix) {
  121. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  122. return true;
  123. }
  124. }
  125. }
  126. } catch (\Throwable $e) {
  127. }
  128. return false;
  129. }
  130. /**
  131. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  132. *
  133. * @param string[] $actions
  134. */
  135. protected function hasProcuremenPermStrict(array $actions): bool
  136. {
  137. foreach ($actions as $action) {
  138. $action = strtolower(trim((string)$action));
  139. if ($action === '') {
  140. continue;
  141. }
  142. if (strpos($action, 'procuremen/') !== 0) {
  143. $action = 'procuremen/' . $action;
  144. }
  145. if ($this->auth->check($action)) {
  146. return true;
  147. }
  148. }
  149. return false;
  150. }
  151. /**
  152. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  153. *
  154. * @param string[] $titles
  155. */
  156. protected function authHasAssignedRuleTitle(array $titles): bool
  157. {
  158. $titles = array_values(array_filter(array_map('trim', $titles)));
  159. if ($titles === []) {
  160. return false;
  161. }
  162. try {
  163. $ids = $this->auth->getRuleIds();
  164. if (in_array('*', $ids, true)) {
  165. return true;
  166. }
  167. if ($ids === []) {
  168. return false;
  169. }
  170. $rows = Db::name('auth_rule')
  171. ->where('status', 'normal')
  172. ->whereIn('id', $ids)
  173. ->column('title');
  174. foreach ($rows as $title) {
  175. $t = trim((string)$title);
  176. if ($t !== '' && in_array($t, $titles, true)) {
  177. return true;
  178. }
  179. }
  180. } catch (\Throwable $e) {
  181. }
  182. return false;
  183. }
  184. protected function procuremenCanPickDelete(): bool
  185. {
  186. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  187. return true;
  188. }
  189. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  190. }
  191. protected function procuremenCanComplete(): bool
  192. {
  193. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  194. return true;
  195. }
  196. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  197. }
  198. protected function procuremenCanDispatch(): bool
  199. {
  200. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  201. }
  202. /**
  203. * 前端按钮显隐(Config.procuremenAuth)
  204. */
  205. protected function assignProcuremenAuthConfig(): void
  206. {
  207. $authMap = [
  208. 'pickreview' => $this->procuremenCanDispatch(),
  209. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  210. 'pickdelete' => $this->procuremenCanPickDelete(),
  211. 'completedirectly' => $this->procuremenCanComplete(),
  212. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  213. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  214. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  215. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  216. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  217. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  218. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  219. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  220. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  221. 'details' => $this->hasProcuremenPerm(['details']),
  222. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  223. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  224. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  225. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  226. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  227. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  228. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  229. 'add' => $this->hasProcuremenPerm(['add']),
  230. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  231. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  232. ];
  233. $this->assignconfig('procuremenAuth', $authMap);
  234. }
  235. /**
  236. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  237. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  238. *
  239. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  240. */
  241. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  242. {
  243. static $mprocCfgLoaded = false;
  244. if (!$mprocCfgLoaded) {
  245. $mprocCfgLoaded = true;
  246. if (is_file(APP_PATH . 'extra/mproc.php')) {
  247. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  248. }
  249. }
  250. $eid = (int)$purchaseOrderDetailId;
  251. $base = $this->resolveMprocMobilePublicBaseUrl();
  252. if ($base === '') {
  253. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  254. }
  255. $path = trim((string)Config::get('mproc.mobile_index_path'));
  256. if ($path === '') {
  257. $path = '/index.php/index/index/index';
  258. } else {
  259. $path = '/' . ltrim($path, '/');
  260. }
  261. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  262. if ($eid > 0) {
  263. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  264. }
  265. return $base . $path . '?main_tab=orders';
  266. }
  267. /**
  268. * 邮件/短信外链:须为带点的公网域名
  269. */
  270. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  271. {
  272. $u = trim((string)$baseUrl);
  273. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  274. return false;
  275. }
  276. $host = parse_url($u, PHP_URL_HOST);
  277. if (!is_string($host) || $host === '') {
  278. return false;
  279. }
  280. if (strcasecmp($host, 'localhost') === 0) {
  281. return false;
  282. }
  283. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  284. return false;
  285. }
  286. if (strpos($host, '.') === false) {
  287. return false;
  288. }
  289. return true;
  290. }
  291. /**
  292. * 解析用于协助邮件/短信的手机端站点根
  293. */
  294. protected function resolveMprocMobilePublicBaseUrl()
  295. {
  296. $candidates = [];
  297. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  298. $candidates[] = trim((string)Config::get('site.indexurl'));
  299. $cdn = trim((string)Config::get('site.cdnurl'));
  300. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  301. $candidates[] = rtrim($cdn, '/');
  302. }
  303. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  304. $candidates[] = $reqBase;
  305. foreach ($candidates as $c) {
  306. if ($c === '') {
  307. continue;
  308. }
  309. $c = rtrim($c, '/');
  310. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  311. return $c;
  312. }
  313. }
  314. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  315. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  316. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  317. return $reqBase;
  318. }
  319. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  320. return '';
  321. }
  322. /**
  323. * 获取 Redis 中 procuremen_redis
  324. */
  325. protected function ProcuremenRedis(): array
  326. {
  327. if ($this->procuremenRedisCache !== null) {
  328. return $this->procuremenRedisCache;
  329. }
  330. try {
  331. $redis = redis();
  332. $raw = $redis->get('procuremen_redis');
  333. if ($raw === false || $raw === '') {
  334. $this->procuremenRedisCache = [];
  335. return $this->procuremenRedisCache;
  336. }
  337. $decoded = json_decode($raw, true);
  338. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  339. $this->procuremenRedisCache = [];
  340. return $this->procuremenRedisCache;
  341. }
  342. $this->procuremenRedisCache = $decoded['data'];
  343. return $this->procuremenRedisCache;
  344. } catch (\Throwable $e) {
  345. $this->procuremenRedisCache = [];
  346. return $this->procuremenRedisCache;
  347. }
  348. }
  349. /**
  350. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  351. *
  352. * @return array<int, array<string, mixed>>
  353. */
  354. protected function procuremenFetchErpPoolFromDb(): array
  355. {
  356. try {
  357. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  358. $endTime = date('Y-m-d 23:59:59');
  359. $list = Db::table('scydgy')
  360. ->alias('a')
  361. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  362. ->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')
  363. ->where([
  364. 'a.bwjg' => 1,
  365. 'a.iEndBz' => 0,
  366. 'a.iType' => 0,
  367. 'a.iStatus' => 10,
  368. ])
  369. ->where('a.dStamp', '>=', $startTime)
  370. ->where('a.dStamp', '<=', $endTime)
  371. ->order('a.dStamp', 'desc')
  372. ->select();
  373. if (!is_array($list)) {
  374. return [];
  375. }
  376. try {
  377. $redis = redis();
  378. $payload = [
  379. 'code' => 200,
  380. 'msg' => 'success',
  381. 'data' => $list,
  382. ];
  383. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  384. $this->procuremenRedisCache = $list;
  385. } catch (\Throwable $e) {
  386. }
  387. return $list;
  388. } catch (\Throwable $e) {
  389. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  390. return [];
  391. }
  392. }
  393. /**
  394. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  395. *
  396. * @return array<int, array<string, mixed>>
  397. */
  398. protected function procuremenEnsureRedisPool(): array
  399. {
  400. $pool = $this->ProcuremenRedis();
  401. if (is_array($pool) && $pool !== []) {
  402. return $pool;
  403. }
  404. static $warmed = false;
  405. if ($warmed) {
  406. return is_array($pool) ? $pool : [];
  407. }
  408. $warmed = true;
  409. return $this->procuremenFetchErpPoolFromDb();
  410. }
  411. /**
  412. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  413. *
  414. * @param array<string, mixed> $row
  415. */
  416. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  417. {
  418. $t = $this->procuremenRowListSortTime($row, $primary);
  419. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  420. return null;
  421. }
  422. $mo = (int)$m[2];
  423. if ($mo < 1 || $mo > 12) {
  424. return null;
  425. }
  426. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  427. }
  428. /**
  429. * @param array<int, array{year:string, months:array}> $sidebar
  430. * @return array<int, array{year:string, months:array}>
  431. */
  432. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  433. {
  434. $ym = trim($ym);
  435. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  436. return $sidebar;
  437. }
  438. foreach ($sidebar as $block) {
  439. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  440. continue;
  441. }
  442. foreach ($block['months'] as $item) {
  443. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  444. return $sidebar;
  445. }
  446. }
  447. }
  448. $y = substr($ym, 0, 4);
  449. $mo = (int)substr($ym, 5, 2);
  450. $sidebar[] = [
  451. 'year' => $y,
  452. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  453. ];
  454. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  455. }
  456. /**
  457. * @param array<int, array{year:string, months:array}> $sidebar
  458. * @return string[]
  459. */
  460. protected function flattenProcuremenSidebarYms(array $sidebar): array
  461. {
  462. $yms = [];
  463. foreach ($sidebar as $block) {
  464. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  465. continue;
  466. }
  467. foreach ($block['months'] as $item) {
  468. if (!is_array($item)) {
  469. continue;
  470. }
  471. $ym = trim((string)($item['ym'] ?? ''));
  472. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  473. $yms[$ym] = true;
  474. }
  475. }
  476. }
  477. return array_keys($yms);
  478. }
  479. /**
  480. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  481. */
  482. protected function GetIndexYearMonths()
  483. {
  484. $ymSet = [];
  485. $pool = $this->procuremenEnsureRedisPool();
  486. foreach ($pool as $r) {
  487. if (!is_array($r)) {
  488. continue;
  489. }
  490. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  491. if ($ym !== null) {
  492. $ymSet[$ym] = true;
  493. }
  494. }
  495. foreach ($this->loadPickManualOrderRows() as $r) {
  496. if (!is_array($r)) {
  497. continue;
  498. }
  499. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  500. if ($ym !== null) {
  501. $ymSet[$ym] = true;
  502. }
  503. }
  504. $ymList = array_keys($ymSet);
  505. if ($ymList === []) {
  506. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  507. }
  508. return $this->buildYearMonthSidebar($ymList);
  509. }
  510. /**
  511. * @param string[] $ymList 形如 2026-06
  512. * @return array<int, array{year:string, months:array}>
  513. */
  514. protected function buildYearMonthSidebar(array $ymList): array
  515. {
  516. rsort($ymList, SORT_STRING);
  517. $byYear = [];
  518. foreach ($ymList as $ym) {
  519. $y = substr($ym, 0, 4);
  520. $mo = (int)substr($ym, 5, 2);
  521. if (!isset($byYear[$y])) {
  522. $byYear[$y] = [];
  523. }
  524. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  525. }
  526. krsort($byYear, SORT_NUMERIC);
  527. foreach ($byYear as $y => $items) {
  528. usort($byYear[$y], function ($a, $b) {
  529. return strcmp($b['ym'], $a['ym']);
  530. });
  531. }
  532. $sidebar = [];
  533. foreach ($byYear as $y => $months) {
  534. $sidebar[] = ['year' => $y, 'months' => $months];
  535. }
  536. return $sidebar;
  537. }
  538. /**
  539. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  540. */
  541. protected function GetIssuedOrderYearMonths(string $stage): array
  542. {
  543. $ymSet = [];
  544. try {
  545. $query = Db::table('purchase_order');
  546. $this->applyPurchaseOrderNotDeletedWhere($query);
  547. if ($stage === 'audit') {
  548. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  549. } elseif ($stage === 'confirm') {
  550. $this->applyPurchaseOrderConfirmStageWhere($query);
  551. } else {
  552. return $this->GetIndexYearMonths();
  553. }
  554. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  555. if (is_array($rows)) {
  556. foreach ($rows as $r) {
  557. if (!is_array($r)) {
  558. continue;
  559. }
  560. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  561. if ($ym !== null) {
  562. $ymSet[$ym] = true;
  563. }
  564. }
  565. }
  566. } catch (\Throwable $e) {
  567. $ymSet = [];
  568. }
  569. $ymList = array_keys($ymSet);
  570. if ($ymList === []) {
  571. $def = $this->resolveProcuremenDefaultYm($stage);
  572. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  573. }
  574. return $this->buildYearMonthSidebar($ymList);
  575. }
  576. /**
  577. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  578. */
  579. protected function resolveProcuremenDefaultYm(string $stage): string
  580. {
  581. if ($stage === 'pick') {
  582. return date('Y-m');
  583. }
  584. try {
  585. $query = Db::table('purchase_order');
  586. $this->applyPurchaseOrderNotDeletedWhere($query);
  587. if ($stage === 'audit') {
  588. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  589. } elseif ($stage === 'confirm') {
  590. $this->applyPurchaseOrderConfirmStageWhere($query);
  591. } else {
  592. return date('Y-m');
  593. }
  594. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  595. if ($latest === null || $latest === '') {
  596. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  597. }
  598. $t = $this->formatProcuremenDetailTime($latest);
  599. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  600. return $m[1] . '-' . $m[2];
  601. }
  602. } catch (\Throwable $e) {
  603. }
  604. return date('Y-m');
  605. }
  606. protected function applyPurchaseOrderNotDeletedWhere($query): void
  607. {
  608. $query->whereRaw(
  609. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  610. );
  611. }
  612. /**
  613. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  614. */
  615. protected function applyPurchaseOrderConfirmStageWhere($query): void
  616. {
  617. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  618. $quoted = [];
  619. foreach ($vals as $v) {
  620. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  621. }
  622. if ($quoted === []) {
  623. $query->whereRaw('1 = 0');
  624. return;
  625. }
  626. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  627. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  628. }
  629. /**
  630. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  631. *
  632. * @param array<string, mixed> $row
  633. * @return array<string, mixed>
  634. */
  635. protected function normalizePurchaseOrderListTimeRow(array $row): array
  636. {
  637. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  638. $pick = trim((string)($row['pick_time'] ?? ''));
  639. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  640. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  641. $t = trim((string)($row[$key] ?? ''));
  642. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  643. $row['pick_time'] = $t;
  644. break;
  645. }
  646. }
  647. }
  648. return $row;
  649. }
  650. /**
  651. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  652. */
  653. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  654. {
  655. if (!in_array($stage, ['audit', 'confirm'], true)) {
  656. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  657. }
  658. if ($pool === []) {
  659. $def = $this->resolveProcuremenDefaultYm($stage);
  660. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  661. }
  662. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  663. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  664. return false;
  665. }
  666. $monthStart = $ym . '-01 00:00:00';
  667. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  668. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  669. return $probe !== [];
  670. };
  671. if ($tryYm($requestedYm)) {
  672. return $requestedYm;
  673. }
  674. $fallback = $this->resolveProcuremenDefaultYm($stage);
  675. if ($tryYm($fallback)) {
  676. return $fallback;
  677. }
  678. $bestYm = '';
  679. $bestTime = '';
  680. foreach ($pool as $row) {
  681. if (!is_array($row)) {
  682. continue;
  683. }
  684. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  685. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  686. continue;
  687. }
  688. $ymRow = $m[1];
  689. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  690. $bestTime = $t;
  691. $bestYm = $ymRow;
  692. }
  693. }
  694. if ($bestYm !== '') {
  695. return $bestYm;
  696. }
  697. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  698. }
  699. protected function isPurchaseOrderDetailVoid(array $row): bool
  700. {
  701. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  702. return true;
  703. }
  704. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  705. }
  706. /**
  707. * 仅当前有效下发明细(排除废弃归档)
  708. */
  709. protected function applyActivePurchaseOrderDetailWhere($query): void
  710. {
  711. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  712. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  713. }
  714. /**
  715. * @param array<string, mixed> $detailRow
  716. */
  717. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  718. {
  719. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  720. return false;
  721. }
  722. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  723. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  724. }
  725. /**
  726. * 废弃退回初选:下发明细标记归档,不物理删除
  727. *
  728. * @param array<int, int|string> $scydgyIds
  729. */
  730. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  731. {
  732. $ids = [];
  733. foreach ($scydgyIds as $sid) {
  734. $n = (int)$sid;
  735. if ($this->isValidScydgyRowId($n) || $n < 0) {
  736. $ids[$n] = true;
  737. }
  738. }
  739. if ($ids === []) {
  740. return;
  741. }
  742. $void = ProcuremenStatus::POD_VOID;
  743. Db::table('purchase_order_detail')
  744. ->where('scydgy_id', 'in', array_keys($ids))
  745. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  746. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  747. ->update([
  748. 'status' => $void,
  749. 'status_name' => $void,
  750. ]);
  751. }
  752. /**
  753. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  754. */
  755. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  756. {
  757. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  758. $norm = function (string $col) use ($p): string {
  759. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  760. };
  761. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  762. $parts = [];
  763. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  764. if ($key === 'createtime') {
  765. $parts[] = $createtime;
  766. } else {
  767. $parts[] = $norm($key);
  768. }
  769. }
  770. return 'COALESCE(' . implode(', ', $parts) . ')';
  771. }
  772. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  773. {
  774. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  775. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  776. }
  777. /**
  778. * @return array<int, array<string, mixed>>
  779. */
  780. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  781. {
  782. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  783. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  784. try {
  785. $query = Db::table('purchase_order')->field($fields);
  786. $this->applyPurchaseOrderNotDeletedWhere($query);
  787. if ($stage === 'audit') {
  788. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  789. } elseif ($stage === 'confirm') {
  790. $this->applyPurchaseOrderConfirmStageWhere($query);
  791. } else {
  792. return [];
  793. }
  794. $query->order('pick_time', 'desc')->order('id', 'desc');
  795. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  796. $monthStart = $ym . '-01 00:00:00';
  797. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  798. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  799. }
  800. $rows = $query->select();
  801. } catch (\Throwable $e) {
  802. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  803. $rows = [];
  804. }
  805. return is_array($rows) ? $rows : [];
  806. }
  807. /**
  808. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  809. */
  810. protected function resolveProcuremenListStage(): string
  811. {
  812. $tab = trim((string)$this->request->request('wff_tab', ''));
  813. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  814. return $tab;
  815. }
  816. $action = strtolower((string)$this->request->action());
  817. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  818. return $action;
  819. }
  820. return 'pick';
  821. }
  822. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  823. {
  824. $rootTrue = rtrim((string)$this->request->root(true), '/');
  825. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  826. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  827. $indexPhpRoot = $rootTrue . '/index.php';
  828. }
  829. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  830. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  831. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  832. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  833. $this->view->assign('defaultYm', $defaultYm);
  834. $this->view->assign('sidebarYearMonths', $sidebar);
  835. $this->view->assign('procuremenStage', $stage);
  836. $this->view->assign('procuremenPageTitle', $pageTitle);
  837. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  838. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  839. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  840. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  841. }
  842. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  843. public function pick()
  844. {
  845. $this->request->filter(['strip_tags', 'trim']);
  846. if (!$this->request->isAjax()) {
  847. $this->assignProcuremenListPage('pick', '协助下发');
  848. return $this->view->fetch('procuremen/index');
  849. }
  850. return $this->index();
  851. }
  852. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  853. public function audit()
  854. {
  855. $this->request->filter(['strip_tags', 'trim']);
  856. if (!$this->request->isAjax()) {
  857. $this->assignProcuremenListPage('audit', '确认供应商');
  858. return $this->view->fetch('procuremen/index');
  859. }
  860. return $this->index();
  861. }
  862. /** 采购确认(定标) */
  863. public function confirm()
  864. {
  865. $this->request->filter(['strip_tags', 'trim']);
  866. if (!$this->request->isAjax()) {
  867. $this->assignProcuremenListPage('confirm', '采购确认');
  868. return $this->view->fetch('procuremen/index');
  869. }
  870. return $this->index();
  871. }
  872. /**
  873. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  874. */
  875. public function index()
  876. {
  877. $this->request->filter(['strip_tags', 'trim']);
  878. if (!$this->request->isAjax()) {
  879. $this->assignProcuremenListPage('pick', '协助下发');
  880. return $this->view->fetch('procuremen/index');
  881. }
  882. if ($this->request->request('keyField')) {
  883. return $this->selectpage();
  884. }
  885. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  886. $limit = max(10, min(500, (int)$limit));
  887. $ym = $this->request->request('ym', '');
  888. $ym = is_string($ym) ? trim($ym) : '';
  889. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  890. $wffTab = $this->resolveProcuremenListStage();
  891. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  892. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  893. ? $this->resolveProcuremenDefaultYm($wffTab)
  894. : date('Y-m');
  895. }
  896. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  897. $ym = date('Y-m');
  898. }
  899. $monthStart = $ym . '-01 00:00:00';
  900. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  901. $search = trim((string)$this->request->get('search', ''));
  902. $hasActiveSearch = ($search !== '');
  903. if (!$hasActiveSearch) {
  904. $filterStr = $this->request->get('filter', '');
  905. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  906. $arr = json_decode($filterStr, true);
  907. if (is_array($arr) && count($arr) > 0) {
  908. foreach ($arr as $v) {
  909. if (is_array($v)) {
  910. if (array_filter($v, function ($x) {
  911. return $x !== '' && $x !== null;
  912. })) {
  913. $hasActiveSearch = true;
  914. break;
  915. }
  916. } elseif ($v !== '' && $v !== null) {
  917. $hasActiveSearch = true;
  918. break;
  919. }
  920. }
  921. }
  922. }
  923. }
  924. $applyMonthRange = !$hasActiveSearch;
  925. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  926. $opArr = (array)json_decode($this->request->get('op', ''), true);
  927. try {
  928. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  929. if ($wffTab === 'audit') {
  930. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  931. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  932. );
  933. } elseif ($wffTab === 'confirm') {
  934. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  935. if ($dbRows === []) {
  936. try {
  937. $dbRows = Db::table('purchase_order')
  938. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  939. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  940. ->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%\')')
  941. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  942. ->order('pick_time', 'desc')->order('id', 'desc')
  943. ->select();
  944. } catch (\Throwable $e) {
  945. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  946. $dbRows = [];
  947. }
  948. }
  949. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  950. if ($pool === []) {
  951. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  952. }
  953. } else {
  954. $pool = $this->procuremenEnsureRedisPool();
  955. if (!is_array($pool)) {
  956. $pool = [];
  957. }
  958. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  959. $hideSet = $this->loadPickHiddenScydgySet();
  960. if ($pool !== [] && $hideSet !== []) {
  961. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  962. if (!is_array($r)) {
  963. return false;
  964. }
  965. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  966. return $id <= 0 || !isset($hideSet[$id]);
  967. }));
  968. }
  969. $manualPool = $this->loadPickManualOrderRows();
  970. if ($manualPool !== []) {
  971. $pool = array_merge($pool, $manualPool);
  972. }
  973. if ($pool === []) {
  974. return json([
  975. 'total' => 0,
  976. 'rows' => [],
  977. ]);
  978. }
  979. }
  980. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  981. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  982. $monthStart = $ym . '-01 00:00:00';
  983. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  984. }
  985. $filtered = $this->filterProcuremenIndexPool(
  986. $pool,
  987. $monthStart,
  988. $monthEnd,
  989. $applyMonthRange,
  990. $search,
  991. $filterArr,
  992. $opArr,
  993. $listTimePrimary
  994. );
  995. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  996. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  997. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  998. }
  999. $sortField = 'ID';
  1000. if (is_string($sort) && $sort !== '') {
  1001. $parts = explode(',', $sort);
  1002. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1003. if ($sortField === '') {
  1004. $sortField = 'ID';
  1005. }
  1006. }
  1007. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1008. $nFiltered = count($filtered);
  1009. if ($nFiltered > 1) {
  1010. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1011. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1012. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1013. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1014. if ($ta === $tb) {
  1015. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1016. }
  1017. if ($ta === '') {
  1018. return 1;
  1019. }
  1020. if ($tb === '') {
  1021. return -1;
  1022. }
  1023. return strcmp($ta, $tb) * $ord;
  1024. });
  1025. } elseif ($sortField === 'ID') {
  1026. $sortKeys = [];
  1027. foreach ($filtered as $i => $row) {
  1028. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1029. }
  1030. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1031. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1032. } elseif ($sortField === 'CCYDH') {
  1033. usort($filtered, function ($a, $b) use ($ord) {
  1034. $sa = trim((string)($a['CCYDH'] ?? ''));
  1035. $sb = trim((string)($b['CCYDH'] ?? ''));
  1036. if ($sa === $sb) {
  1037. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1038. }
  1039. if ($sa === '') {
  1040. return 1;
  1041. }
  1042. if ($sb === '') {
  1043. return -1;
  1044. }
  1045. return strcmp($sa, $sb) * $ord;
  1046. });
  1047. } else {
  1048. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1049. $va = $a[$sortField] ?? null;
  1050. $vb = $b[$sortField] ?? null;
  1051. $sa = (string)$va;
  1052. $sb = (string)$vb;
  1053. if ($sa === $sb) {
  1054. return 0;
  1055. }
  1056. return strcmp($sa, $sb) * $ord;
  1057. });
  1058. }
  1059. }
  1060. $offset = max(0, (int)$offset);
  1061. $limit = max(1, (int)$limit);
  1062. $rows = array_slice($filtered, $offset, $limit);
  1063. foreach ($rows as &$rw) {
  1064. if (!is_array($rw)) {
  1065. continue;
  1066. }
  1067. $rid = (int)($rw['ID'] ?? 0);
  1068. $rw['_iss_out'] = ($wffTab !== 'pick');
  1069. }
  1070. unset($rw);
  1071. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1072. $idList = [];
  1073. foreach ($rows as $rw) {
  1074. if (!is_array($rw)) {
  1075. continue;
  1076. }
  1077. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1078. foreach ($rw['_order_merge_rows'] as $mr) {
  1079. $mid = (int)($mr['ID'] ?? 0);
  1080. if ($this->isValidScydgyRowId($mid)) {
  1081. $idList[$mid] = true;
  1082. }
  1083. }
  1084. }
  1085. $id = (int)($rw['ID'] ?? 0);
  1086. if ($this->isValidScydgyRowId($id)) {
  1087. $idList[$id] = true;
  1088. }
  1089. }
  1090. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1091. foreach ($rows as &$rw) {
  1092. if (!is_array($rw)) {
  1093. continue;
  1094. }
  1095. $mergeIds = [];
  1096. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1097. foreach ($rw['_order_merge_rows'] as $mr) {
  1098. $mid = (int)($mr['ID'] ?? 0);
  1099. if ($this->isValidScydgyRowId($mid)) {
  1100. $mergeIds[$mid] = true;
  1101. }
  1102. }
  1103. }
  1104. $rid = (int)($rw['ID'] ?? 0);
  1105. if ($this->isValidScydgyRowId($rid)) {
  1106. $mergeIds[$rid] = true;
  1107. }
  1108. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1109. $rw['po_detail_count'] = $s['cnt'];
  1110. $rw['po_amount_fill_cnt'] = $s['amt'];
  1111. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1112. }
  1113. unset($rw);
  1114. }
  1115. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1116. $idList = [];
  1117. foreach ($rows as $rw) {
  1118. if (!is_array($rw)) {
  1119. continue;
  1120. }
  1121. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1122. foreach ($rw['_order_merge_rows'] as $mr) {
  1123. $mid = (int)($mr['ID'] ?? 0);
  1124. if ($this->isValidScydgyRowId($mid)) {
  1125. $idList[$mid] = true;
  1126. }
  1127. }
  1128. }
  1129. $id = (int)($rw['ID'] ?? 0);
  1130. if ($this->isValidScydgyRowId($id)) {
  1131. $idList[$id] = true;
  1132. }
  1133. }
  1134. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1135. $bidOpenSet = [];
  1136. if ($wffTab === 'audit') {
  1137. $ccydhList = [];
  1138. foreach ($rows as $rw0) {
  1139. if (!is_array($rw0)) {
  1140. continue;
  1141. }
  1142. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1143. if ($c0 !== '') {
  1144. $ccydhList[] = $c0;
  1145. }
  1146. }
  1147. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1148. }
  1149. foreach ($rows as &$rw) {
  1150. if (!is_array($rw)) {
  1151. continue;
  1152. }
  1153. $mergeIds = [];
  1154. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1155. foreach ($rw['_order_merge_rows'] as $mr) {
  1156. $mid = (int)($mr['ID'] ?? 0);
  1157. if ($this->isValidScydgyRowId($mid)) {
  1158. $mergeIds[$mid] = true;
  1159. }
  1160. }
  1161. }
  1162. $rid = (int)($rw['ID'] ?? 0);
  1163. if ($this->isValidScydgyRowId($rid)) {
  1164. $mergeIds[$rid] = true;
  1165. }
  1166. $buckets = [];
  1167. foreach (array_keys($mergeIds) as $mid) {
  1168. if (isset($quoteBucket[$mid])) {
  1169. $buckets[] = $quoteBucket[$mid];
  1170. }
  1171. }
  1172. $supplierText = $buckets !== []
  1173. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1174. : '';
  1175. if ($wffTab === 'confirm') {
  1176. $rw['picked_supplier_name'] = $supplierText;
  1177. } else {
  1178. $rw['notify_supplier_text'] = $supplierText;
  1179. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1180. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1181. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1182. $rw['bid_open_status_text'] = $verified ? '已开标' : '待开标';
  1183. }
  1184. }
  1185. unset($rw);
  1186. }
  1187. if ($wffTab === 'all' && count($rows) > 0) {
  1188. $this->mergePurchaseOrder($rows);
  1189. }
  1190. if ($wffTab === 'pick' && count($rows) > 0) {
  1191. $this->mergePurchaseOrder($rows);
  1192. }
  1193. foreach ($rows as &$rwClean) {
  1194. if (is_array($rwClean)) {
  1195. unset($rwClean['_order_merge_rows']);
  1196. if (array_key_exists('NGZL', $rwClean)) {
  1197. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1198. }
  1199. }
  1200. }
  1201. unset($rwClean);
  1202. return json([
  1203. 'total' => count($filtered),
  1204. 'rows' => $rows,
  1205. 'activeYm' => $ym,
  1206. ]);
  1207. } catch (\Throwable $e) {
  1208. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1209. return json([
  1210. 'total' => 0,
  1211. 'rows' => [],
  1212. ]);
  1213. }
  1214. }
  1215. /**
  1216. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1217. *
  1218. * @return array<int, true>
  1219. */
  1220. protected function loadPickHiddenScydgySet(): array
  1221. {
  1222. if ($this->pickHiddenScydgySetCache !== null) {
  1223. return $this->pickHiddenScydgySetCache;
  1224. }
  1225. $hideSet = [];
  1226. try {
  1227. $poIds = Db::table('purchase_order')
  1228. ->where(function ($q) {
  1229. $q->whereIn('wflow_status', array_merge(
  1230. ProcuremenStatus::wflowPendingConfirmValues(),
  1231. ProcuremenStatus::wflowPendingApprovalValues()
  1232. ))
  1233. ->whereOr(function ($q1) {
  1234. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1235. })
  1236. ->whereOr(function ($q2) {
  1237. $q2->whereNotNull('pick_time')
  1238. ->where('pick_time', '<>', '')
  1239. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1240. })
  1241. ->whereOr(function ($q3) {
  1242. $q3->whereNotNull('mod_rq')
  1243. ->where('mod_rq', '<>', '')
  1244. ->where('mod_rq', 'not like', '0000-00-00%');
  1245. });
  1246. })
  1247. ->column('scydgy_id');
  1248. if (is_array($poIds)) {
  1249. foreach ($poIds as $pid) {
  1250. $k = (int)$pid;
  1251. if ($k !== 0) {
  1252. $hideSet[$k] = true;
  1253. }
  1254. }
  1255. }
  1256. } catch (\Throwable $e) {
  1257. }
  1258. try {
  1259. $detIdsQuery = Db::table('purchase_order_detail');
  1260. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1261. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1262. if (is_array($detIds)) {
  1263. foreach ($detIds as $pid) {
  1264. $k = (int)$pid;
  1265. if ($this->isValidScydgyRowId($k)) {
  1266. $hideSet[$k] = true;
  1267. }
  1268. }
  1269. }
  1270. } catch (\Throwable $e) {
  1271. }
  1272. $this->pickHiddenScydgySetCache = $hideSet;
  1273. return $hideSet;
  1274. }
  1275. /**
  1276. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1277. *
  1278. * @return array<int, array<string, mixed>>
  1279. */
  1280. protected function loadPickManualOrderRows(): array
  1281. {
  1282. try {
  1283. $dbRows = Db::table('purchase_order')
  1284. ->where('scydgy_id', '<', 0)
  1285. ->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%\')')
  1286. ->order('scydgy_id', 'asc')
  1287. ->select();
  1288. } catch (\Throwable $e) {
  1289. try {
  1290. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1291. } catch (\Throwable $e2) {
  1292. return [];
  1293. }
  1294. }
  1295. if (!is_array($dbRows) || $dbRows === []) {
  1296. return [];
  1297. }
  1298. $detailSidSet = [];
  1299. try {
  1300. $negIds = [];
  1301. foreach ($dbRows as $dbRow) {
  1302. if (!is_array($dbRow)) {
  1303. continue;
  1304. }
  1305. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1306. if ($sid < 0) {
  1307. $negIds[$sid] = true;
  1308. }
  1309. }
  1310. if ($negIds !== []) {
  1311. $detQuery = Db::table('purchase_order_detail')
  1312. ->where('scydgy_id', 'in', array_keys($negIds));
  1313. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1314. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1315. if (is_array($detRows)) {
  1316. foreach ($detRows as $did) {
  1317. $detailSidSet[(int)$did] = true;
  1318. }
  1319. }
  1320. }
  1321. } catch (\Throwable $e) {
  1322. }
  1323. $pool = [];
  1324. foreach ($dbRows as $dbRow) {
  1325. if (!is_array($dbRow)) {
  1326. continue;
  1327. }
  1328. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1329. if ($sid >= 0) {
  1330. continue;
  1331. }
  1332. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1333. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1334. continue;
  1335. }
  1336. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1337. // 仅排除已完结;「进行中」含待下发的新建手工单,必须出现在初选
  1338. if ($st === ProcuremenStatus::PO_COMPLETED) {
  1339. continue;
  1340. }
  1341. if (isset($detailSidSet[$sid])) {
  1342. continue;
  1343. }
  1344. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1345. $r['_is_manual'] = 1;
  1346. $pool[] = $r;
  1347. }
  1348. return $pool;
  1349. }
  1350. /**
  1351. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1352. */
  1353. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1354. {
  1355. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1356. foreach ($keys as $k) {
  1357. $t = trim((string)($row[$k] ?? ''));
  1358. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1359. return $t;
  1360. }
  1361. }
  1362. return '';
  1363. }
  1364. /**
  1365. * 分配手工新增工序行 ID(负数递减)
  1366. */
  1367. protected function allocateManualScydgyId(): int
  1368. {
  1369. try {
  1370. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1371. $min = (int)$min;
  1372. return $min < 0 ? $min - 1 : -1;
  1373. } catch (\Throwable $e) {
  1374. return -1;
  1375. }
  1376. }
  1377. /**
  1378. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1379. */
  1380. protected function allocateManualOrderCcydh(): string
  1381. {
  1382. $prefix = 'YW' . date('Ymd');
  1383. $maxSeq = 0;
  1384. try {
  1385. $rows = Db::table('purchase_order')
  1386. ->where('CCYDH', 'like', $prefix . '%')
  1387. ->column('CCYDH');
  1388. if (is_array($rows)) {
  1389. foreach ($rows as $ccydh) {
  1390. $ccydh = trim((string)$ccydh);
  1391. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1392. $maxSeq = max($maxSeq, (int)$m[1]);
  1393. }
  1394. }
  1395. }
  1396. } catch (\Throwable $e) {
  1397. }
  1398. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1399. }
  1400. /**
  1401. * purchase_order.mod_rq 是否有有效软删除时间
  1402. */
  1403. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1404. {
  1405. $t = trim((string)$modRq);
  1406. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1407. }
  1408. /**
  1409. * 列表行 → purchase_order 写入字段
  1410. *
  1411. * @return array<string, mixed>
  1412. */
  1413. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1414. {
  1415. return [
  1416. 'scydgy_id' => $scydgyId,
  1417. 'CCYDH' => $row['CCYDH'] ?? null,
  1418. 'CYJMC' => $row['CYJMC'] ?? null,
  1419. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1420. 'CDXMC' => $row['CDXMC'] ?? null,
  1421. 'CGYBH' => $row['CGYBH'] ?? null,
  1422. 'CGYMC' => $row['CGYMC'] ?? null,
  1423. 'CDW' => $row['CDW'] ?? null,
  1424. 'NGZL' => $row['NGZL'] ?? null,
  1425. 'CDF' => $row['CDF'] ?? null,
  1426. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1427. 'MBZ' => $row['MBZ'] ?? null,
  1428. 'bwjg' => $row['bwjg'] ?? null,
  1429. 'iStatus' => $row['iStatus'] ?? null,
  1430. 'dStamp' => $row['dStamp'] ?? null,
  1431. 'dputrecord' => $row['dputrecord'] ?? null,
  1432. 'cywyxm' => $row['cywyxm'] ?? null,
  1433. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1434. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1435. ];
  1436. }
  1437. /**
  1438. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1439. *
  1440. * @return array{po:?array<string,mixed>, hidden:bool}
  1441. */
  1442. protected function resolvePickRowPoContext(int $sid): array
  1443. {
  1444. $po = null;
  1445. try {
  1446. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1447. if (is_array($found)) {
  1448. $po = $found;
  1449. }
  1450. } catch (\Throwable $e) {
  1451. }
  1452. $hideSet = $this->loadPickHiddenScydgySet();
  1453. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1454. }
  1455. /**
  1456. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1457. */
  1458. protected function assertPickRowCanDelete(int $sid, array $row): void
  1459. {
  1460. $ctx = $this->resolvePickRowPoContext($sid);
  1461. $po = $ctx['po'];
  1462. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1463. return;
  1464. }
  1465. if (is_array($po)) {
  1466. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1467. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1468. }
  1469. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1470. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1471. }
  1472. }
  1473. if ($ctx['hidden']) {
  1474. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1475. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1476. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1477. }
  1478. }
  1479. /**
  1480. * 初选直接完结前校验
  1481. */
  1482. protected function assertPickRowCanComplete(int $sid, array $row): void
  1483. {
  1484. $ctx = $this->resolvePickRowPoContext($sid);
  1485. $po = $ctx['po'];
  1486. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1487. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1488. }
  1489. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1490. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1491. }
  1492. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1493. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1494. }
  1495. }
  1496. /**
  1497. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1498. */
  1499. protected function softDeleteProcuremenPickRow(array $row): void
  1500. {
  1501. $sid = $this->extractScydgyRowId($row);
  1502. if (!$this->isValidScydgyRowId($sid)) {
  1503. throw new \InvalidArgumentException('无效的行主键');
  1504. }
  1505. $this->assertPickRowCanDelete($sid, $row);
  1506. $po = $this->resolvePickRowPoContext($sid)['po'];
  1507. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1508. return;
  1509. }
  1510. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1511. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1512. }
  1513. $now = date('Y-m-d H:i:s');
  1514. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1515. if (is_array($exists)) {
  1516. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1517. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1518. } else {
  1519. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1520. $data['mod_rq'] = $now;
  1521. $data['createtime'] = $now;
  1522. Db::table('purchase_order')->insert($data);
  1523. $poIdLog = (int)Db::getLastInsID();
  1524. }
  1525. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1526. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1527. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1528. if ($gymcLog !== '') {
  1529. $logTail .= ' / ' . $gymcLog;
  1530. }
  1531. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1532. }
  1533. /**
  1534. * 手工新增协助工序(写入 purchase_order)
  1535. *
  1536. * @param array<string, mixed> $params
  1537. * @return int scydgy_id
  1538. */
  1539. protected function saveManualPickOrder(array $params): int
  1540. {
  1541. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1542. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1543. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1544. if ($ccydh === '') {
  1545. $ccydh = $this->allocateManualOrderCcydh();
  1546. }
  1547. $now = date('Y-m-d H:i:s');
  1548. $sid = $this->allocateManualScydgyId();
  1549. $data = [
  1550. 'scydgy_id' => $sid,
  1551. 'CCYDH' => $ccydh,
  1552. 'CYJMC' => $cyjmc,
  1553. 'CGYMC' => $cgymc,
  1554. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1555. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1556. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1557. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1558. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1559. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1560. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1561. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1562. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1563. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1564. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  1565. 'createtime' => $now,
  1566. 'dStamp' => $now,
  1567. 'dputrecord' => $now,
  1568. ];
  1569. Db::table('purchase_order')->insert($data);
  1570. $poId = (int)Db::getLastInsID();
  1571. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1572. return $sid;
  1573. }
  1574. protected function formatProcuremenRowLabel(array $row): string
  1575. {
  1576. $dh = trim((string)($row['CCYDH'] ?? ''));
  1577. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1578. if ($dh !== '' && $gymc !== '') {
  1579. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1580. }
  1581. if ($dh !== '') {
  1582. return '订单「' . $dh . '」';
  1583. }
  1584. if ($gymc !== '') {
  1585. return '工序「' . $gymc . '」';
  1586. }
  1587. $id = $this->extractScydgyRowId($row);
  1588. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1589. }
  1590. /**
  1591. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1592. */
  1593. protected function extractScydgyRowId(array $row): int
  1594. {
  1595. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1596. }
  1597. protected function isValidScydgyRowId(int $id): bool
  1598. {
  1599. return ProcuremenGuard::isValidScydgyId($id);
  1600. }
  1601. protected function isManualScydgyRowId(int $id): bool
  1602. {
  1603. return $id < 0;
  1604. }
  1605. /**
  1606. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1607. *
  1608. * @param int[] $scydgyIds
  1609. * @return array<int, string[]>
  1610. */
  1611. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1612. {
  1613. $out = [];
  1614. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1615. if ($scydgyIds === []) {
  1616. return $out;
  1617. }
  1618. try {
  1619. $rows = Db::table('purchase_order_detail')
  1620. ->where('scydgy_id', 'in', $scydgyIds)
  1621. ->field('scydgy_id,company_name')
  1622. ->order('company_name', 'asc')
  1623. ->select();
  1624. } catch (\Throwable $e) {
  1625. $rows = [];
  1626. }
  1627. if (!is_array($rows)) {
  1628. return $out;
  1629. }
  1630. foreach ($rows as $r) {
  1631. if (!is_array($r)) {
  1632. continue;
  1633. }
  1634. $sid = (int)($r['scydgy_id'] ?? 0);
  1635. $cn = trim((string)($r['company_name'] ?? ''));
  1636. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1637. continue;
  1638. }
  1639. if (!isset($out[$sid])) {
  1640. $out[$sid] = [];
  1641. }
  1642. if (!in_array($cn, $out[$sid], true)) {
  1643. $out[$sid][] = $cn;
  1644. }
  1645. }
  1646. return $out;
  1647. }
  1648. /**
  1649. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1650. *
  1651. * @param string[] $names
  1652. */
  1653. protected function formatNotifySupplierDisplay(array $names): string
  1654. {
  1655. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1656. return trim((string)$n);
  1657. }, $names))));
  1658. if ($names === []) {
  1659. return '';
  1660. }
  1661. sort($names, SORT_STRING);
  1662. return implode("\n", $names);
  1663. }
  1664. /**
  1665. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1666. *
  1667. * @param int[] $scydgyIds
  1668. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1669. */
  1670. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1671. {
  1672. $out = [];
  1673. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1674. if ($scydgyIds === []) {
  1675. return $out;
  1676. }
  1677. try {
  1678. $rows = Db::table('purchase_order_detail')
  1679. ->where('scydgy_id', 'in', $scydgyIds)
  1680. ->field('scydgy_id,company_name,amount')
  1681. ->select();
  1682. } catch (\Throwable $e) {
  1683. $rows = [];
  1684. }
  1685. if (!is_array($rows)) {
  1686. return $out;
  1687. }
  1688. foreach ($rows as $r) {
  1689. if (!is_array($r)) {
  1690. continue;
  1691. }
  1692. $sid = (int)($r['scydgy_id'] ?? 0);
  1693. $cn = trim((string)($r['company_name'] ?? ''));
  1694. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1695. continue;
  1696. }
  1697. if (!isset($out[$sid])) {
  1698. $out[$sid] = ['all' => [], 'quoted' => []];
  1699. }
  1700. $out[$sid]['all'][$cn] = true;
  1701. $am = trim((string)($r['amount'] ?? ''));
  1702. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1703. $out[$sid]['quoted'][$cn] = true;
  1704. }
  1705. }
  1706. return $out;
  1707. }
  1708. /**
  1709. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1710. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1711. */
  1712. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1713. {
  1714. $merged = ['all' => [], 'quoted' => []];
  1715. foreach ($buckets as $b) {
  1716. if (!is_array($b)) {
  1717. continue;
  1718. }
  1719. foreach ($b['all'] ?? [] as $cn => $_) {
  1720. $merged['all'][$cn] = true;
  1721. }
  1722. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1723. $merged['quoted'][$cn] = true;
  1724. }
  1725. }
  1726. return $merged;
  1727. }
  1728. /**
  1729. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1730. */
  1731. protected function formatQuotedSupplierLines(array $bucket): string
  1732. {
  1733. $all = array_keys($bucket['all'] ?? []);
  1734. if ($all === []) {
  1735. return '';
  1736. }
  1737. sort($all, SORT_STRING);
  1738. $lines = [];
  1739. foreach ($all as $cn) {
  1740. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1741. $lines[] = $cn . '(' . $status . ')';
  1742. }
  1743. return implode("\n", $lines);
  1744. }
  1745. /**
  1746. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  1747. */
  1748. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  1749. {
  1750. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  1751. $this->view->engine->layout(false);
  1752. try {
  1753. $bodyHtml = $this->view->fetch($view);
  1754. $this->view->assign('dialogBody', $bodyHtml);
  1755. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  1756. return $this->view->fetch('procuremen/dialog_lite_shell');
  1757. } finally {
  1758. if ($restoreLayout) {
  1759. $this->view->engine->layout($restoreLayout);
  1760. }
  1761. }
  1762. }
  1763. /**
  1764. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1765. */
  1766. protected function resolveBundleSysRq(array $bundle): string
  1767. {
  1768. foreach ($bundle['pos'] ?? [] as $po) {
  1769. if (!is_array($po)) {
  1770. continue;
  1771. }
  1772. $sr = trim((string)($po['sys_rq'] ?? ''));
  1773. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1774. return $sr;
  1775. }
  1776. }
  1777. return '';
  1778. }
  1779. /**
  1780. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1781. */
  1782. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1783. {
  1784. $raw = trim((string)$sysRq);
  1785. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1786. return true;
  1787. }
  1788. $ts = strtotime(str_replace('T', ' ', $raw));
  1789. if ($ts === false || $ts <= 0) {
  1790. return true;
  1791. }
  1792. return time() >= $ts;
  1793. }
  1794. /**
  1795. * 开标前校验:必须已过报价截止时间
  1796. *
  1797. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1798. */
  1799. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1800. {
  1801. $sysRq = $this->resolveBundleSysRq($bundle);
  1802. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1803. $this->error('未到截止时间');
  1804. }
  1805. }
  1806. /**
  1807. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  1808. *
  1809. * @param array<string, mixed> $d
  1810. * @param string $deliveryYmd
  1811. */
  1812. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  1813. {
  1814. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  1815. return max(0, (int)$d['lead_days']);
  1816. }
  1817. if ($deliveryYmd === '') {
  1818. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  1819. }
  1820. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  1821. return null;
  1822. }
  1823. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  1824. $t2 = strtotime($m[1] . ' 00:00:00');
  1825. if ($t1 === false || $t2 === false) {
  1826. return null;
  1827. }
  1828. return max(0, (int)round(($t2 - $t1) / 86400));
  1829. }
  1830. /**
  1831. * @param int|null $days
  1832. */
  1833. protected function formatProcuremenLeadDaysText($days): string
  1834. {
  1835. if ($days === null || $days === '') {
  1836. return '未填写';
  1837. }
  1838. if (!is_numeric($days)) {
  1839. return '未填写';
  1840. }
  1841. return ((int)$days) . '天';
  1842. }
  1843. /**
  1844. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  1845. *
  1846. * @param array<string, mixed> $line
  1847. */
  1848. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  1849. {
  1850. $amountFilled = !empty($line['amount_filled']);
  1851. $deliveryFilled = !empty($line['delivery_filled']);
  1852. $leadFilled = !empty($line['lead_days_filled']);
  1853. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  1854. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  1855. $line['amount_show'] = '';
  1856. if (array_key_exists('amount_text', $line)) {
  1857. $line['amount_text'] = $line['unit_price_text'];
  1858. }
  1859. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  1860. $line['delivery_show'] = $deliveryText;
  1861. if (array_key_exists('delivery_text', $line)) {
  1862. $line['delivery_text'] = $deliveryText;
  1863. }
  1864. $line['delivery_ymd'] = '';
  1865. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  1866. $line['lead_days_show'] = $leadText;
  1867. $line['lead_days_text'] = $leadText;
  1868. $line['lead_days'] = '';
  1869. // 小计、操作时间与单价等同属报价信息,开标前不可见
  1870. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  1871. $line['subtotal_num'] = null;
  1872. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  1873. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  1874. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  1875. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  1876. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  1877. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  1878. $line['amount_filled'] = false;
  1879. $line['delivery_filled'] = false;
  1880. $line['lead_days_filled'] = false;
  1881. $line['is_quoted'] = false;
  1882. if (array_key_exists('quote_label', $line)) {
  1883. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  1884. }
  1885. }
  1886. protected function ensurePurchaseOrderBidOpenTable(): void
  1887. {
  1888. try {
  1889. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  1890. } catch (\Throwable $e) {
  1891. Db::execute(
  1892. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  1893. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  1894. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  1895. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  1896. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  1897. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  1898. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  1899. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  1900. `operator_name` varchar(64) NOT NULL DEFAULT '',
  1901. `createtime` datetime DEFAULT NULL,
  1902. PRIMARY KEY (`id`),
  1903. UNIQUE KEY `uk_ccydh` (`ccydh`)
  1904. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  1905. );
  1906. }
  1907. }
  1908. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  1909. {
  1910. $ccydh = trim($ccydh);
  1911. if ($ccydh === '') {
  1912. return false;
  1913. }
  1914. $this->ensurePurchaseOrderBidOpenTable();
  1915. try {
  1916. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1917. return is_array($row);
  1918. } catch (\Throwable $e) {
  1919. return false;
  1920. }
  1921. }
  1922. /**
  1923. * 批量查询订单是否已开标验证
  1924. *
  1925. * @param array<int, string> $ccydhs
  1926. * @return array<string, bool> ccydh => true
  1927. */
  1928. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  1929. {
  1930. $set = [];
  1931. $list = [];
  1932. foreach ($ccydhs as $c) {
  1933. $c = trim((string)$c);
  1934. if ($c !== '') {
  1935. $list[$c] = true;
  1936. }
  1937. }
  1938. if ($list === []) {
  1939. return $set;
  1940. }
  1941. $this->ensurePurchaseOrderBidOpenTable();
  1942. try {
  1943. $rows = Db::table('purchase_order_bid_open')
  1944. ->where('ccydh', 'in', array_keys($list))
  1945. ->field('ccydh')
  1946. ->select();
  1947. foreach ($rows as $row) {
  1948. if (!is_array($row)) {
  1949. continue;
  1950. }
  1951. $c = trim((string)($row['ccydh'] ?? ''));
  1952. if ($c !== '') {
  1953. $set[$c] = true;
  1954. }
  1955. }
  1956. } catch (\Throwable $e) {
  1957. return [];
  1958. }
  1959. return $set;
  1960. }
  1961. /**
  1962. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  1963. *
  1964. * @param array<string, mixed> $group
  1965. */
  1966. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  1967. {
  1968. if ($quoteVisible) {
  1969. $group['remark_quote_pending'] = 0;
  1970. return;
  1971. }
  1972. $group['remark'] = '';
  1973. $group['remark_quote_pending'] = 0;
  1974. }
  1975. /**
  1976. * @param array{ccydh?:string} $bundle
  1977. */
  1978. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  1979. {
  1980. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  1981. }
  1982. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  1983. {
  1984. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  1985. }
  1986. protected function loadBidOpenAdminUser(int $adminId): ?array
  1987. {
  1988. if ($adminId <= 0) {
  1989. return null;
  1990. }
  1991. try {
  1992. $row = Db::name('admin')->where('id', $adminId)->find();
  1993. } catch (\Throwable $e) {
  1994. return null;
  1995. }
  1996. if (!is_array($row)) {
  1997. return null;
  1998. }
  1999. $status = strtolower(trim((string)($row['status'] ?? '')));
  2000. if ($status !== '' && $status !== 'normal') {
  2001. return null;
  2002. }
  2003. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2004. return null;
  2005. }
  2006. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2007. if (!preg_match('/^1\d{10}$/', $phone)) {
  2008. return null;
  2009. }
  2010. $name = trim((string)($row['nickname'] ?? ''));
  2011. if ($name === '') {
  2012. $name = trim((string)($row['username'] ?? ''));
  2013. }
  2014. return [
  2015. 'id' => (int)$row['id'],
  2016. 'username' => trim((string)($row['username'] ?? '')),
  2017. 'nickname' => $name,
  2018. 'mobile' => $phone,
  2019. ];
  2020. }
  2021. /**
  2022. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2023. */
  2024. protected function bidOpenVerifierAuthGroupRootId(): int
  2025. {
  2026. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2027. return $id > 0 ? $id : 10;
  2028. }
  2029. /**
  2030. * @return int[]
  2031. */
  2032. protected function loadBidOpenVerifierAuthGroupIds(): array
  2033. {
  2034. static $memo = [];
  2035. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2036. if (isset($memo[$rootId])) {
  2037. return $memo[$rootId];
  2038. }
  2039. try {
  2040. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2041. } catch (\Throwable $e) {
  2042. $memo[$rootId] = [$rootId];
  2043. return $memo[$rootId];
  2044. }
  2045. if (!is_array($groups) || $groups === []) {
  2046. $memo[$rootId] = [$rootId];
  2047. return $memo[$rootId];
  2048. }
  2049. $groupList = [];
  2050. foreach ($groups as $g) {
  2051. if (is_array($g)) {
  2052. $groupList[] = $g;
  2053. }
  2054. }
  2055. if ($groupList === []) {
  2056. $memo[$rootId] = [$rootId];
  2057. return $memo[$rootId];
  2058. }
  2059. $tree = \fast\Tree::instance();
  2060. $tree->init($groupList);
  2061. $ids = $tree->getChildrenIds($rootId, true);
  2062. if (!is_array($ids) || $ids === []) {
  2063. $memo[$rootId] = [$rootId];
  2064. return $memo[$rootId];
  2065. }
  2066. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2067. return $memo[$rootId];
  2068. }
  2069. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2070. {
  2071. if ($adminId <= 0) {
  2072. return false;
  2073. }
  2074. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2075. if ($groupIds === []) {
  2076. return false;
  2077. }
  2078. try {
  2079. return (bool)Db::name('auth_group_access')
  2080. ->where('uid', $adminId)
  2081. ->where('group_id', 'in', $groupIds)
  2082. ->count();
  2083. } catch (\Throwable $e) {
  2084. return false;
  2085. }
  2086. }
  2087. /**
  2088. * @return array<int, array<string, mixed>>
  2089. */
  2090. protected function listBidOpenVerifierCandidates(): array
  2091. {
  2092. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2093. if ($groupIds === []) {
  2094. return [];
  2095. }
  2096. try {
  2097. $adminIds = Db::name('auth_group_access')
  2098. ->where('group_id', 'in', $groupIds)
  2099. ->column('uid');
  2100. } catch (\Throwable $e) {
  2101. $adminIds = [];
  2102. }
  2103. $adminIds = is_array($adminIds)
  2104. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  2105. : [];
  2106. if ($adminIds === []) {
  2107. return [];
  2108. }
  2109. try {
  2110. $rows = Db::name('admin')
  2111. ->where('status', 'normal')
  2112. ->where('id', 'in', $adminIds)
  2113. ->where('mobile', '<>', '')
  2114. ->order('id', 'asc')
  2115. ->select();
  2116. } catch (\Throwable $e) {
  2117. return [];
  2118. }
  2119. if (!is_array($rows)) {
  2120. return [];
  2121. }
  2122. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  2123. $out = [];
  2124. foreach ($rows as $row) {
  2125. if (!is_array($row)) {
  2126. continue;
  2127. }
  2128. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  2129. if ($one === null) {
  2130. continue;
  2131. }
  2132. $out[] = [
  2133. 'id' => $one['id'],
  2134. 'username' => $one['username'],
  2135. 'nickname' => $one['nickname'],
  2136. 'group_name' => $groupNameMap[$one['id']] ?? '',
  2137. 'mobile' => mask_phone($one['mobile']),
  2138. ];
  2139. }
  2140. return $out;
  2141. }
  2142. /**
  2143. * @param int[] $adminIds
  2144. * @return array<int, string>
  2145. */
  2146. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2147. {
  2148. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2149. if ($adminIds === []) {
  2150. return [];
  2151. }
  2152. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2153. try {
  2154. $rows = Db::name('auth_group_access')
  2155. ->alias('aga')
  2156. ->join('auth_group ag', 'aga.group_id = ag.id')
  2157. ->where('aga.uid', 'in', $adminIds)
  2158. ->where('aga.group_id', 'in', $groupIds)
  2159. ->field('aga.uid,ag.name')
  2160. ->order('aga.uid', 'asc')
  2161. ->order('aga.group_id', 'asc')
  2162. ->select();
  2163. } catch (\Throwable $e) {
  2164. return [];
  2165. }
  2166. if (!is_array($rows)) {
  2167. return [];
  2168. }
  2169. $out = [];
  2170. foreach ($rows as $row) {
  2171. if (!is_array($row)) {
  2172. continue;
  2173. }
  2174. $uid = (int)($row['uid'] ?? 0);
  2175. $name = trim((string)($row['name'] ?? ''));
  2176. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2177. continue;
  2178. }
  2179. $out[$uid] = $name;
  2180. }
  2181. return $out;
  2182. }
  2183. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2184. {
  2185. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2186. }
  2187. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2188. {
  2189. return 'procuremen_bidopen_wait_' . $adminId;
  2190. }
  2191. protected function renderBidOpenVerifySms(string $code): string
  2192. {
  2193. $tpl = '';
  2194. try {
  2195. $row = $this->loadNotifyTemplateRow('bid_open');
  2196. if (is_array($row)) {
  2197. $tpl = trim((string)($row['content'] ?? ''));
  2198. }
  2199. } catch (\Throwable $e) {
  2200. $tpl = '';
  2201. }
  2202. if ($tpl === '') {
  2203. $tpl = '【可集达】您的短信验证码是{code}';
  2204. }
  2205. return str_replace('{code}', $code, $tpl);
  2206. }
  2207. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2208. {
  2209. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2210. }
  2211. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2212. {
  2213. $code = trim($code);
  2214. if (!preg_match('/^\d{6}$/', $code)) {
  2215. return false;
  2216. }
  2217. $mock = Config::get('mproc.mock_sms_code');
  2218. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2219. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2220. return true;
  2221. }
  2222. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2223. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2224. return false;
  2225. }
  2226. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2227. return true;
  2228. }
  2229. /**
  2230. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2231. */
  2232. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2233. {
  2234. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2235. if ($ccydh === '') {
  2236. throw new \InvalidArgumentException('订单号无效');
  2237. }
  2238. $this->ensurePurchaseOrderBidOpenTable();
  2239. list($operatorId, $operatorName) = $this->GetUseName();
  2240. $now = date('Y-m-d H:i:s');
  2241. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2242. $payload = [
  2243. 'ccydh' => $ccydh,
  2244. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2245. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2246. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2247. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2248. 'operator_id' => (int)$operatorId,
  2249. 'operator_name' => trim((string)$operatorName),
  2250. 'createtime' => $now,
  2251. ];
  2252. if (is_array($exists)) {
  2253. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2254. } else {
  2255. Db::table('purchase_order_bid_open')->insert($payload);
  2256. }
  2257. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2258. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2259. $orderPart = '(订单' . $ccydh . ')';
  2260. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2261. $seenSid = [];
  2262. foreach ($bundle['pos'] ?? [] as $poRow) {
  2263. if (!is_array($poRow)) {
  2264. continue;
  2265. }
  2266. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2267. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2268. continue;
  2269. }
  2270. $seenSid[$sid] = true;
  2271. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2272. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2273. }
  2274. if ($seenSid === []) {
  2275. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2276. if ($this->isValidScydgyRowId($anchor)) {
  2277. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2278. }
  2279. }
  2280. // 开标通过后计算并写入供应商服务评分
  2281. try {
  2282. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  2283. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  2284. } catch (\Throwable $e) {
  2285. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  2286. }
  2287. }
  2288. /**
  2289. * 报价行展示字段默认值(模板安全访问)
  2290. *
  2291. * @param array<string, mixed> $line
  2292. * @return array<string, mixed>
  2293. */
  2294. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2295. {
  2296. if (!array_key_exists('amount_quote_pending', $line)) {
  2297. $line['amount_quote_pending'] = 0;
  2298. }
  2299. if (!array_key_exists('delivery_quote_pending', $line)) {
  2300. $line['delivery_quote_pending'] = 0;
  2301. }
  2302. if (!array_key_exists('quote_before_deadline', $line)) {
  2303. $line['quote_before_deadline'] = 0;
  2304. }
  2305. if (!array_key_exists('amount_filled', $line)) {
  2306. $line['amount_filled'] = 0;
  2307. }
  2308. if (!array_key_exists('delivery_filled', $line)) {
  2309. $line['delivery_filled'] = 0;
  2310. }
  2311. if (!array_key_exists('lead_days_filled', $line)) {
  2312. $line['lead_days_filled'] = 0;
  2313. }
  2314. if (!array_key_exists('lead_days_quote_pending', $line)) {
  2315. $line['lead_days_quote_pending'] = 0;
  2316. }
  2317. if (!array_key_exists('lead_days_show', $line)) {
  2318. $line['lead_days_show'] = '未填写';
  2319. }
  2320. if (!array_key_exists('lead_days_text', $line)) {
  2321. $line['lead_days_text'] = $line['lead_days_show'];
  2322. }
  2323. return $line;
  2324. }
  2325. /**
  2326. * 审核弹窗:按供应商汇总报价明细
  2327. *
  2328. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2329. * @return array<int, array<string, mixed>>
  2330. */
  2331. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2332. {
  2333. $sids = [];
  2334. foreach ($bundle['pos'] ?? [] as $po) {
  2335. if (!is_array($po)) {
  2336. continue;
  2337. }
  2338. $sid = (int)($po['scydgy_id'] ?? 0);
  2339. if ($this->isValidScydgyRowId($sid)) {
  2340. $sids[$sid] = true;
  2341. }
  2342. }
  2343. if ($sids === []) {
  2344. return [];
  2345. }
  2346. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2347. $gymcMap = [];
  2348. $qtyBySid = [];
  2349. $orderedSids = [];
  2350. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2351. if (!is_array($mr)) {
  2352. continue;
  2353. }
  2354. $gid = $this->extractScydgyRowId($mr);
  2355. if ($this->isValidScydgyRowId($gid)) {
  2356. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2357. $orderedSids[] = $gid;
  2358. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2359. if ($qty === '') {
  2360. $qty = trim((string)($mr['NGZL'] ?? ''));
  2361. }
  2362. $qtyBySid[$gid] = $qty;
  2363. }
  2364. }
  2365. foreach ($bundle['pos'] ?? [] as $po) {
  2366. if (!is_array($po)) {
  2367. continue;
  2368. }
  2369. $gid = (int)($po['scydgy_id'] ?? 0);
  2370. if ($this->isValidScydgyRowId($gid)) {
  2371. $nm = trim((string)($po['CGYMC'] ?? ''));
  2372. if ($nm !== '') {
  2373. $gymcMap[$gid] = $nm;
  2374. }
  2375. if (!in_array($gid, $orderedSids, true)) {
  2376. $orderedSids[] = $gid;
  2377. }
  2378. }
  2379. }
  2380. try {
  2381. $detailsQuery = Db::table('purchase_order_detail')
  2382. ->where('scydgy_id', 'in', array_keys($sids));
  2383. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2384. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2385. } catch (\Throwable $e) {
  2386. try {
  2387. $detailsQuery = Db::table('purchase_order_detail')
  2388. ->where('scydgy_id', 'in', array_keys($sids));
  2389. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2390. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2391. } catch (\Throwable $e2) {
  2392. $details = [];
  2393. }
  2394. }
  2395. if (!is_array($details)) {
  2396. $details = [];
  2397. }
  2398. $byCompany = [];
  2399. foreach ($details as $d) {
  2400. if (!is_array($d)) {
  2401. continue;
  2402. }
  2403. $cn = trim((string)($d['company_name'] ?? ''));
  2404. if ($cn === '') {
  2405. continue;
  2406. }
  2407. if (!isset($byCompany[$cn])) {
  2408. $ph = trim((string)($d['phone'] ?? ''));
  2409. $username = trim((string)($d['username'] ?? ''));
  2410. if ($username === '') {
  2411. $username = $this->resolveCustomerContactName($ph, $cn);
  2412. }
  2413. $byCompany[$cn] = [
  2414. 'name' => $cn,
  2415. 'email' => trim((string)($d['email'] ?? '')),
  2416. 'phone' => $ph,
  2417. 'username' => $username,
  2418. 'remark' => '',
  2419. 'has_quote' => false,
  2420. 'lines_map' => [],
  2421. ];
  2422. }
  2423. if ($byCompany[$cn]['remark'] === '') {
  2424. $rm = '';
  2425. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2426. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2427. $rm = trim((string)$d[$rk]);
  2428. break;
  2429. }
  2430. }
  2431. if ($rm !== '') {
  2432. $byCompany[$cn]['remark'] = $rm;
  2433. }
  2434. }
  2435. $sid = (int)($d['scydgy_id'] ?? 0);
  2436. $am = trim((string)($d['amount'] ?? ''));
  2437. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2438. if ($gymc === '') {
  2439. $gymc = '工序';
  2440. }
  2441. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2442. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2443. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2444. $deliveryShow = $deliveryRaw;
  2445. }
  2446. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2447. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2448. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2449. $subtotal = null;
  2450. if ($amountNum !== null) {
  2451. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2452. }
  2453. $unitPriceText = $amountFilled
  2454. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2455. : '未填写';
  2456. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2457. $leadFilled = ($leadDays !== null);
  2458. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2459. $lineRow = [
  2460. 'cgymc' => $gymc,
  2461. 'amount' => $am,
  2462. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2463. 'amount_filled' => $amountFilled,
  2464. 'unit_price_text' => $unitPriceText,
  2465. 'delivery' => $deliveryRaw,
  2466. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2467. 'delivery_filled' => $deliveryFilled,
  2468. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2469. 'lead_days' => $leadFilled ? $leadDays : '',
  2470. 'lead_days_filled'=> $leadFilled,
  2471. 'lead_days_show' => $leadText,
  2472. 'lead_days_text' => $leadText,
  2473. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2474. 'subtotal_num' => $subtotal,
  2475. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2476. 'is_quoted' => $amountFilled,
  2477. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2478. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2479. ];
  2480. if (!$quoteVisible) {
  2481. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2482. }
  2483. // 按工序 id 暂存,下面再按上方工序表顺序输出
  2484. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2485. }
  2486. foreach ($byCompany as $cn => $g) {
  2487. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  2488. $lines = [];
  2489. $usedSids = [];
  2490. foreach ($orderedSids as $sid) {
  2491. if (!isset($linesMap[$sid])) {
  2492. continue;
  2493. }
  2494. $lines[] = $linesMap[$sid];
  2495. $usedSids[$sid] = true;
  2496. }
  2497. foreach ($linesMap as $sid => $ln) {
  2498. if (isset($usedSids[$sid])) {
  2499. continue;
  2500. }
  2501. $lines[] = $ln;
  2502. }
  2503. $total = count($lines);
  2504. $quoted = 0;
  2505. $groupTotal = 0.0;
  2506. $groupHasTotal = false;
  2507. if ($quoteVisible) {
  2508. foreach ($lines as $ln) {
  2509. $am = trim((string)($ln['amount'] ?? ''));
  2510. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2511. $quoted++;
  2512. }
  2513. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2514. $groupTotal += (float)$ln['subtotal_num'];
  2515. $groupHasTotal = true;
  2516. }
  2517. }
  2518. }
  2519. unset($byCompany[$cn]['lines_map']);
  2520. $byCompany[$cn]['lines'] = $lines;
  2521. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2522. $byCompany[$cn]['line_count'] = $total;
  2523. $byCompany[$cn]['has_total'] = $total > 0;
  2524. $byCompany[$cn]['has_remark'] = $total > 0;
  2525. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  2526. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2527. // 工序行 + 备注行 + 总计行
  2528. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  2529. }
  2530. $groups = array_values($byCompany);
  2531. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2532. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  2533. }
  2534. /**
  2535. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2536. *
  2537. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2538. * @return array<int, array<string, mixed>>
  2539. */
  2540. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2541. {
  2542. $sids = [];
  2543. $poIdMap = [];
  2544. foreach ($bundle['pos'] ?? [] as $po) {
  2545. if (!is_array($po)) {
  2546. continue;
  2547. }
  2548. $sid = (int)($po['scydgy_id'] ?? 0);
  2549. if ($this->isValidScydgyRowId($sid)) {
  2550. $sids[$sid] = true;
  2551. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2552. }
  2553. }
  2554. if ($sids === []) {
  2555. return [];
  2556. }
  2557. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2558. $gymcMap = [];
  2559. $qtyBySid = [];
  2560. $orderedSids = [];
  2561. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2562. if (!is_array($mr)) {
  2563. continue;
  2564. }
  2565. $gid = $this->extractScydgyRowId($mr);
  2566. if ($this->isValidScydgyRowId($gid)) {
  2567. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2568. $orderedSids[] = $gid;
  2569. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2570. if ($qty === '') {
  2571. $qty = trim((string)($mr['NGZL'] ?? ''));
  2572. }
  2573. $qtyBySid[$gid] = $qty;
  2574. }
  2575. }
  2576. foreach ($bundle['pos'] ?? [] as $po) {
  2577. if (!is_array($po)) {
  2578. continue;
  2579. }
  2580. $gid = (int)($po['scydgy_id'] ?? 0);
  2581. if ($this->isValidScydgyRowId($gid)) {
  2582. $nm = trim((string)($po['CGYMC'] ?? ''));
  2583. if ($nm !== '') {
  2584. $gymcMap[$gid] = $nm;
  2585. }
  2586. }
  2587. }
  2588. try {
  2589. $details = Db::table('purchase_order_detail')
  2590. ->where('scydgy_id', 'in', array_keys($sids))
  2591. ->order('company_name', 'asc')
  2592. ->order('id', 'asc')
  2593. ->select();
  2594. } catch (\Throwable $e) {
  2595. try {
  2596. $details = Db::table('purchase_order_detail')
  2597. ->where('scydgy_id', 'in', array_keys($sids))
  2598. ->order('company_name', 'asc')
  2599. ->order('ID', 'asc')
  2600. ->select();
  2601. } catch (\Throwable $e2) {
  2602. $details = [];
  2603. }
  2604. }
  2605. if (!is_array($details)) {
  2606. $details = [];
  2607. }
  2608. $byCompany = [];
  2609. foreach ($details as $d) {
  2610. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2611. continue;
  2612. }
  2613. $cn = trim((string)($d['company_name'] ?? ''));
  2614. if ($cn === '') {
  2615. continue;
  2616. }
  2617. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2618. $sid = (int)($d['scydgy_id'] ?? 0);
  2619. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2620. continue;
  2621. }
  2622. if (!isset($byCompany[$cn])) {
  2623. $ph = trim((string)($d['phone'] ?? ''));
  2624. $username = trim((string)($d['username'] ?? ''));
  2625. if ($username === '') {
  2626. $username = $this->resolveCustomerContactName($ph, $cn);
  2627. }
  2628. $byCompany[$cn] = [
  2629. 'name' => $cn,
  2630. 'email' => trim((string)($d['email'] ?? '')),
  2631. 'phone' => $ph,
  2632. 'username' => $username,
  2633. 'remark' => '',
  2634. 'pick_lines' => [],
  2635. 'detail_picks' => [],
  2636. ];
  2637. }
  2638. if ($byCompany[$cn]['remark'] === '') {
  2639. $rm = '';
  2640. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2641. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2642. $rm = trim((string)$d[$rk]);
  2643. break;
  2644. }
  2645. }
  2646. if ($rm !== '') {
  2647. $byCompany[$cn]['remark'] = $rm;
  2648. }
  2649. }
  2650. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2651. if ($gymc === '') {
  2652. $gymc = '工序';
  2653. }
  2654. $am = trim((string)($d['amount'] ?? ''));
  2655. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2656. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2657. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2658. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2659. $deliveryShow = $deliveryRaw;
  2660. }
  2661. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2662. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2663. $subtotal = null;
  2664. if ($amountNum !== null) {
  2665. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2666. }
  2667. $unitPriceText = $amountFilled
  2668. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2669. : '未填写';
  2670. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2671. $leadFilled = ($leadDays !== null);
  2672. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2673. $pickLine = [
  2674. 'cgymc' => $gymc,
  2675. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2676. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2677. 'amount_filled' => $amountFilled,
  2678. 'delivery_filled' => $deliveryFilled,
  2679. 'unit_price_text' => $unitPriceText,
  2680. 'lead_days' => $leadFilled ? $leadDays : '',
  2681. 'lead_days_filled'=> $leadFilled,
  2682. 'lead_days_show' => $leadText,
  2683. 'lead_days_text' => $leadText,
  2684. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2685. 'subtotal_num' => $subtotal,
  2686. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2687. 'is_quoted' => $amountFilled,
  2688. ];
  2689. if (!$quoteVisible) {
  2690. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2691. }
  2692. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2693. $byCompany[$cn]['detail_picks'][$sid] = [
  2694. 'scydgy_id' => $sid,
  2695. 'detail_id' => $detailId,
  2696. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2697. 'cgymc' => $gymc,
  2698. ];
  2699. }
  2700. $out = [];
  2701. foreach ($byCompany as $g) {
  2702. $pickLinesMap = $g['pick_lines'] ?? [];
  2703. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2704. continue;
  2705. }
  2706. $pickLines = [];
  2707. $usedLineSids = [];
  2708. foreach ($orderedSids as $sid) {
  2709. if (!isset($pickLinesMap[$sid])) {
  2710. continue;
  2711. }
  2712. $pickLines[] = $pickLinesMap[$sid];
  2713. $usedLineSids[$sid] = true;
  2714. }
  2715. foreach ($pickLinesMap as $sid => $ln) {
  2716. if (isset($usedLineSids[$sid])) {
  2717. continue;
  2718. }
  2719. $pickLines[] = $ln;
  2720. }
  2721. $groupTotal = 0.0;
  2722. $groupHasTotal = false;
  2723. if ($quoteVisible) {
  2724. foreach ($pickLines as $ln) {
  2725. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2726. $groupTotal += (float)$ln['subtotal_num'];
  2727. $groupHasTotal = true;
  2728. }
  2729. }
  2730. }
  2731. $lineCount = count($pickLines);
  2732. $g['pick_lines'] = $pickLines;
  2733. $g['line_count'] = $lineCount;
  2734. $g['has_total'] = $lineCount > 0;
  2735. $g['has_remark'] = $lineCount > 0;
  2736. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  2737. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2738. // 工序行 + 备注行 + 总计行
  2739. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  2740. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  2741. $detailPicks = [];
  2742. $usedPickSids = [];
  2743. foreach ($orderedSids as $sid) {
  2744. if (!isset($detailPicksMap[$sid])) {
  2745. continue;
  2746. }
  2747. $detailPicks[] = $detailPicksMap[$sid];
  2748. $usedPickSids[$sid] = true;
  2749. }
  2750. foreach ($detailPicksMap as $sid => $dp) {
  2751. if (isset($usedPickSids[$sid])) {
  2752. continue;
  2753. }
  2754. $detailPicks[] = $dp;
  2755. }
  2756. $g['detail_picks'] = $detailPicks;
  2757. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2758. unset($g['detail_picks']);
  2759. $out[] = $g;
  2760. }
  2761. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2762. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  2763. }
  2764. /**
  2765. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2766. * @return array<int, int[]> scydgy_id => detail_id[]
  2767. */
  2768. protected function mapDetailIdsByScydgyId(array $details): array
  2769. {
  2770. $out = [];
  2771. foreach ($details as $d) {
  2772. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2773. continue;
  2774. }
  2775. $sid = (int)($d['scydgy_id'] ?? 0);
  2776. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2777. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2778. continue;
  2779. }
  2780. if (!isset($out[$sid])) {
  2781. $out[$sid] = [];
  2782. }
  2783. $out[$sid][] = $pk;
  2784. }
  2785. foreach ($out as $sid => $ids) {
  2786. $out[$sid] = array_values(array_unique($ids));
  2787. }
  2788. return $out;
  2789. }
  2790. /**
  2791. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2792. *
  2793. * @param array<string, mixed> $dbRow
  2794. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2795. */
  2796. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2797. {
  2798. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2799. $r = [
  2800. 'ID' => $sid,
  2801. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2802. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2803. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2804. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2805. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2806. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2807. 'CDW' => $dbRow['CDW'] ?? '',
  2808. 'NGZL' => $dbRow['NGZL'] ?? '',
  2809. 'CDF' => $dbRow['CDF'] ?? '',
  2810. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2811. 'MBZ' => $dbRow['MBZ'] ?? '',
  2812. 'bwjg' => $dbRow['bwjg'] ?? '',
  2813. 'iStatus' => $dbRow['iStatus'] ?? '',
  2814. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2815. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2816. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2817. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2818. 'dStamp' => $dbRow['dStamp'] ?? '',
  2819. 'pick_time' => $dbRow['pick_time'] ?? '',
  2820. ];
  2821. if ($sid > 0 && isset($dStampMap[$sid])) {
  2822. $t = trim((string)$dStampMap[$sid]);
  2823. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2824. $r['dStamp'] = $dStampMap[$sid];
  2825. }
  2826. }
  2827. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2828. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2829. $ct = $dbRow['createtime'];
  2830. if (is_numeric($ct) && (int)$ct > 946684800) {
  2831. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2832. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2833. $r['dStamp'] = trim($ct);
  2834. }
  2835. }
  2836. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2837. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2838. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2839. $fallback = trim((string)($r['dStamp'] ?? ''));
  2840. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2841. $r['dputrecord'] = $fallback;
  2842. }
  2843. }
  2844. if (array_key_exists('id', $dbRow)) {
  2845. $r['purchase_order_id'] = (int)$dbRow['id'];
  2846. }
  2847. if ($sid < 0) {
  2848. $r['_is_manual'] = 1;
  2849. }
  2850. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2851. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2852. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2853. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2854. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2855. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2856. $r['pick_time'] = $pickFallback;
  2857. break;
  2858. }
  2859. }
  2860. }
  2861. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2862. if ($pickNm !== '') {
  2863. $r['pick_company_name'] = $pickNm;
  2864. $r['picked_supplier_name'] = $pickNm;
  2865. }
  2866. return $r;
  2867. }
  2868. /**
  2869. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2870. *
  2871. * @return array<int, array<string, mixed>>
  2872. */
  2873. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2874. {
  2875. $pool = [];
  2876. if (!is_array($dbRows) || $dbRows === []) {
  2877. return $pool;
  2878. }
  2879. $dStampMap = [];
  2880. $sidList = [];
  2881. foreach ($dbRows as $tmpRow) {
  2882. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2883. $sid = (int)$tmpRow['scydgy_id'];
  2884. if ($sid > 0) {
  2885. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2886. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2887. $sidList[$sid] = true;
  2888. }
  2889. }
  2890. }
  2891. }
  2892. if ($sidList !== []) {
  2893. try {
  2894. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2895. } catch (\Throwable $e) {
  2896. $dStampMap = [];
  2897. }
  2898. }
  2899. foreach ($dbRows as $dbRow) {
  2900. if (!is_array($dbRow)) {
  2901. continue;
  2902. }
  2903. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2904. }
  2905. return $pool;
  2906. }
  2907. /**
  2908. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2909. *
  2910. * @param int[] $scydgyIds
  2911. * @return array<int, array<string, mixed>>
  2912. */
  2913. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2914. {
  2915. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2916. if ($scydgyIds === []) {
  2917. return [];
  2918. }
  2919. try {
  2920. $list = Db::table('purchase_order_detail')
  2921. ->where('scydgy_id', 'in', $scydgyIds)
  2922. ->field('scydgy_id,company_name,amount,delivery')
  2923. ->select();
  2924. } catch (\Throwable $e) {
  2925. $list = [];
  2926. }
  2927. return is_array($list) ? $list : [];
  2928. }
  2929. /**
  2930. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2931. *
  2932. * @param int[] $scydgyIds
  2933. * @param array<int, array<string, mixed>> $allRows
  2934. * @return array{cnt:int, amt:int, deliv:int}
  2935. */
  2936. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2937. {
  2938. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2939. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2940. if ($scydgyIds === [] || $allRows === []) {
  2941. return $out;
  2942. }
  2943. $idSet = array_flip($scydgyIds);
  2944. $all = [];
  2945. $withAmt = [];
  2946. $withDeliv = [];
  2947. foreach ($allRows as $r) {
  2948. if (!is_array($r)) {
  2949. continue;
  2950. }
  2951. $sid = (int)($r['scydgy_id'] ?? 0);
  2952. if (!isset($idSet[$sid])) {
  2953. continue;
  2954. }
  2955. $cn = trim((string)($r['company_name'] ?? ''));
  2956. if ($cn === '') {
  2957. continue;
  2958. }
  2959. $all[$cn] = true;
  2960. $am = $r['amount'] ?? null;
  2961. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2962. $withAmt[$cn] = true;
  2963. }
  2964. $dv = $r['delivery'] ?? null;
  2965. if ($dv !== null && trim((string)$dv) !== '') {
  2966. $withDeliv[$cn] = true;
  2967. }
  2968. }
  2969. return [
  2970. 'cnt' => count($all),
  2971. 'amt' => count($withAmt),
  2972. 'deliv' => count($withDeliv),
  2973. ];
  2974. }
  2975. /**
  2976. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2977. *
  2978. * @param int[] $scydgyIds
  2979. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2980. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2981. */
  2982. protected function OrderDetailSummary(array $scydgyIds)
  2983. {
  2984. $out = [];
  2985. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2986. if ($scydgyIds === []) {
  2987. return $out;
  2988. }
  2989. $list = [];
  2990. try {
  2991. $list = Db::table('purchase_order_detail')
  2992. ->where('scydgy_id', 'in', $scydgyIds)
  2993. ->field('id,scydgy_id,amount,delivery')
  2994. ->select();
  2995. } catch (\Throwable $e) {
  2996. $list = [];
  2997. }
  2998. if (!is_array($list)) {
  2999. return $out;
  3000. }
  3001. foreach ($list as $r) {
  3002. if (!is_array($r)) {
  3003. continue;
  3004. }
  3005. $ids = (int)($r['scydgy_id'] ?? 0);
  3006. if (!$this->isValidScydgyRowId($ids)) {
  3007. continue;
  3008. }
  3009. if (!isset($out[$ids])) {
  3010. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3011. }
  3012. $out[$ids]['cnt']++;
  3013. $am = $r['amount'] ?? null;
  3014. if ($am !== null && $am !== '') {
  3015. if (!(is_string($am) && trim($am) === '')) {
  3016. $out[$ids]['amt']++;
  3017. }
  3018. }
  3019. $dv = $r['delivery'] ?? null;
  3020. if ($dv !== null && trim((string)$dv) !== '') {
  3021. $out[$ids]['deliv']++;
  3022. }
  3023. }
  3024. return $out;
  3025. }
  3026. /**
  3027. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  3028. *
  3029. * @return array
  3030. */
  3031. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  3032. {
  3033. $strContains = function ($haystack, $needle) {
  3034. if ($needle === '') {
  3035. return false;
  3036. }
  3037. $haystack = (string)$haystack;
  3038. if (function_exists('mb_stripos')) {
  3039. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  3040. }
  3041. return stripos($haystack, $needle) !== false;
  3042. };
  3043. $stripAlias = function ($f) {
  3044. return preg_replace('/^[ab]\./i', '', (string)$f);
  3045. };
  3046. $searchColNames = [];
  3047. foreach (explode(',', $this->searchFields) as $colRaw) {
  3048. $c = $stripAlias(trim($colRaw));
  3049. if ($c !== '') {
  3050. $searchColNames[] = $c;
  3051. }
  3052. }
  3053. $filtered = [];
  3054. foreach ($pool as $r) {
  3055. if (!is_array($r)) {
  3056. continue;
  3057. }
  3058. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  3059. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  3060. if (!$isManual) {
  3061. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  3062. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  3063. continue;
  3064. }
  3065. if ($applyMonthRange) {
  3066. $mo = (int)$m[2];
  3067. if ($mo < 1 || $mo > 12) {
  3068. continue;
  3069. }
  3070. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3071. $rowMonthStart = $ymRow . '-01 00:00:00';
  3072. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3073. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3074. continue;
  3075. }
  3076. }
  3077. } elseif ($applyMonthRange) {
  3078. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  3079. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3080. $ds = $listTime;
  3081. }
  3082. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  3083. continue;
  3084. }
  3085. $mo = (int)$m[2];
  3086. if ($mo < 1 || $mo > 12) {
  3087. continue;
  3088. }
  3089. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3090. $rowMonthStart = $ymRow . '-01 00:00:00';
  3091. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3092. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3093. continue;
  3094. }
  3095. }
  3096. if ($search !== '') {
  3097. $hitSearch = false;
  3098. foreach ($searchColNames as $c) {
  3099. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  3100. if ($cell !== '' && $strContains($cell, $search)) {
  3101. $hitSearch = true;
  3102. break;
  3103. }
  3104. }
  3105. if (!$hitSearch) {
  3106. continue;
  3107. }
  3108. }
  3109. foreach ($filterArr as $fk => $fv) {
  3110. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  3111. continue;
  3112. }
  3113. if (is_array($fv)) {
  3114. continue;
  3115. }
  3116. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  3117. continue;
  3118. }
  3119. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  3120. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  3121. $field = $stripAlias($fk);
  3122. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  3123. $cellStr = trim((string)$cell);
  3124. switch ($sym) {
  3125. case '=':
  3126. if ((string)$cell !== (string)$fv) {
  3127. continue 3;
  3128. }
  3129. break;
  3130. case '<>':
  3131. if ((string)$cell === (string)$fv) {
  3132. continue 3;
  3133. }
  3134. break;
  3135. case 'LIKE':
  3136. case 'NOT LIKE':
  3137. $needle = trim((string)$fv);
  3138. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  3139. if ($sym === 'LIKE' && !$hit) {
  3140. continue 3;
  3141. }
  3142. if ($sym === 'NOT LIKE' && $hit) {
  3143. continue 3;
  3144. }
  3145. break;
  3146. case '>':
  3147. case '>=':
  3148. case '<':
  3149. case '<=':
  3150. if (!is_numeric($cell) && $cellStr === '') {
  3151. continue 3;
  3152. }
  3153. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  3154. $vv = (float)$fv;
  3155. if ($sym === '>' && !($cv > $vv)) {
  3156. continue 3;
  3157. }
  3158. if ($sym === '>=' && !($cv >= $vv)) {
  3159. continue 3;
  3160. }
  3161. if ($sym === '<' && !($cv < $vv)) {
  3162. continue 3;
  3163. }
  3164. if ($sym === '<=' && !($cv <= $vv)) {
  3165. continue 3;
  3166. }
  3167. break;
  3168. case 'RANGE':
  3169. case 'NOT RANGE':
  3170. case 'BETWEEN':
  3171. case 'NOT BETWEEN':
  3172. case 'BETWEEN TIME':
  3173. case 'NOT BETWEEN TIME':
  3174. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  3175. $rawR = str_replace(' - ', ',', $rawR);
  3176. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  3177. if (count($arr) < 2) {
  3178. break;
  3179. }
  3180. $lo = $arr[0];
  3181. $hi = $arr[1];
  3182. if ($lo === '' && $hi === '') {
  3183. break;
  3184. }
  3185. $isNot = (strpos($sym, 'NOT') !== false);
  3186. if ($lo === '') {
  3187. $in = ($cellStr !== '' && $cellStr <= $hi);
  3188. if ($isNot ? $in : !$in) {
  3189. continue 3;
  3190. }
  3191. break;
  3192. }
  3193. if ($hi === '') {
  3194. $in = ($cellStr !== '' && $cellStr >= $lo);
  3195. if ($isNot ? $in : !$in) {
  3196. continue 3;
  3197. }
  3198. break;
  3199. }
  3200. $in = ($cellStr >= $lo && $cellStr <= $hi);
  3201. if ($isNot ? $in : !$in) {
  3202. continue 3;
  3203. }
  3204. break;
  3205. case 'NULL':
  3206. case 'IS NULL':
  3207. if ($cell !== null && $cell !== '') {
  3208. continue 3;
  3209. }
  3210. break;
  3211. case 'NOT NULL':
  3212. case 'IS NOT NULL':
  3213. if ($cell === null || $cell === '') {
  3214. continue 3;
  3215. }
  3216. break;
  3217. default:
  3218. break;
  3219. }
  3220. }
  3221. $filtered[] = $r;
  3222. }
  3223. return $filtered;
  3224. }
  3225. /**
  3226. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  3227. */
  3228. public function snapshotToProcure()
  3229. {
  3230. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3231. $this->error(__('Invalid parameters'));
  3232. }
  3233. $row = json_decode($this->request->post('row_json', ''), true);
  3234. if (!is_array($row)) {
  3235. $this->error(__('Invalid parameters'));
  3236. }
  3237. try {
  3238. $ids = $this->extractScydgyRowId($row);
  3239. if (!$this->isValidScydgyRowId($ids)) {
  3240. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3241. }
  3242. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3243. $data = [
  3244. 'scydgy_id' => $ids,
  3245. 'CCYDH' => $row['CCYDH'] ?? null,
  3246. 'CYJMC' => $row['CYJMC'] ?? null,
  3247. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3248. 'CDXMC' => $row['CDXMC'] ?? null,
  3249. 'CGYBH' => $row['CGYBH'] ?? null,
  3250. 'CGYMC' => $row['CGYMC'] ?? null,
  3251. 'CDW' => $row['CDW'] ?? null,
  3252. 'NGZL' => $row['NGZL'] ?? null,
  3253. 'CDF' => $row['CDF'] ?? null,
  3254. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3255. 'MBZ' => $row['MBZ'] ?? null,
  3256. 'bwjg' => $row['bwjg'] ?? null,
  3257. 'iStatus' => $row['iStatus'] ?? null,
  3258. 'dStamp' => $row['dStamp'] ?? null,
  3259. 'dputrecord' => $row['dputrecord'] ?? null,
  3260. 'cywyxm' => $row['cywyxm'] ?? null,
  3261. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3262. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3263. ];
  3264. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3265. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3266. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3267. $this->success('操作成功');
  3268. return;
  3269. }
  3270. if ($exists) {
  3271. $upd = $data;
  3272. unset($upd['scydgy_id'], $upd['status']);
  3273. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3274. } else {
  3275. // 新增:不写 status(空/走库默认);仅写创建时间
  3276. $data['createtime'] = date('Y-m-d H:i:s');
  3277. Db::table('purchase_order')->insert($data);
  3278. }
  3279. } catch (\Throwable $e) {
  3280. $this->error($e->getMessage());
  3281. }
  3282. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3283. $this->success('操作成功');
  3284. }
  3285. /**
  3286. * 未发列表
  3287. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3288. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3289. */
  3290. public function completeDirectly()
  3291. {
  3292. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3293. $this->error(__('参数错误'));
  3294. }
  3295. if (!$this->procuremenCanComplete()) {
  3296. $this->error(__('You have no permission'));
  3297. }
  3298. $row = json_decode($this->request->post('row_json', ''), true);
  3299. if (!is_array($row)) {
  3300. $this->error(__('Invalid parameters'));
  3301. }
  3302. $finishRaw = $this->request->post('finish', '1');
  3303. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3304. $poIdLog = null;
  3305. try {
  3306. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3307. $ids = $this->extractScydgyRowId($row);
  3308. if (!$this->isValidScydgyRowId($ids)) {
  3309. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3310. }
  3311. if ($asComplete) {
  3312. $this->assertPickRowCanComplete($ids, $row);
  3313. }
  3314. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3315. $data = [
  3316. 'scydgy_id' => $ids,
  3317. 'CCYDH' => $row['CCYDH'] ?? null,
  3318. 'CYJMC' => $row['CYJMC'] ?? null,
  3319. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3320. 'CDXMC' => $row['CDXMC'] ?? null,
  3321. 'CGYBH' => $row['CGYBH'] ?? null,
  3322. 'CGYMC' => $row['CGYMC'] ?? null,
  3323. 'CDW' => $row['CDW'] ?? null,
  3324. 'NGZL' => $row['NGZL'] ?? null,
  3325. 'CDF' => $row['CDF'] ?? null,
  3326. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3327. 'MBZ' => $row['MBZ'] ?? null,
  3328. 'bwjg' => $row['bwjg'] ?? null,
  3329. 'iStatus' => $row['iStatus'] ?? null,
  3330. 'dStamp' => $row['dStamp'] ?? null,
  3331. 'dputrecord' => $row['dputrecord'] ?? null,
  3332. 'cywyxm' => $row['cywyxm'] ?? null,
  3333. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3334. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3335. ];
  3336. if ($asComplete) {
  3337. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3338. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3339. }
  3340. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3341. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3342. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3343. $this->success('操作成功');
  3344. return;
  3345. }
  3346. if ($exists) {
  3347. $upd = $data;
  3348. unset($upd['scydgy_id']);
  3349. if (!$asComplete) {
  3350. unset($upd['status']);
  3351. }
  3352. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3353. } else {
  3354. // 新增:不写 status;完结时 $data 已含 status=1
  3355. $data['createtime'] = date('Y-m-d H:i:s');
  3356. Db::table('purchase_order')->insert($data);
  3357. }
  3358. } catch (\Throwable $e) {
  3359. $this->error($e->getMessage());
  3360. }
  3361. try {
  3362. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3363. if (is_array($rpo)) {
  3364. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3365. $poIdLog = $tid > 0 ? $tid : null;
  3366. }
  3367. } catch (\Throwable $e) {
  3368. $poIdLog = null;
  3369. }
  3370. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3371. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3372. if ($asComplete) {
  3373. $this->addOrderLog(
  3374. $ids,
  3375. 'mark_complete',
  3376. '点击「完结」,已标记为已完结',
  3377. $poIdLog
  3378. );
  3379. try {
  3380. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3381. if ($pdfPublicPath === '') {
  3382. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3383. }
  3384. } catch (\Throwable $e) {
  3385. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3386. }
  3387. } else {
  3388. $this->addOrderLog(
  3389. $ids,
  3390. 'save_qty_price',
  3391. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3392. $poIdLog
  3393. );
  3394. }
  3395. $this->pickHiddenScydgySetCache = null;
  3396. $this->success("操作成功");
  3397. }
  3398. /**
  3399. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3400. *
  3401. * @param array<int, array> $rows 引用传递当前页行
  3402. */
  3403. protected function mergePurchaseOrder(array &$rows)
  3404. {
  3405. if ($rows === []) {
  3406. return;
  3407. }
  3408. $ids = [];
  3409. foreach ($rows as $rw) {
  3410. if (!is_array($rw)) {
  3411. continue;
  3412. }
  3413. $id = (int)($rw['ID'] ?? 0);
  3414. if ($id > 0) {
  3415. $ids[$id] = true;
  3416. }
  3417. }
  3418. $idList = array_keys($ids);
  3419. if ($idList === []) {
  3420. return;
  3421. }
  3422. try {
  3423. $list = Db::table('purchase_order')
  3424. ->where('scydgy_id', 'in', $idList)
  3425. ->field('scydgy_id,This_quantity,ceilingPrice')
  3426. ->select();
  3427. } catch (\Throwable $e) {
  3428. return;
  3429. }
  3430. if (!is_array($list)) {
  3431. return;
  3432. }
  3433. $byId = [];
  3434. foreach ($list as $dbRow) {
  3435. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3436. continue;
  3437. }
  3438. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3439. }
  3440. foreach ($rows as &$rw) {
  3441. if (!is_array($rw)) {
  3442. continue;
  3443. }
  3444. $sid = (int)($rw['ID'] ?? 0);
  3445. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3446. continue;
  3447. }
  3448. $db = $byId[$sid];
  3449. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  3450. if (array_key_exists('This_quantity', $db)) {
  3451. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  3452. }
  3453. if (array_key_exists('ceilingPrice', $db)) {
  3454. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  3455. } elseif (array_key_exists('ceiling_price', $db)) {
  3456. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  3457. }
  3458. }
  3459. unset($rw);
  3460. }
  3461. /**
  3462. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3463. */
  3464. public function purchaseConfirmPick()
  3465. {
  3466. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3467. $this->error(__('Invalid parameters'));
  3468. }
  3469. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3470. $this->error(__('You have no permission'));
  3471. }
  3472. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3473. if ($batchRaw !== '') {
  3474. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3475. return;
  3476. }
  3477. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3478. $sid = (int)$scydgyId;
  3479. if (!$this->isValidScydgyRowId($sid)) {
  3480. $this->error('参数无效');
  3481. }
  3482. $parseIdList = function ($raw) {
  3483. if (is_array($raw)) {
  3484. $arr = $raw;
  3485. } else {
  3486. $decoded = json_decode((string)$raw, true);
  3487. $arr = is_array($decoded) ? $decoded : [];
  3488. }
  3489. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3490. };
  3491. $selectedRaw = $this->request->post('selected_ids', null);
  3492. if ($selectedRaw === null || $selectedRaw === '') {
  3493. $legacy = (int)$this->request->post('selected_id', 0);
  3494. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3495. } else {
  3496. $selectedIds = $parseIdList($selectedRaw);
  3497. }
  3498. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3499. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3500. try {
  3501. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3502. } catch (\InvalidArgumentException $e) {
  3503. $this->error($e->getMessage());
  3504. } catch (\Throwable $e) {
  3505. $this->error($e->getMessage());
  3506. }
  3507. $this->pickHiddenScydgySetCache = null;
  3508. $this->success('操作成功', '', $result);
  3509. }
  3510. /**
  3511. * 整单采购确认(多道工序一次提交)
  3512. */
  3513. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3514. {
  3515. $decoded = json_decode($batchRaw, true);
  3516. if (!is_array($decoded) || $decoded === []) {
  3517. $this->error('提交数据无效');
  3518. }
  3519. $picks = [];
  3520. foreach ($decoded as $item) {
  3521. if (!is_array($item)) {
  3522. continue;
  3523. }
  3524. $sid = (int)($item['scydgy_id'] ?? 0);
  3525. if (!$this->isValidScydgyRowId($sid)) {
  3526. continue;
  3527. }
  3528. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3529. if (!is_array($sel)) {
  3530. $sel = [(int)$sel];
  3531. }
  3532. $unsel = $item['unselected_ids'] ?? [];
  3533. if (!is_array($unsel)) {
  3534. $unsel = json_decode((string)$unsel, true);
  3535. $unsel = is_array($unsel) ? $unsel : [];
  3536. }
  3537. $picks[] = [
  3538. 'scydgy_id' => $sid,
  3539. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3540. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3541. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3542. ];
  3543. }
  3544. if ($picks === []) {
  3545. $this->error('提交数据无效');
  3546. }
  3547. Db::startTrans();
  3548. $results = [];
  3549. try {
  3550. foreach ($picks as $pick) {
  3551. $results[] = $this->runPurchaseConfirmPick(
  3552. (int)$pick['scydgy_id'],
  3553. $pick['selected_ids'],
  3554. $pick['unselected_ids'],
  3555. (int)$pick['purchase_order_id'],
  3556. false,
  3557. false
  3558. );
  3559. }
  3560. Db::commit();
  3561. } catch (\Throwable $e) {
  3562. Db::rollback();
  3563. $msg = $e->getMessage();
  3564. $this->error($msg !== '' ? $msg : '提交失败');
  3565. }
  3566. try {
  3567. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3568. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3569. } catch (\Throwable $e) {
  3570. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3571. }
  3572. $this->pickHiddenScydgySetCache = null;
  3573. $this->success('操作成功', '', ['batch' => $results]);
  3574. }
  3575. /**
  3576. * @return array<string, mixed>
  3577. */
  3578. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3579. {
  3580. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3581. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3582. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3583. $scydgyId = (string)$sid;
  3584. if ($selectedIds === []) {
  3585. throw new \InvalidArgumentException('请至少勾选一条明细');
  3586. }
  3587. $inter = array_intersect($selectedIds, $unselectedIds);
  3588. if ($inter !== []) {
  3589. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3590. }
  3591. $allIds = $this->purchaseOrderDetail($sid);
  3592. if ($allIds === []) {
  3593. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3594. }
  3595. foreach ($selectedIds as $id) {
  3596. if (!in_array($id, $allIds, true)) {
  3597. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3598. }
  3599. }
  3600. foreach ($unselectedIds as $id) {
  3601. if (!in_array($id, $allIds, true)) {
  3602. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3603. }
  3604. }
  3605. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3606. sort($union, SORT_NUMERIC);
  3607. $expect = $allIds;
  3608. sort($expect, SORT_NUMERIC);
  3609. if ($union !== $expect) {
  3610. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3611. }
  3612. if ($manageTransaction) {
  3613. Db::startTrans();
  3614. }
  3615. try {
  3616. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3617. $aff = 0;
  3618. try {
  3619. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3620. } catch (\Throwable $e) {
  3621. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3622. }
  3623. if ($aff < 1) {
  3624. throw new \Exception('更新选中状态失败');
  3625. }
  3626. $poPayload = [
  3627. 'status' => ProcuremenStatus::PO_COMPLETED,
  3628. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3629. ];
  3630. if ($purchaseOrderId > 0) {
  3631. $poAff = (int)Db::table('purchase_order')
  3632. ->where('id', $purchaseOrderId)
  3633. ->where('scydgy_id', $sid)
  3634. ->update($poPayload);
  3635. if ($poAff < 1) {
  3636. throw new \Exception('主表订单不存在或与工序行不匹配');
  3637. }
  3638. } else {
  3639. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3640. if ($poAff < 1) {
  3641. throw new \Exception('未找到');
  3642. }
  3643. }
  3644. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3645. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3646. if ($manageTransaction) {
  3647. Db::commit();
  3648. }
  3649. } catch (\Throwable $e) {
  3650. if ($manageTransaction) {
  3651. Db::rollback();
  3652. }
  3653. throw $e;
  3654. }
  3655. $poIdFinal = $purchaseOrderId;
  3656. if ($poIdFinal <= 0) {
  3657. try {
  3658. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3659. if (is_array($rpo)) {
  3660. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3661. }
  3662. } catch (\Throwable $e) {
  3663. $poIdFinal = 0;
  3664. }
  3665. }
  3666. $pickNames = [];
  3667. foreach ($selectedIds as $pid) {
  3668. $dr = $this->purchaseOrderDetai($sid, $pid);
  3669. $nm = trim((string)($dr['company_name'] ?? ''));
  3670. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3671. }
  3672. $this->addOrderLog(
  3673. $sid,
  3674. 'purchase_confirm',
  3675. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3676. $poIdFinal > 0 ? $poIdFinal : null
  3677. );
  3678. if ($sendNotifications) {
  3679. try {
  3680. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3681. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3682. 'scydgy_id' => $sid,
  3683. 'selected_ids' => $selectedIds,
  3684. 'unselected_ids' => $unselectedIds,
  3685. 'purchase_order_id' => $purchaseOrderId,
  3686. ]]);
  3687. } catch (\Throwable $e) {
  3688. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3689. }
  3690. }
  3691. Log::write(sprintf(
  3692. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3693. $scydgyId,
  3694. $purchaseOrderId,
  3695. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3696. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3697. ), 'notice');
  3698. $pdfPublicPath = '';
  3699. try {
  3700. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3701. } catch (\Throwable $e) {
  3702. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3703. }
  3704. return [
  3705. 'scydgy_id' => $scydgyId,
  3706. 'purchase_order_id' => $purchaseOrderId,
  3707. 'selected_ids' => $selectedIds,
  3708. 'unselected_ids' => $unselectedIds,
  3709. 'purchase_confirm_pdf' => $pdfPublicPath,
  3710. ];
  3711. }
  3712. /**
  3713. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3714. *
  3715. * @param int[]|string[] $scydgyIds
  3716. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3717. */
  3718. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3719. {
  3720. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3721. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3722. if ($scydgyIds === []) {
  3723. return $empty;
  3724. }
  3725. $pos = [];
  3726. try {
  3727. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3728. } catch (\Throwable $e) {
  3729. $rows = [];
  3730. }
  3731. if (is_array($rows)) {
  3732. foreach ($rows as $po) {
  3733. if (is_array($po)) {
  3734. $pos[] = $po;
  3735. }
  3736. }
  3737. }
  3738. if ($pos === []) {
  3739. return $empty;
  3740. }
  3741. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3742. return [
  3743. 'ccydh' => $ccydh,
  3744. 'pos' => $pos,
  3745. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3746. ];
  3747. }
  3748. /**
  3749. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3750. *
  3751. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3752. * @param array<int, array<string, mixed>> $picks
  3753. */
  3754. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3755. {
  3756. if ($picks === []) {
  3757. return;
  3758. }
  3759. $fallbackDetailId = 0;
  3760. $winners = [];
  3761. $losers = [];
  3762. foreach ($picks as $pick) {
  3763. if (!is_array($pick)) {
  3764. continue;
  3765. }
  3766. $sid = (int)($pick['scydgy_id'] ?? 0);
  3767. if (!$this->isValidScydgyRowId($sid)) {
  3768. continue;
  3769. }
  3770. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3771. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3772. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3773. $fallbackDetailId = (int)$selectedIds[0];
  3774. }
  3775. foreach ($selectedIds as $pid) {
  3776. $dr = $this->purchaseOrderDetai($sid, $pid);
  3777. if (!is_array($dr)) {
  3778. continue;
  3779. }
  3780. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3781. }
  3782. foreach ($unselectedIds as $pid) {
  3783. $dr = $this->purchaseOrderDetai($sid, $pid);
  3784. if (!is_array($dr)) {
  3785. continue;
  3786. }
  3787. $key = $this->notifySupplierDedupeKey($dr);
  3788. if (!isset($winners[$key])) {
  3789. $losers[$key] = $dr;
  3790. }
  3791. }
  3792. }
  3793. if ($winners === [] && $losers === []) {
  3794. return;
  3795. }
  3796. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3797. $sendSmsSafe = function ($phone, $content) {
  3798. $phone = trim((string)$phone);
  3799. if ($phone === '') {
  3800. return;
  3801. }
  3802. try {
  3803. $this->smsbao($phone, $content);
  3804. } catch (\Throwable $e) {
  3805. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3806. }
  3807. };
  3808. foreach ($winners as $dr) {
  3809. $cname = trim((string)($dr['company_name'] ?? ''));
  3810. $ph = trim((string)($dr['phone'] ?? ''));
  3811. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3812. 'company_name' => $cname,
  3813. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3814. 'phone' => $ph,
  3815. ]));
  3816. $sendSmsSafe($ph, $sms);
  3817. }
  3818. foreach ($losers as $dr) {
  3819. $cname = trim((string)($dr['company_name'] ?? ''));
  3820. $ph = trim((string)($dr['phone'] ?? ''));
  3821. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3822. 'company_name' => $cname,
  3823. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3824. 'phone' => $ph,
  3825. ]));
  3826. $sendSmsSafe($ph, $sms);
  3827. }
  3828. }
  3829. /**
  3830. * 短信去重键:优先手机号,否则公司名
  3831. */
  3832. protected function notifySupplierDedupeKey(array $detailRow): string
  3833. {
  3834. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  3835. if ($ph !== '') {
  3836. return 'p:' . $ph;
  3837. }
  3838. $cn = trim((string)($detailRow['company_name'] ?? ''));
  3839. return 'c:' . $cn;
  3840. }
  3841. /**
  3842. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3843. *
  3844. * @param int[] $detailIds
  3845. */
  3846. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3847. {
  3848. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3849. if ($detailIds === []) {
  3850. return;
  3851. }
  3852. $payload = ['status_name' => $statusName];
  3853. try {
  3854. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3855. } catch (\Throwable $e) {
  3856. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3857. }
  3858. }
  3859. /**
  3860. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3861. */
  3862. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3863. {
  3864. try {
  3865. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3866. } catch (\Throwable $e) {
  3867. return;
  3868. }
  3869. if (!is_array($rows)) {
  3870. return;
  3871. }
  3872. foreach ($rows as $dr) {
  3873. if (!is_array($dr)) {
  3874. continue;
  3875. }
  3876. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3877. if ($id <= 0) {
  3878. continue;
  3879. }
  3880. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3881. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3882. try {
  3883. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3884. } catch (\Throwable $e) {
  3885. }
  3886. }
  3887. }
  3888. /**
  3889. * @param array<string, mixed> $detailRow
  3890. */
  3891. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3892. {
  3893. $am = $detailRow['amount'] ?? null;
  3894. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3895. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3896. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3897. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3898. }
  3899. /**
  3900. * @return int[]
  3901. */
  3902. protected function purchaseOrderDetail(int $scydgyId): array
  3903. {
  3904. if (!$this->isValidScydgyRowId($scydgyId)) {
  3905. return [];
  3906. }
  3907. try {
  3908. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3909. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3910. $list = $listQuery->select();
  3911. } catch (\Throwable $e) {
  3912. return [];
  3913. }
  3914. if (!is_array($list)) {
  3915. return [];
  3916. }
  3917. $ids = [];
  3918. foreach ($list as $r) {
  3919. if (!is_array($r)) {
  3920. continue;
  3921. }
  3922. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3923. if ($pk > 0) {
  3924. $ids[] = $pk;
  3925. }
  3926. }
  3927. return array_values(array_unique($ids));
  3928. }
  3929. /**
  3930. * 获取当前登录用户信息 [id, 展示名]
  3931. */
  3932. protected function GetUseName(): array
  3933. {
  3934. $id = 0;
  3935. $name = '';
  3936. try {
  3937. if ($this->auth && $this->auth->isLogin()) {
  3938. $u = $this->auth->getUserInfo();
  3939. if (is_array($u)) {
  3940. $id = (int)($u['id'] ?? 0);
  3941. $name = trim((string)($u['nickname'] ?? ''));
  3942. if ($name === '') {
  3943. $name = trim((string)($u['username'] ?? ''));
  3944. }
  3945. }
  3946. }
  3947. } catch (\Throwable $e) {
  3948. }
  3949. if ($name === '') {
  3950. $name = '未知用户';
  3951. }
  3952. return [$id, $name];
  3953. }
  3954. /**
  3955. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3956. */
  3957. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3958. {
  3959. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3960. }
  3961. /**
  3962. * 按主键取一条
  3963. */
  3964. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3965. {
  3966. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3967. return [];
  3968. }
  3969. try {
  3970. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3971. if (is_array($one)) {
  3972. return $one;
  3973. }
  3974. } catch (\Throwable $e) {
  3975. }
  3976. try {
  3977. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3978. if (is_array($one)) {
  3979. return $one;
  3980. }
  3981. } catch (\Throwable $e) {
  3982. }
  3983. return [];
  3984. }
  3985. /**
  3986. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3987. */
  3988. protected function formatProcuremenDetailTime($v): string
  3989. {
  3990. if ($v === null || $v === '') {
  3991. return '';
  3992. }
  3993. if (is_numeric($v) && (int)$v > 946684800) {
  3994. return date('Y-m-d H:i:s', (int)$v);
  3995. }
  3996. return ProcuremenTime::formatDisplayDateTime($v);
  3997. }
  3998. /**
  3999. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  4000. */
  4001. protected function formatDeliveryYmd($v): string
  4002. {
  4003. if ($v === null || $v === '') {
  4004. return '';
  4005. }
  4006. $s = trim((string)$v);
  4007. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  4008. return '';
  4009. }
  4010. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  4011. return $m[1];
  4012. }
  4013. $ts = strtotime($s);
  4014. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  4015. }
  4016. /**
  4017. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  4018. */
  4019. protected function detailRowSupplierOperated(array $r): bool
  4020. {
  4021. $am = $r['amount'] ?? null;
  4022. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4023. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4024. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4025. return $okAmt || $okDel;
  4026. }
  4027. /**
  4028. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  4029. */
  4030. protected function resolveDetailSupplierOperTime(array $r): string
  4031. {
  4032. if (!$this->detailRowSupplierOperated($r)) {
  4033. return '';
  4034. }
  4035. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  4036. if ($t !== '') {
  4037. return $t;
  4038. }
  4039. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  4040. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  4041. continue;
  4042. }
  4043. $t = $this->formatProcuremenDetailTime($r[$col]);
  4044. if ($t !== '') {
  4045. return $t;
  4046. }
  4047. }
  4048. return '';
  4049. }
  4050. /**
  4051. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  4052. */
  4053. protected function detailRowSupplierAccepted(array $r): bool
  4054. {
  4055. $am = $r['amount'] ?? null;
  4056. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4057. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4058. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4059. return $okAmt && $okDel;
  4060. }
  4061. /**
  4062. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  4063. */
  4064. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  4065. {
  4066. if ($detailCount > 0) {
  4067. return true;
  4068. }
  4069. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  4070. return true;
  4071. }
  4072. $pickTime = trim((string)($main['pick_time'] ?? ''));
  4073. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  4074. return true;
  4075. }
  4076. return false;
  4077. }
  4078. /**
  4079. * 下发时间:优先 pick_time,其次首条下发明细时间
  4080. */
  4081. protected function resolveProcuremenIssueTime(array $main, array $details): string
  4082. {
  4083. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  4084. if ($issueTime !== '') {
  4085. return $issueTime;
  4086. }
  4087. foreach ($details as $dr) {
  4088. if (!is_array($dr)) {
  4089. continue;
  4090. }
  4091. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4092. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  4093. $issueTime = $t;
  4094. }
  4095. }
  4096. if ($issueTime !== '') {
  4097. return $issueTime;
  4098. }
  4099. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4100. }
  4101. /**
  4102. * 直接点「完结」时间:优先操作记录 mark_complete
  4103. */
  4104. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  4105. {
  4106. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  4107. }
  4108. /**
  4109. * 操作记录时间(取指定 action 最近一条)
  4110. *
  4111. * @param string|array<int, string> $actions
  4112. */
  4113. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  4114. {
  4115. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  4116. }
  4117. /**
  4118. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  4119. *
  4120. * @param array $main purchase_order 一行
  4121. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  4122. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  4123. */
  4124. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  4125. {
  4126. $issueCnt = count($details);
  4127. $acceptCnt = 0;
  4128. $pickedName = '';
  4129. $pickedTime = '';
  4130. foreach ($details as $dr) {
  4131. if (!is_array($dr)) {
  4132. continue;
  4133. }
  4134. if ($this->detailRowSupplierAccepted($dr)) {
  4135. $acceptCnt++;
  4136. }
  4137. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4138. if ($pickedName === '') {
  4139. $pickedName = trim((string)($dr['company_name'] ?? ''));
  4140. }
  4141. if ($pickedTime === '') {
  4142. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  4143. if ($pickedTime === '') {
  4144. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4145. }
  4146. }
  4147. }
  4148. }
  4149. $hasMain = $main !== [];
  4150. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  4151. if ($poTime === '') {
  4152. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  4153. }
  4154. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  4155. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  4156. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  4157. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  4158. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  4159. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  4160. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  4161. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  4162. $supplierTime = '';
  4163. if ($acceptCnt > 0) {
  4164. foreach ($details as $dr) {
  4165. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  4166. continue;
  4167. }
  4168. $t = $this->resolveDetailSupplierOperTime($dr);
  4169. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  4170. $supplierTime = $t;
  4171. }
  4172. }
  4173. }
  4174. $directComplete = ($mainCompleted && !$issued);
  4175. $doneTime = '';
  4176. if ($mainCompleted) {
  4177. if ($directComplete) {
  4178. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  4179. }
  4180. if ($doneTime === '') {
  4181. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4182. }
  4183. if ($doneTime === '') {
  4184. foreach ($details as $dr) {
  4185. if (!is_array($dr)) {
  4186. continue;
  4187. }
  4188. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  4189. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  4190. $doneTime = $t;
  4191. }
  4192. }
  4193. }
  4194. if ($doneTime === '') {
  4195. $doneTime = $poTime;
  4196. }
  4197. if ($confirmApproveTime !== '') {
  4198. $doneTime = $confirmApproveTime;
  4199. }
  4200. }
  4201. if ($directComplete) {
  4202. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  4203. $step1Done = $hasMain;
  4204. $step2Done = false;
  4205. $step3Done = false;
  4206. $step4Done = false;
  4207. $step5Done = false;
  4208. $step6Done = true;
  4209. } else {
  4210. $step1Done = $issued;
  4211. $step2Done = $issued;
  4212. $step3Done = $acceptCnt > 0;
  4213. $step4Done = $wflowPendingApproval;
  4214. if (!$step4Done) {
  4215. foreach ($details as $dr) {
  4216. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4217. $step4Done = true;
  4218. break;
  4219. }
  4220. }
  4221. }
  4222. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  4223. $step6Done = $mainCompleted;
  4224. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  4225. if ($mainCompleted && $issued) {
  4226. $step3Done = true;
  4227. $step4Done = true;
  4228. $step5Done = true;
  4229. if ($supplierTime === '') {
  4230. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4231. if ($fillT !== '') {
  4232. $supplierTime = $fillT;
  4233. }
  4234. }
  4235. if ($pickedTime === '') {
  4236. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4237. if ($fillT !== '') {
  4238. $pickedTime = $fillT;
  4239. }
  4240. }
  4241. if ($auditSelectTime === '') {
  4242. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4243. if ($fillT !== '') {
  4244. $auditSelectTime = $fillT;
  4245. }
  4246. }
  4247. if ($confirmApproveTime === '') {
  4248. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4249. if ($fillT !== '') {
  4250. $confirmApproveTime = $fillT;
  4251. }
  4252. }
  4253. }
  4254. }
  4255. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4256. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4257. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4258. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4259. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4260. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4261. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4262. $deadlineLines = [];
  4263. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  4264. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  4265. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  4266. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  4267. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  4268. }
  4269. }
  4270. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  4271. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  4272. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  4273. if ($deliveryDisp === '') {
  4274. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  4275. }
  4276. if ($deliveryDisp !== '') {
  4277. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  4278. }
  4279. }
  4280. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  4281. if ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') {
  4282. $deadlineLines[] = '操作时间:' . $issueOperTimeRaw;
  4283. }
  4284. $deadlineText = implode("\n", $deadlineLines);
  4285. $prefixOperTime = static function (string $t): string {
  4286. $t = trim($t);
  4287. if ($t === '' || $t === '—') {
  4288. return $t;
  4289. }
  4290. if (strpos($t, '操作时间') === 0) {
  4291. return $t;
  4292. }
  4293. return '操作时间:' . $t;
  4294. };
  4295. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  4296. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '';
  4297. $step6Time = $step6Done ? $doneTime : '';
  4298. $steps = [
  4299. [
  4300. 'title' => '未发',
  4301. 'subtitle' => '',
  4302. 'time' => $issued ? '—' : ($hasMain ? $prefixOperTime($poTime) : ''),
  4303. 'done' => $step1Done,
  4304. ],
  4305. [
  4306. 'title' => '下发',
  4307. 'subtitle' => $deadlineText,
  4308. 'time' => '',
  4309. 'done' => $step2Done,
  4310. ],
  4311. [
  4312. 'title' => '供应商接单',
  4313. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4314. 'time' => '',
  4315. 'done' => $step3Done,
  4316. ],
  4317. [
  4318. 'title' => '待确认',
  4319. 'subtitle' => $step4Done
  4320. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4321. : ($issued ? '待选供应商' : ''),
  4322. 'time' => $prefixOperTime($step4Time),
  4323. 'done' => $step4Done,
  4324. ],
  4325. [
  4326. 'title' => '待审批',
  4327. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4328. 'time' => $prefixOperTime($step5Time),
  4329. 'done' => $step5Done,
  4330. ],
  4331. [
  4332. 'title' => '已完结',
  4333. 'subtitle' => '',
  4334. 'time' => $prefixOperTime($step6Time),
  4335. 'done' => $step6Done,
  4336. ],
  4337. ];
  4338. $currentIdx = count($steps) - 1;
  4339. if (!$directComplete) {
  4340. foreach ($steps as $i => $s) {
  4341. if (!$s['done']) {
  4342. $currentIdx = $i;
  4343. break;
  4344. }
  4345. }
  4346. }
  4347. $nSteps = count($steps);
  4348. foreach ($steps as $idx => &$s) {
  4349. $s['current'] = ($idx === $currentIdx);
  4350. if ($idx === 0) {
  4351. $s['pdf_left_bg'] = '';
  4352. } else {
  4353. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4354. }
  4355. if ($idx >= $nSteps - 1) {
  4356. $s['pdf_right_bg'] = '';
  4357. } else {
  4358. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4359. }
  4360. }
  4361. unset($s);
  4362. $labelMap = [
  4363. 'CCYDH' => '订单号',
  4364. 'CYJMC' => '印件名称',
  4365. 'CCLBMMC' => '承揽部门',
  4366. 'CGYMC' => '工序名称',
  4367. 'CDW' => '单位',
  4368. 'NGZL' => '工作量',
  4369. 'CDF' => '单价',
  4370. 'cGzzxMc' => '工作中心',
  4371. 'MBZ' => '备注',
  4372. 'This_quantity' => '本次数量',
  4373. 'ceilingPrice' => '最高限价',
  4374. ];
  4375. $orderSummary = [];
  4376. foreach ($labelMap as $key => $lab) {
  4377. if (!array_key_exists($key, $main)) {
  4378. continue;
  4379. }
  4380. $val = $main[$key];
  4381. if ($val === null) {
  4382. $val = '';
  4383. } elseif (!is_scalar($val)) {
  4384. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4385. } else {
  4386. $val = (string)$val;
  4387. }
  4388. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4389. }
  4390. $orderSummaryGrid = [];
  4391. $n = count($orderSummary);
  4392. for ($i = 0; $i < $n; $i += 2) {
  4393. $left = $orderSummary[$i];
  4394. $hasRight = ($i + 1) < $n;
  4395. $orderSummaryGrid[] = [
  4396. 'l1' => $left['label'],
  4397. 'v1' => $left['value'],
  4398. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4399. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4400. ];
  4401. }
  4402. return [
  4403. 'steps' => $steps,
  4404. 'orderSummary' => $orderSummary,
  4405. 'orderSummaryGrid' => $orderSummaryGrid,
  4406. 'detailRows' => $details,
  4407. ];
  4408. }
  4409. /**
  4410. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4411. *
  4412. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4413. */
  4414. protected function prepareProcuremenDetailsView(string $ids): array
  4415. {
  4416. $main = [];
  4417. try {
  4418. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4419. $main = is_array($one) ? $one : [];
  4420. } catch (\Throwable $e) {
  4421. $main = [];
  4422. }
  4423. $details = [];
  4424. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4425. if ($mergeRows === []) {
  4426. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4427. if ($mergeRows === [] && $main !== []) {
  4428. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4429. }
  4430. }
  4431. $detailSidList = [];
  4432. $anchorSid = (int)$ids;
  4433. if ($anchorSid !== 0) {
  4434. $detailSidList[$anchorSid] = true;
  4435. }
  4436. foreach ($mergeRows as $mr) {
  4437. if (!is_array($mr)) {
  4438. continue;
  4439. }
  4440. $sid = $this->extractScydgyRowId($mr);
  4441. if ($sid !== 0) {
  4442. $detailSidList[$sid] = true;
  4443. }
  4444. }
  4445. try {
  4446. if ($detailSidList !== []) {
  4447. $details = Db::table('purchase_order_detail')
  4448. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4449. ->order('id', 'asc')
  4450. ->select();
  4451. }
  4452. } catch (\Throwable $e) {
  4453. $details = [];
  4454. }
  4455. if (!is_array($details)) {
  4456. $details = [];
  4457. }
  4458. foreach ($details as &$r) {
  4459. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4460. $r['id'] = $r['ID'];
  4461. }
  4462. if (isset($r['createtime'])) {
  4463. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4464. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4465. } else {
  4466. $r['createtime_text'] = (string)$r['createtime'];
  4467. }
  4468. } else {
  4469. $r['createtime_text'] = '';
  4470. }
  4471. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4472. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4473. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4474. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4475. if (is_array($r)) {
  4476. $r = $this->maskSupplierContactFields($r);
  4477. }
  4478. }
  4479. unset($r);
  4480. $activeDetails = [];
  4481. foreach ($details as $r) {
  4482. if (is_array($r) && empty($r['is_void'])) {
  4483. $activeDetails[] = $r;
  4484. }
  4485. }
  4486. $operLogs = [];
  4487. try {
  4488. $operSidList = array_keys($detailSidList);
  4489. if ($operSidList === [] && (int)$ids !== 0) {
  4490. $operSidList = [(int)$ids];
  4491. }
  4492. if ($operSidList !== []) {
  4493. $operLogs = Db::table('purchase_order_oper_log')
  4494. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  4495. ->order('id', 'asc')
  4496. ->select();
  4497. }
  4498. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  4499. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  4500. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  4501. if ($poId > 0) {
  4502. $operLogs = Db::table('purchase_order_oper_log')
  4503. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  4504. ->order('id', 'asc')
  4505. ->select();
  4506. }
  4507. }
  4508. } catch (\Throwable $e) {
  4509. $operLogs = [];
  4510. }
  4511. if (!is_array($operLogs)) {
  4512. $operLogs = [];
  4513. }
  4514. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4515. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4516. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4517. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4518. if ($ccydh === '') {
  4519. foreach ($details as $r) {
  4520. if (!is_array($r)) {
  4521. continue;
  4522. }
  4523. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4524. if ($ccydh !== '') {
  4525. break;
  4526. }
  4527. }
  4528. }
  4529. $this->view->assign('ccydh', $ccydh);
  4530. $this->view->assign('steps', $bundle['steps']);
  4531. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4532. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4533. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4534. $this->view->assign('processCount', count($mergeRows));
  4535. $this->view->assign('detailRows', $details);
  4536. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4537. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4538. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4539. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4540. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  4541. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  4542. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  4543. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  4544. $this->view->assign('operLogs', $operLogs);
  4545. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaText());
  4546. return [
  4547. 'ok' => $main !== [] || $details !== [],
  4548. 'ccydh' => $ccydh,
  4549. ];
  4550. }
  4551. /**
  4552. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4553. */
  4554. public function details()
  4555. {
  4556. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4557. if (is_array($ids)) {
  4558. $ids = isset($ids[0]) ? $ids[0] : '';
  4559. }
  4560. $ids = trim((string)$ids);
  4561. if ($ids === '') {
  4562. $this->error(__('Invalid parameters'));
  4563. }
  4564. $this->assertManualOrderDetailsViewable((int)$ids);
  4565. $this->prepareProcuremenDetailsView($ids);
  4566. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4567. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4568. $this->view->engine->layout(false);
  4569. try {
  4570. return $this->view->fetch('procuremen/details_dialog_shell');
  4571. } finally {
  4572. if ($restoreLayout) {
  4573. $this->view->engine->layout($restoreLayout);
  4574. }
  4575. }
  4576. }
  4577. /**
  4578. * 解析合并审核工序行(订单号须一致,且均未协助)
  4579. *
  4580. * @return array<int, array<string, mixed>>
  4581. */
  4582. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4583. {
  4584. $primary = json_decode($rowJson, true);
  4585. if (!is_array($primary)) {
  4586. $this->error(__('Invalid parameters'));
  4587. }
  4588. $merge = json_decode($mergeRowsJson, true);
  4589. if (!is_array($merge) || $merge === []) {
  4590. $merge = [$primary];
  4591. }
  4592. $seen = [];
  4593. $out = [];
  4594. foreach ($merge as $r) {
  4595. if (!is_array($r)) {
  4596. continue;
  4597. }
  4598. $id = $this->extractScydgyRowId($r);
  4599. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4600. continue;
  4601. }
  4602. $seen[$id] = true;
  4603. $out[] = $r;
  4604. }
  4605. if ($out === []) {
  4606. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4607. }
  4608. $ccydh = null;
  4609. foreach ($out as $r) {
  4610. $dh = trim((string)($r['CCYDH'] ?? ''));
  4611. if ($ccydh === null) {
  4612. $ccydh = $dh;
  4613. } elseif ($dh !== $ccydh) {
  4614. $this->error('合并审核要求所选行的订单号一致');
  4615. }
  4616. }
  4617. $ids = [];
  4618. foreach ($out as $r) {
  4619. $id = $this->extractScydgyRowId($r);
  4620. if ($this->isValidScydgyRowId($id)) {
  4621. $ids[$id] = true;
  4622. }
  4623. }
  4624. $poBySid = [];
  4625. $detCntBySid = [];
  4626. if ($ids !== []) {
  4627. $idList = array_keys($ids);
  4628. try {
  4629. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4630. if (is_array($poList)) {
  4631. foreach ($poList as $po) {
  4632. if (!is_array($po)) {
  4633. continue;
  4634. }
  4635. $sid = (int)($po['scydgy_id'] ?? 0);
  4636. if ($this->isValidScydgyRowId($sid)) {
  4637. $poBySid[$sid] = $po;
  4638. }
  4639. }
  4640. }
  4641. } catch (\Throwable $e) {
  4642. }
  4643. try {
  4644. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4645. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4646. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4647. if (is_array($detRows)) {
  4648. foreach ($detRows as $dr) {
  4649. if (!is_array($dr)) {
  4650. continue;
  4651. }
  4652. $sid = (int)($dr['scydgy_id'] ?? 0);
  4653. if ($this->isValidScydgyRowId($sid)) {
  4654. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4655. }
  4656. }
  4657. }
  4658. } catch (\Throwable $e) {
  4659. }
  4660. }
  4661. foreach ($out as $r) {
  4662. $id = $this->extractScydgyRowId($r);
  4663. if (!$this->isValidScydgyRowId($id)) {
  4664. continue;
  4665. }
  4666. $po = $poBySid[$id] ?? null;
  4667. if (!is_array($po)) {
  4668. continue;
  4669. }
  4670. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4671. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4672. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4673. }
  4674. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4675. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4676. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4677. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4678. }
  4679. }
  4680. return $out;
  4681. }
  4682. /**
  4683. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4684. */
  4685. protected function maskSupplierContactFields(array $item): array
  4686. {
  4687. if (array_key_exists('email', $item)) {
  4688. $item['email'] = mask_email((string)$item['email']);
  4689. }
  4690. if (array_key_exists('phone', $item)) {
  4691. $item['phone'] = mask_phone((string)$item['phone']);
  4692. }
  4693. return $item;
  4694. }
  4695. /**
  4696. * @param array<int, array<string, mixed>> $list
  4697. * @return array<int, array<string, mixed>>
  4698. */
  4699. protected function maskSupplierContactList(array $list): array
  4700. {
  4701. $out = [];
  4702. foreach ($list as $item) {
  4703. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4704. }
  4705. return $out;
  4706. }
  4707. /**
  4708. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4709. *
  4710. * @return array<string, string>|null
  4711. */
  4712. protected function buildCustomerContactPayloadFromRow($row): ?array
  4713. {
  4714. if (!is_array($row)) {
  4715. return null;
  4716. }
  4717. $norm = [];
  4718. foreach ($row as $k => $v) {
  4719. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4720. }
  4721. $row = $norm;
  4722. $st = $row['status'] ?? '';
  4723. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4724. return null;
  4725. }
  4726. $companyName = '';
  4727. foreach (['company_name', 'name'] as $nk) {
  4728. if (!empty($row[$nk])) {
  4729. $companyName = trim((string)$row[$nk]);
  4730. break;
  4731. }
  4732. }
  4733. if ($companyName === '') {
  4734. return null;
  4735. }
  4736. $username = '';
  4737. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4738. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4739. $username = trim((string)$row[$uk]);
  4740. break;
  4741. }
  4742. }
  4743. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4744. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4745. if ($phone === '' && isset($row['account'])) {
  4746. $phone = trim((string)$row['account']);
  4747. }
  4748. if ($phone === '' && isset($row['mobile'])) {
  4749. $phone = trim((string)$row['mobile']);
  4750. }
  4751. if ($email === '' && $phone === '') {
  4752. return null;
  4753. }
  4754. $category = '';
  4755. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4756. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4757. $category = trim((string)$row[$ck]);
  4758. break;
  4759. }
  4760. }
  4761. return [
  4762. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4763. 'name' => $companyName,
  4764. 'company_name' => $companyName,
  4765. 'username' => $username,
  4766. 'email' => $email,
  4767. 'phone' => $phone,
  4768. 'category' => $category,
  4769. 'company_type' => $category,
  4770. ];
  4771. }
  4772. /**
  4773. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4774. */
  4775. protected function resolveCustomerContactById(string $id): ?array
  4776. {
  4777. $id = trim($id);
  4778. if ($id === '' || !ctype_digit($id)) {
  4779. return null;
  4780. }
  4781. try {
  4782. $row = Db::table('customer')->where('id', (int)$id)->find();
  4783. } catch (\Throwable $e) {
  4784. return null;
  4785. }
  4786. return $this->buildCustomerContactPayloadFromRow($row);
  4787. }
  4788. /**
  4789. * 按供应商名称解析联系信息(兼容旧提交数据)
  4790. */
  4791. protected function resolveCustomerContactByCompanyName(string $name): ?array
  4792. {
  4793. $name = trim($name);
  4794. if ($name === '') {
  4795. return null;
  4796. }
  4797. try {
  4798. $row = Db::table('customer')
  4799. ->where(function ($q) use ($name) {
  4800. $q->where('company_name', $name)->whereOr('name', $name);
  4801. })
  4802. ->order('id', 'desc')
  4803. ->find();
  4804. } catch (\Throwable $e) {
  4805. return null;
  4806. }
  4807. return $this->buildCustomerContactPayloadFromRow($row);
  4808. }
  4809. /**
  4810. * 规范化下发/确认时勾选的供应商
  4811. *
  4812. * @param array<int, mixed> $companies
  4813. * @return array<int, array<string, string>>
  4814. */
  4815. protected function normalizePickCompanies(array $companies): array
  4816. {
  4817. $out = [];
  4818. foreach ($companies as $c) {
  4819. if (!is_array($c)) {
  4820. continue;
  4821. }
  4822. $resolved = null;
  4823. $cid = trim((string)($c['id'] ?? ''));
  4824. if ($cid !== '') {
  4825. $resolved = $this->resolveCustomerContactById($cid);
  4826. }
  4827. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  4828. if ($resolved === null && $name !== '') {
  4829. $resolved = $this->resolveCustomerContactByCompanyName($name);
  4830. }
  4831. if ($resolved === null) {
  4832. continue;
  4833. }
  4834. $out[] = $resolved;
  4835. }
  4836. return $out;
  4837. }
  4838. /**
  4839. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  4840. *
  4841. * @param array<int, array<string, mixed>> $pool
  4842. * @return array<int, array<string, mixed>>
  4843. */
  4844. protected function collapseProcuremenPoolByOrder(array $pool): array
  4845. {
  4846. if ($pool === []) {
  4847. return [];
  4848. }
  4849. $groups = [];
  4850. foreach ($pool as $row) {
  4851. if (!is_array($row)) {
  4852. continue;
  4853. }
  4854. $dh = trim((string)($row['CCYDH'] ?? ''));
  4855. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  4856. if (!isset($groups[$key])) {
  4857. $groups[$key] = [];
  4858. }
  4859. $groups[$key][] = $row;
  4860. }
  4861. $out = [];
  4862. foreach ($groups as $ccydh => $rows) {
  4863. if ($rows === []) {
  4864. continue;
  4865. }
  4866. usort($rows, function ($a, $b) {
  4867. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  4868. });
  4869. $head = $rows[0];
  4870. $gymcList = [];
  4871. foreach ($rows as $r) {
  4872. $g = trim((string)($r['CGYMC'] ?? ''));
  4873. if ($g !== '' && !in_array($g, $gymcList, true)) {
  4874. $gymcList[] = $g;
  4875. }
  4876. }
  4877. $merged = $head;
  4878. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  4879. $merged['process_count'] = count($rows);
  4880. $merged['_order_merge_rows'] = $rows;
  4881. if (count($rows) > 1) {
  4882. $merged['CGYMC'] = implode('、', $gymcList);
  4883. }
  4884. $mergedPickTime = '';
  4885. foreach ($rows as $r) {
  4886. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  4887. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  4888. $mergedPickTime = $t;
  4889. }
  4890. }
  4891. if ($mergedPickTime !== '') {
  4892. $merged['pick_time'] = $mergedPickTime;
  4893. }
  4894. $out[] = $merged;
  4895. }
  4896. usort($out, function ($a, $b) {
  4897. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  4898. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  4899. if ($ta === $tb) {
  4900. $ida = (int)($a['purchase_order_id'] ?? 0);
  4901. $idb = (int)($b['purchase_order_id'] ?? 0);
  4902. if ($ida !== $idb) {
  4903. return $idb <=> $ida;
  4904. }
  4905. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  4906. }
  4907. if ($ta === '') {
  4908. return 1;
  4909. }
  4910. if ($tb === '') {
  4911. return -1;
  4912. }
  4913. return strcmp($tb, $ta);
  4914. });
  4915. return $out;
  4916. }
  4917. /**
  4918. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  4919. *
  4920. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4921. */
  4922. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  4923. {
  4924. $scydgyId = trim($scydgyId);
  4925. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4926. if ($scydgyId === '') {
  4927. return $empty;
  4928. }
  4929. try {
  4930. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4931. } catch (\Throwable $e) {
  4932. $anchor = null;
  4933. }
  4934. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  4935. return $empty;
  4936. }
  4937. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4938. if ($ccydh === '') {
  4939. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4940. }
  4941. try {
  4942. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4943. } catch (\Throwable $e) {
  4944. $pos = [$anchor];
  4945. }
  4946. if (!is_array($pos) || $pos === []) {
  4947. $pos = [$anchor];
  4948. }
  4949. return [
  4950. 'ccydh' => $ccydh,
  4951. 'pos' => $pos,
  4952. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4953. ];
  4954. }
  4955. /**
  4956. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4957. */
  4958. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4959. {
  4960. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4961. return false;
  4962. }
  4963. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4964. return false;
  4965. }
  4966. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4967. return true;
  4968. }
  4969. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4970. $sid = (int)($po['scydgy_id'] ?? 0);
  4971. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4972. }
  4973. return false;
  4974. }
  4975. /**
  4976. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4977. *
  4978. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4979. */
  4980. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4981. {
  4982. $scydgyId = trim($scydgyId);
  4983. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4984. if ($scydgyId === '') {
  4985. return $empty;
  4986. }
  4987. try {
  4988. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4989. } catch (\Throwable $e) {
  4990. $anchor = null;
  4991. }
  4992. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4993. return $empty;
  4994. }
  4995. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4996. if ($ccydh === '') {
  4997. return [
  4998. 'ccydh' => '',
  4999. 'pos' => [$anchor],
  5000. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  5001. ];
  5002. }
  5003. try {
  5004. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  5005. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  5006. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  5007. } catch (\Throwable $e) {
  5008. $pos = [$anchor];
  5009. }
  5010. if (!is_array($pos) || $pos === []) {
  5011. $pos = [$anchor];
  5012. }
  5013. $pos = array_values(array_filter($pos, function ($po) {
  5014. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  5015. }));
  5016. if ($pos === []) {
  5017. $pos = [$anchor];
  5018. }
  5019. return [
  5020. 'ccydh' => $ccydh,
  5021. 'pos' => $pos,
  5022. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5023. ];
  5024. }
  5025. /**
  5026. * @param array<int, array<string, mixed>> $purchaseOrders
  5027. * @return array<int, array<string, mixed>>
  5028. */
  5029. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  5030. {
  5031. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  5032. $byId = [];
  5033. foreach ($pool as $r) {
  5034. if (!is_array($r)) {
  5035. continue;
  5036. }
  5037. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  5038. if ($this->isValidScydgyRowId($sid)) {
  5039. $byId[$sid] = $r;
  5040. }
  5041. }
  5042. $out = [];
  5043. foreach ($purchaseOrders as $po) {
  5044. if (!is_array($po)) {
  5045. continue;
  5046. }
  5047. $sid = (int)($po['scydgy_id'] ?? 0);
  5048. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  5049. $out[] = $byId[$sid];
  5050. }
  5051. }
  5052. return $out;
  5053. }
  5054. /**
  5055. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  5056. *
  5057. * @return array<int, array<string, mixed>>
  5058. */
  5059. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  5060. {
  5061. $scydgyId = trim($scydgyId);
  5062. if ($scydgyId === '') {
  5063. return [];
  5064. }
  5065. try {
  5066. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5067. } catch (\Throwable $e) {
  5068. $anchor = null;
  5069. }
  5070. if (!is_array($anchor)) {
  5071. return [];
  5072. }
  5073. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  5074. return [];
  5075. }
  5076. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5077. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  5078. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  5079. try {
  5080. $q = Db::table('purchase_order');
  5081. if ($ccydh !== '') {
  5082. $q->where('CCYDH', $ccydh);
  5083. } else {
  5084. $q->where('scydgy_id', $scydgyId);
  5085. }
  5086. if ($isValidPick) {
  5087. $q->where('pick_time', $pickTime);
  5088. }
  5089. $pos = $q->order('scydgy_id', 'asc')->select();
  5090. } catch (\Throwable $e) {
  5091. $pos = [$anchor];
  5092. }
  5093. if (!is_array($pos) || $pos === []) {
  5094. $pos = [$anchor];
  5095. }
  5096. $pos = array_values(array_filter($pos, function ($po) {
  5097. if (!is_array($po)) {
  5098. return false;
  5099. }
  5100. $mr = $po['mod_rq'] ?? null;
  5101. if ($mr === null || $mr === '') {
  5102. return true;
  5103. }
  5104. $mrs = trim((string)$mr);
  5105. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  5106. }));
  5107. if ($pos === []) {
  5108. $pos = [$anchor];
  5109. }
  5110. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  5111. if ($rows === []) {
  5112. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  5113. }
  5114. return $rows;
  5115. }
  5116. /**
  5117. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  5118. *
  5119. * @param array<int, array<string, mixed>> $mergeRows
  5120. * @return array<int, array<string, mixed>>
  5121. */
  5122. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  5123. {
  5124. $list = array_values($mergeRows);
  5125. $n = count($list);
  5126. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  5127. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  5128. $mergeSame = $n > 1 && $orderKey0 !== '';
  5129. if ($mergeSame) {
  5130. foreach ($list as $rr) {
  5131. if (!is_array($rr)) {
  5132. $mergeSame = false;
  5133. break;
  5134. }
  5135. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  5136. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  5137. $mergeSame = false;
  5138. break;
  5139. }
  5140. }
  5141. }
  5142. $out = [];
  5143. foreach ($list as $idx => $r) {
  5144. if (!is_array($r)) {
  5145. continue;
  5146. }
  5147. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  5148. if (is_scalar($qty)) {
  5149. $qty = trim((string)$qty);
  5150. } else {
  5151. $qty = '';
  5152. }
  5153. if ($qty === '') {
  5154. $gzl = $r['NGZL'] ?? '';
  5155. if (is_scalar($gzl)) {
  5156. $qty = trim((string)$gzl);
  5157. }
  5158. }
  5159. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  5160. $sid = $this->extractScydgyRowId($r);
  5161. $out[] = [
  5162. 'seq' => $idx + 1,
  5163. 'scydgy_id' => $sid,
  5164. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5165. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5166. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5167. 'CDW' => trim((string)($r['CDW'] ?? '')),
  5168. 'NGZL' => $r['NGZL'] ?? '',
  5169. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  5170. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  5171. 'CDF' => trim((string)($r['CDF'] ?? '')),
  5172. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  5173. 'show_order_cells' => !$mergeSame || $idx === 0,
  5174. 'order_rowspan' => $mergeSame ? $n : 1,
  5175. ];
  5176. }
  5177. return $out;
  5178. }
  5179. /**
  5180. * 解析金额/数量(去千分位等非数字字符)
  5181. */
  5182. protected function parseProcuremenMoneyNumber($value): ?float
  5183. {
  5184. if ($value === null || $value === '') {
  5185. return null;
  5186. }
  5187. if (is_numeric($value)) {
  5188. return (float)$value;
  5189. }
  5190. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  5191. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  5192. }
  5193. protected function formatProcuremenMoneyDisplay(?float $amount): string
  5194. {
  5195. if ($amount === null) {
  5196. return '';
  5197. }
  5198. return (string)(int)round($amount);
  5199. }
  5200. /**
  5201. * 列表/详情展示:工作量为 0 时显示空
  5202. */
  5203. protected function formatProcuremenWorkloadDisplay($value): string
  5204. {
  5205. if ($value === null || $value === '') {
  5206. return '';
  5207. }
  5208. $s = trim((string)$value);
  5209. if ($s === '') {
  5210. return '';
  5211. }
  5212. if (is_numeric($s) && (float)$s == 0) {
  5213. return '';
  5214. }
  5215. return $s;
  5216. }
  5217. /**
  5218. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  5219. */
  5220. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  5221. {
  5222. foreach ($details as $d) {
  5223. if (!is_array($d)) {
  5224. continue;
  5225. }
  5226. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  5227. $cn = trim((string)($d['company_name'] ?? ''));
  5228. if ($cn !== '') {
  5229. return $cn;
  5230. }
  5231. }
  5232. }
  5233. return trim((string)($main['pick_company_name'] ?? ''));
  5234. }
  5235. /**
  5236. * 详情报价小计:单价 × 本工序本次数量
  5237. */
  5238. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  5239. {
  5240. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  5241. if ($unit === null) {
  5242. return null;
  5243. }
  5244. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  5245. if ($qty === null || $qty <= 0) {
  5246. return null;
  5247. }
  5248. return $unit * $qty;
  5249. }
  5250. /**
  5251. * 详情页:工序小计 + 供应商分组报价与总计
  5252. *
  5253. * @param array<int, array<string, mixed>> $mergeRows
  5254. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  5255. * @return array{
  5256. * process_rows: array,
  5257. * supplier_groups: array,
  5258. * order_total_text: string,
  5259. * order_total_has: bool,
  5260. * selected_company: string
  5261. * }
  5262. */
  5263. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  5264. {
  5265. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5266. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  5267. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  5268. $qtyBySid = [];
  5269. $gymcBySid = [];
  5270. $orderedSids = [];
  5271. foreach ($mergeRows as $mr) {
  5272. if (!is_array($mr)) {
  5273. continue;
  5274. }
  5275. $sid = $this->extractScydgyRowId($mr);
  5276. if ($this->isValidScydgyRowId($sid)) {
  5277. $orderedSids[] = $sid;
  5278. }
  5279. $qty = trim((string)($mr['This_quantity'] ?? ''));
  5280. if ($qty === '') {
  5281. $qty = trim((string)($mr['NGZL'] ?? ''));
  5282. }
  5283. $qtyBySid[$sid] = $qty;
  5284. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  5285. }
  5286. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  5287. $detailByCompanySid = [];
  5288. foreach ($details as $d) {
  5289. if (!is_array($d)) {
  5290. continue;
  5291. }
  5292. $cn = trim((string)($d['company_name'] ?? ''));
  5293. $sid = (int)($d['scydgy_id'] ?? 0);
  5294. if ($cn === '' || $sid === 0) {
  5295. continue;
  5296. }
  5297. if (!isset($detailByCompanySid[$cn])) {
  5298. $detailByCompanySid[$cn] = [];
  5299. }
  5300. $detailByCompanySid[$cn][$sid] = $d;
  5301. }
  5302. $supplierGroups = [];
  5303. foreach ($detailByCompanySid as $cn => $bySid) {
  5304. $lines = [];
  5305. $groupTotal = 0.0;
  5306. $groupHas = false;
  5307. $groupVoid = true;
  5308. $usedSids = [];
  5309. $appendLine = function (int $sid, array $d) use (
  5310. &$lines,
  5311. &$groupTotal,
  5312. &$groupHas,
  5313. &$groupVoid,
  5314. $qtyBySid,
  5315. $gymcBySid,
  5316. $quoteVisible
  5317. ) {
  5318. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5319. if (!$isVoid) {
  5320. $groupVoid = false;
  5321. }
  5322. $qtyStr = $qtyBySid[$sid] ?? '';
  5323. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5324. $am = trim((string)($d['amount'] ?? ''));
  5325. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5326. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5327. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5328. $sub = null;
  5329. if (!$isVoid && $amountNum !== null) {
  5330. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5331. }
  5332. $ct = $this->resolveDetailSupplierOperTime($d);
  5333. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  5334. $leadFilled = ($leadDays !== null);
  5335. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  5336. $line = [
  5337. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5338. 'unit_price_text' => $amountFilled
  5339. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  5340. : '未填写',
  5341. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5342. 'delivery_ymd' => $deliveryYmd,
  5343. 'amount_filled' => $amountFilled,
  5344. 'delivery_filled' => $deliveryFilled,
  5345. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5346. 'lead_days' => $leadFilled ? $leadDays : '',
  5347. 'lead_days_filled'=> $leadFilled,
  5348. 'lead_days_show' => $leadText,
  5349. 'lead_days_text' => $leadText,
  5350. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5351. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5352. 'is_void' => $isVoid,
  5353. 'oper_time_text' => $ct,
  5354. ];
  5355. if (!$quoteVisible && !$isVoid) {
  5356. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5357. } elseif ($sub !== null) {
  5358. $groupTotal += $sub;
  5359. $groupHas = true;
  5360. }
  5361. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5362. };
  5363. foreach ($orderedSids as $sid) {
  5364. if (!isset($bySid[$sid])) {
  5365. continue;
  5366. }
  5367. $usedSids[$sid] = true;
  5368. $appendLine($sid, $bySid[$sid]);
  5369. }
  5370. foreach ($bySid as $sid => $d) {
  5371. if (isset($usedSids[$sid])) {
  5372. continue;
  5373. }
  5374. $appendLine((int)$sid, $d);
  5375. }
  5376. $firstDetail = null;
  5377. foreach ($bySid as $d) {
  5378. if (is_array($d)) {
  5379. $firstDetail = $d;
  5380. break;
  5381. }
  5382. }
  5383. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5384. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5385. if ($username === '' && $ph !== '') {
  5386. $username = $this->resolveCustomerContactName($ph, $cn);
  5387. }
  5388. $remark = '';
  5389. foreach ($bySid as $d) {
  5390. if (!is_array($d)) {
  5391. continue;
  5392. }
  5393. $rm = '';
  5394. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  5395. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  5396. $rm = trim((string)$d[$rk]);
  5397. break;
  5398. }
  5399. }
  5400. if ($rm !== '') {
  5401. $remark = $rm;
  5402. break;
  5403. }
  5404. }
  5405. $lineCount = count($lines);
  5406. $hasRemark = $lineCount > 0;
  5407. $supplierGroup = [
  5408. 'company_name' => $cn,
  5409. 'username' => $username,
  5410. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5411. 'phone' => $ph,
  5412. 'remark' => $remark,
  5413. 'has_remark' => $hasRemark,
  5414. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5415. 'is_void' => $groupVoid,
  5416. 'lines' => $lines,
  5417. 'line_count' => $lineCount,
  5418. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  5419. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5420. 'has_total' => $lineCount > 0,
  5421. ];
  5422. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  5423. $supplierGroups[] = $supplierGroup;
  5424. }
  5425. usort($supplierGroups, function ($a, $b) {
  5426. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5427. return ($a['is_void'] ?? false) ? 1 : -1;
  5428. }
  5429. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5430. return ($a['is_selected'] ?? false) ? -1 : 1;
  5431. }
  5432. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5433. });
  5434. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  5435. return [
  5436. 'process_rows' => $processRows,
  5437. 'supplier_groups' => $supplierGroups,
  5438. 'order_total_text' => '',
  5439. 'order_total_has' => false,
  5440. 'selected_company' => $selectedCompany,
  5441. ];
  5442. }
  5443. /**
  5444. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5445. */
  5446. protected function buildProcessLinesPlain(array $mergeRows): string
  5447. {
  5448. $lines = [];
  5449. $i = 1;
  5450. foreach ($mergeRows as $r) {
  5451. if (!is_array($r)) {
  5452. continue;
  5453. }
  5454. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5455. $dw = trim((string)($r['CDW'] ?? ''));
  5456. $gzl = trim((string)($r['NGZL'] ?? ''));
  5457. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5458. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5459. if ($dw !== '') {
  5460. $parts[] = '单位:' . $dw;
  5461. }
  5462. if ($gzl !== '') {
  5463. $parts[] = '工作量:' . $gzl;
  5464. }
  5465. if ($qty !== '') {
  5466. $parts[] = '本次数量:' . $qty;
  5467. }
  5468. $lines[] = implode(' ', $parts);
  5469. $i++;
  5470. }
  5471. return implode("\n", $lines);
  5472. }
  5473. /**
  5474. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5475. *
  5476. * @return array<string, string>
  5477. */
  5478. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5479. {
  5480. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5481. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5482. }
  5483. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5484. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5485. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5486. $cyjmc = '';
  5487. foreach ($mergeRows as $mr) {
  5488. if (!is_array($mr)) {
  5489. continue;
  5490. }
  5491. if ($ccydh === '') {
  5492. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5493. }
  5494. if ($cyjmc === '') {
  5495. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5496. }
  5497. }
  5498. if ($pos !== []) {
  5499. $firstPo = $pos[0];
  5500. if (is_array($firstPo)) {
  5501. if ($ccydh === '') {
  5502. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5503. }
  5504. if ($cyjmc === '') {
  5505. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5506. }
  5507. }
  5508. }
  5509. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5510. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5511. if (is_array($any)) {
  5512. if ($ccydh === '') {
  5513. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5514. }
  5515. if ($cyjmc === '') {
  5516. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5517. }
  5518. }
  5519. }
  5520. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5521. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5522. $cgymc = '';
  5523. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5524. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5525. }
  5526. return [
  5527. 'ccydh' => $ccydh,
  5528. 'cyjmc' => $cyjmc,
  5529. 'cgymc' => $cgymc,
  5530. 'process_lines' => $processLines,
  5531. 'process_lines_html' => '',
  5532. ];
  5533. }
  5534. /**
  5535. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5536. */
  5537. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5538. {
  5539. $lines = [];
  5540. if ($ccydh !== '') {
  5541. $lines[] = '订单号:' . $ccydh;
  5542. }
  5543. if ($cyjmc !== '') {
  5544. $lines[] = '印件名称:' . $cyjmc;
  5545. }
  5546. if ($processPlain !== '') {
  5547. $lines[] = $processPlain;
  5548. }
  5549. return implode("\n", $lines);
  5550. }
  5551. /**
  5552. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5553. *
  5554. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5555. */
  5556. protected function buildPlatformLinksPlain(array $detailLinks): string
  5557. {
  5558. $lines = [];
  5559. $i = 1;
  5560. foreach ($detailLinks as $lk) {
  5561. if (!is_array($lk)) {
  5562. continue;
  5563. }
  5564. $url = trim((string)($lk['url'] ?? ''));
  5565. if ($url === '') {
  5566. continue;
  5567. }
  5568. $label = trim((string)($lk['cgymc'] ?? ''));
  5569. if ($label === '') {
  5570. $label = '工序' . $i;
  5571. }
  5572. $lines[] = $label . ':' . $url;
  5573. $i++;
  5574. }
  5575. return implode("\n", $lines);
  5576. }
  5577. /**
  5578. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5579. *
  5580. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5581. */
  5582. protected function buildPlatformLinksHtml(array $detailLinks): string
  5583. {
  5584. $parts = [];
  5585. $i = 1;
  5586. foreach ($detailLinks as $lk) {
  5587. if (!is_array($lk)) {
  5588. continue;
  5589. }
  5590. $url = trim((string)($lk['url'] ?? ''));
  5591. if ($url === '') {
  5592. continue;
  5593. }
  5594. $label = trim((string)($lk['cgymc'] ?? ''));
  5595. if ($label === '') {
  5596. $label = '工序' . $i;
  5597. }
  5598. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5599. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5600. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5601. $i++;
  5602. }
  5603. return implode("<br>\n", $parts);
  5604. }
  5605. /**
  5606. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5607. *
  5608. * @return array<string, mixed>
  5609. */
  5610. protected function loadMailerConfig(): array
  5611. {
  5612. try {
  5613. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5614. } catch (\Throwable $e) {
  5615. $cfg = [];
  5616. }
  5617. return is_array($cfg) ? $cfg : [];
  5618. }
  5619. protected function loadNotifyTemplateRow(string $scene): ?array
  5620. {
  5621. try {
  5622. $row = Db::table('purchase_sms_template')
  5623. ->where('scene', $scene)
  5624. ->where(function ($q) {
  5625. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5626. })
  5627. ->order('id', 'asc')
  5628. ->find();
  5629. } catch (\Throwable $e) {
  5630. return null;
  5631. }
  5632. if (!is_array($row) || $row === []) {
  5633. return null;
  5634. }
  5635. return [
  5636. 'title' => trim((string)($row['title'] ?? '')),
  5637. 'content' => trim((string)($row['content'] ?? '')),
  5638. ];
  5639. }
  5640. /**
  5641. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5642. */
  5643. protected function buildProcessLinesHtml(array $mergeRows): string
  5644. {
  5645. if (count($mergeRows) <= 1) {
  5646. $r = $mergeRows[0] ?? [];
  5647. if (!is_array($r)) {
  5648. return '';
  5649. }
  5650. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5651. $dw = trim((string)($r['CDW'] ?? ''));
  5652. $gzl = trim((string)($r['NGZL'] ?? ''));
  5653. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5654. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5655. if ($dw !== '') {
  5656. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5657. }
  5658. if ($gzl !== '') {
  5659. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5660. }
  5661. if ($qty !== '') {
  5662. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5663. }
  5664. return $html;
  5665. }
  5666. $rows = '';
  5667. $i = 1;
  5668. foreach ($mergeRows as $r) {
  5669. if (!is_array($r)) {
  5670. continue;
  5671. }
  5672. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5673. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5674. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5675. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5676. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5677. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5678. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5679. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5680. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5681. $i++;
  5682. }
  5683. if ($rows === '') {
  5684. return '';
  5685. }
  5686. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5687. . '<thead><tr style="background:#f5f5f5;">'
  5688. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5689. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5690. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5691. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5692. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5693. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5694. }
  5695. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  5696. {
  5697. $sysRq = trim($sysRq);
  5698. if ($sysRq === '') {
  5699. if ($required) {
  5700. $this->error('请选择招标截止日期');
  5701. }
  5702. return '';
  5703. }
  5704. $ts = strtotime($sysRq);
  5705. if ($ts === false || $ts <= 0) {
  5706. $this->error('招标截止日期格式无效');
  5707. }
  5708. $ymd = date('Y-m-d', $ts);
  5709. if ($ymd < date('Y-m-d')) {
  5710. $this->error('招标截止日期不能早于今天');
  5711. }
  5712. if ($ts <= time()) {
  5713. $this->error('招标截止时间不能早于当前时间');
  5714. }
  5715. return date('Y-m-d H:i:s', $ts);
  5716. }
  5717. /**
  5718. * 确保 purchase_order.delivery_deadline 存在
  5719. */
  5720. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  5721. {
  5722. static $done = false;
  5723. if ($done) {
  5724. return;
  5725. }
  5726. $done = true;
  5727. try {
  5728. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  5729. if (empty($cols)) {
  5730. Db::execute(
  5731. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  5732. );
  5733. }
  5734. } catch (\Throwable $e) {
  5735. // ignore
  5736. }
  5737. }
  5738. /**
  5739. * 解析交货截止日期(仅年月日)
  5740. */
  5741. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  5742. {
  5743. $raw = trim($raw);
  5744. if ($raw === '') {
  5745. if ($required) {
  5746. $this->error('请选择交货截止日期');
  5747. }
  5748. return '';
  5749. }
  5750. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  5751. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  5752. } else {
  5753. $ts = strtotime(str_replace('/', '-', $raw));
  5754. if ($ts === false || $ts <= 0) {
  5755. $this->error('交货截止日期格式无效');
  5756. }
  5757. $ymd = date('Y-m-d', $ts);
  5758. }
  5759. if ($ymd < date('Y-m-d')) {
  5760. $this->error('交货截止日期不能早于今天');
  5761. }
  5762. return $ymd;
  5763. }
  5764. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  5765. {
  5766. $s = trim((string)$value);
  5767. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  5768. return '';
  5769. }
  5770. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5771. return $m[1];
  5772. }
  5773. $ts = strtotime(str_replace('/', '-', $s));
  5774. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  5775. }
  5776. /**
  5777. * @param array{pos?:array} $bundle
  5778. */
  5779. protected function resolveBundleDeliveryDeadline(array $bundle): string
  5780. {
  5781. foreach ($bundle['pos'] ?? [] as $po) {
  5782. if (!is_array($po)) {
  5783. continue;
  5784. }
  5785. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  5786. if ($d !== '') {
  5787. return $d;
  5788. }
  5789. }
  5790. return '';
  5791. }
  5792. protected function formatProcuremenSysRqForInput($sysRq): string
  5793. {
  5794. $sr = trim((string)$sysRq);
  5795. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  5796. return '';
  5797. }
  5798. $ts = strtotime($sr);
  5799. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  5800. }
  5801. protected function formatProcuremenSysRqForDisplay($sysRq): string
  5802. {
  5803. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  5804. if ($sr === '') {
  5805. return '—';
  5806. }
  5807. $ts = strtotime($sr);
  5808. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  5809. }
  5810. /**
  5811. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  5812. *
  5813. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  5814. * @return array{ccydh?:string,pos:array,merge_rows:array}
  5815. */
  5816. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  5817. {
  5818. return $bundle;
  5819. }
  5820. /**
  5821. * 写入/更新 purchase_order(单道工序行)
  5822. */
  5823. protected function upsertPurchaseOrderFromRow(
  5824. array $row,
  5825. string $sysRqDb,
  5826. $wflowStatus = null,
  5827. ?string $pickTime = null,
  5828. ?array $exists = null,
  5829. ?string $deliveryDeadline = null
  5830. ): void {
  5831. $ids = $this->extractScydgyRowId($row);
  5832. if (!$this->isValidScydgyRowId($ids)) {
  5833. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  5834. }
  5835. if ($exists === null) {
  5836. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5837. }
  5838. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  5839. $data = [
  5840. 'scydgy_id' => $ids,
  5841. 'CCYDH' => $row['CCYDH'] ?? null,
  5842. 'CYJMC' => $row['CYJMC'] ?? null,
  5843. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5844. 'CDXMC' => $row['CDXMC'] ?? null,
  5845. 'CGYBH' => $row['CGYBH'] ?? null,
  5846. 'CGYMC' => $row['CGYMC'] ?? null,
  5847. 'CDW' => $row['CDW'] ?? null,
  5848. 'NGZL' => $row['NGZL'] ?? null,
  5849. 'CDF' => $row['CDF'] ?? null,
  5850. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5851. 'MBZ' => $row['MBZ'] ?? null,
  5852. 'bwjg' => $row['bwjg'] ?? null,
  5853. 'iStatus' => $row['iStatus'] ?? null,
  5854. 'dStamp' => $row['dStamp'] ?? null,
  5855. 'dputrecord' => $row['dputrecord'] ?? null,
  5856. 'cywyxm' => $row['cywyxm'] ?? null,
  5857. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5858. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5859. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5860. 'sys_rq' => $sysRqDb,
  5861. ];
  5862. if ($deliveryDeadline !== null) {
  5863. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  5864. }
  5865. if ($wflowStatus !== null && $wflowStatus !== '') {
  5866. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  5867. }
  5868. if ($pickTime !== null && $pickTime !== '') {
  5869. $data['pick_time'] = $pickTime;
  5870. $data['pick_company_name'] = '';
  5871. }
  5872. if ($exists) {
  5873. $upd = $data;
  5874. unset($upd['scydgy_id']);
  5875. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5876. } else {
  5877. $data['createtime'] = date('Y-m-d H:i:s');
  5878. Db::table('purchase_order')->insert($data);
  5879. }
  5880. }
  5881. /**
  5882. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  5883. *
  5884. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  5885. */
  5886. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  5887. {
  5888. $toDb = function ($value) {
  5889. if ($value === null) {
  5890. return null;
  5891. }
  5892. if (is_scalar($value)) {
  5893. return $value;
  5894. }
  5895. return json_encode($value, JSON_UNESCAPED_UNICODE);
  5896. };
  5897. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5898. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5899. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5900. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  5901. if ($username === '') {
  5902. $username = $this->resolveCustomerContactName($phone, $companyName);
  5903. }
  5904. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5905. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  5906. }
  5907. if ($phone === '') {
  5908. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  5909. }
  5910. $detailLinks = [];
  5911. foreach ($mergeRows as $row) {
  5912. if (!is_array($row)) {
  5913. continue;
  5914. }
  5915. $sid = $this->extractScydgyRowId($row);
  5916. $detailId = 0;
  5917. if ($skipExisting) {
  5918. try {
  5919. $existsQuery = Db::table('purchase_order_detail')
  5920. ->where('scydgy_id', $sid)
  5921. ->where('company_name', $companyName);
  5922. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  5923. $exists = $existsQuery->find();
  5924. } catch (\Throwable $e) {
  5925. $exists = null;
  5926. }
  5927. if (is_array($exists)) {
  5928. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  5929. }
  5930. }
  5931. if ($detailId <= 0) {
  5932. $one = [
  5933. 'scydgy_id' => $toDb($sid),
  5934. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  5935. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  5936. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  5937. 'username' => $username !== '' ? $username : null,
  5938. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  5939. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  5940. 'createtime' => date('Y-m-d H:i:s'),
  5941. 'status' => ProcuremenStatus::POD_UNPICKED,
  5942. 'status_name' => '未提交',
  5943. ];
  5944. Db::table('purchase_order_detail')->insert($one);
  5945. $detailId = (int)Db::getLastInsID();
  5946. }
  5947. $mprocUrl = '';
  5948. if ($buildMobileLinks && $detailId > 0) {
  5949. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  5950. }
  5951. $detailLinks[] = [
  5952. 'detail_id' => $detailId,
  5953. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  5954. 'url' => $mprocUrl,
  5955. ];
  5956. }
  5957. return $detailLinks;
  5958. }
  5959. /**
  5960. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  5961. * @return array<string, mixed>
  5962. */
  5963. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  5964. {
  5965. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5966. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5967. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5968. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  5969. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  5970. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  5971. $isMerge = !empty($ctx['is_merge']);
  5972. $contactName = trim((string)($c['username'] ?? ''));
  5973. if ($contactName === '') {
  5974. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  5975. }
  5976. $notifyVars = [
  5977. 'company_name' => $companyName,
  5978. 'contact_name' => $contactName,
  5979. 'phone' => $phone,
  5980. 'email' => $toEmail,
  5981. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  5982. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  5983. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  5984. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  5985. 'deadline' => (string)($ctx['deadline'] ?? ''),
  5986. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  5987. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  5988. 'platform_url' => $platformUrl,
  5989. 'platform_links' => $platformLinksPlain,
  5990. 'platform_links_html' => $platformLinksHtml,
  5991. ];
  5992. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  5993. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  5994. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5995. return [
  5996. 'company_name' => $companyName,
  5997. 'phone' => $phone,
  5998. 'email' => $toEmail,
  5999. 'sms_content' => $smsContent,
  6000. 'mail_plain' => $mailPlain,
  6001. 'mail_body' => $mailBody,
  6002. 'notify_vars' => $notifyVars,
  6003. 'detail_links' => $detailLinks,
  6004. ];
  6005. }
  6006. /**
  6007. * @param array<string, mixed> $chosen
  6008. * @param array<int, array<string, mixed>> $mergeRows
  6009. * @param array{ccydh:string, pos:array} $bundle
  6010. */
  6011. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  6012. {
  6013. if (!$sendSms && !$sendEmail) {
  6014. return;
  6015. }
  6016. $companyName = trim((string)($chosen['name'] ?? ''));
  6017. $phone = trim((string)($chosen['phone'] ?? ''));
  6018. $toEmail = trim((string)($chosen['email'] ?? ''));
  6019. if ($companyName === '') {
  6020. throw new \Exception('供应商名称无效');
  6021. }
  6022. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  6023. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  6024. }
  6025. if ($sendSms && $phone === '') {
  6026. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  6027. }
  6028. $sids = [];
  6029. foreach ($mergeRows as $mr) {
  6030. if (!is_array($mr)) {
  6031. continue;
  6032. }
  6033. $sid = $this->extractScydgyRowId($mr);
  6034. if ($this->isValidScydgyRowId($sid)) {
  6035. $sids[$sid] = true;
  6036. }
  6037. }
  6038. if ($sids === []) {
  6039. throw new \Exception('未找到工序行,无法发送通知');
  6040. }
  6041. $sysRqNotify = '';
  6042. $pos = $bundle['pos'] ?? [];
  6043. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6044. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  6045. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  6046. $ts = strtotime($sr);
  6047. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  6048. }
  6049. }
  6050. try {
  6051. $detailsQuery = Db::table('purchase_order_detail')
  6052. ->where('scydgy_id', 'in', array_keys($sids))
  6053. ->where('company_name', $companyName);
  6054. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6055. $details = $detailsQuery->order('id', 'asc')->select();
  6056. } catch (\Throwable $e) {
  6057. $details = [];
  6058. }
  6059. if (!is_array($details) || $details === []) {
  6060. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  6061. try {
  6062. $detailsQuery = Db::table('purchase_order_detail')
  6063. ->where('scydgy_id', 'in', array_keys($sids))
  6064. ->where('company_name', $companyName);
  6065. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6066. $details = $detailsQuery->order('id', 'asc')->select();
  6067. } catch (\Throwable $e) {
  6068. $details = [];
  6069. }
  6070. }
  6071. if (!is_array($details) || $details === []) {
  6072. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  6073. }
  6074. $detailLinks = [];
  6075. foreach ($details as $d) {
  6076. if (!is_array($d)) {
  6077. continue;
  6078. }
  6079. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  6080. if ($detailId <= 0) {
  6081. continue;
  6082. }
  6083. $sid = (int)($d['scydgy_id'] ?? 0);
  6084. $gymc = '';
  6085. foreach ($mergeRows as $mr) {
  6086. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  6087. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6088. break;
  6089. }
  6090. }
  6091. $detailLinks[] = [
  6092. 'detail_id' => $detailId,
  6093. 'cgymc' => $gymc,
  6094. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  6095. ];
  6096. }
  6097. if ($detailLinks === []) {
  6098. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  6099. }
  6100. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  6101. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  6102. $notifyBundle['email_log_scene'] = $emailLogScene;
  6103. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  6104. $poIdLog = 0;
  6105. $pos = $bundle['pos'] ?? [];
  6106. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6107. $poIdLog = (int)($pos[0]['id'] ?? 0);
  6108. }
  6109. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  6110. if ($sendEmail) {
  6111. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  6112. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  6113. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  6114. }
  6115. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  6116. $mailConfig = $this->loadMailerConfig();
  6117. if (!$this->isProcuremenNotifyDryRun()) {
  6118. if (empty($mailConfig['host'])) {
  6119. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  6120. }
  6121. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  6122. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  6123. }
  6124. }
  6125. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  6126. }
  6127. if ($sendSms) {
  6128. $this->issueSendSupplierSms($notifyBundle);
  6129. }
  6130. }
  6131. /**
  6132. * @param array<int, array<string, mixed>> $quoteGroups
  6133. * @return array<int, array<string, mixed>>
  6134. */
  6135. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  6136. {
  6137. $names = [];
  6138. if (is_string($companiesJson) && $companiesJson !== '') {
  6139. $decoded = json_decode($companiesJson, true);
  6140. if (is_array($decoded)) {
  6141. foreach ($decoded as $nm) {
  6142. $nm = trim((string)$nm);
  6143. if ($nm !== '') {
  6144. $names[] = $nm;
  6145. }
  6146. }
  6147. }
  6148. }
  6149. $names = array_values(array_unique($names));
  6150. if ($names === [] && $selectedCompany !== '') {
  6151. $names = [$selectedCompany];
  6152. }
  6153. if ($names === []) {
  6154. return $quoteGroups;
  6155. }
  6156. $targets = [];
  6157. foreach ($quoteGroups as $g) {
  6158. if (!is_array($g)) {
  6159. continue;
  6160. }
  6161. $cn = trim((string)($g['name'] ?? ''));
  6162. if ($cn !== '' && in_array($cn, $names, true)) {
  6163. $targets[] = $g;
  6164. }
  6165. }
  6166. return $targets;
  6167. }
  6168. /**
  6169. * @return array{pos:array, merge_rows:array, bundle:array}
  6170. */
  6171. protected function loadAuditResendBundle(string $scydgyId): array
  6172. {
  6173. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6174. $pos = $bundle['pos'];
  6175. $mergeRows = $bundle['merge_rows'];
  6176. if ($pos === [] || $mergeRows === []) {
  6177. $this->error('该订单不在待确认供应商状态');
  6178. }
  6179. $sysRqDb = '';
  6180. if (isset($pos[0]) && is_array($pos[0])) {
  6181. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  6182. }
  6183. foreach ($pos as $i => $poRow) {
  6184. if (is_array($pos[$i]) && $sysRqDb !== '') {
  6185. $pos[$i]['sys_rq'] = $sysRqDb;
  6186. }
  6187. }
  6188. $bundle['pos'] = $pos;
  6189. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  6190. }
  6191. /**
  6192. * @param array<int, array<string, mixed>> $targets
  6193. */
  6194. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  6195. {
  6196. if ($targets === []) {
  6197. $this->error('未找到可通知的供应商');
  6198. }
  6199. $notifyErrors = [];
  6200. try {
  6201. $this->notifyDryRunPreview = [];
  6202. foreach ($targets as $g) {
  6203. if (!is_array($g)) {
  6204. continue;
  6205. }
  6206. $cname = trim((string)($g['name'] ?? ''));
  6207. if ($cname === '') {
  6208. continue;
  6209. }
  6210. $chosen = [
  6211. 'name' => $cname,
  6212. 'company_name' => $cname,
  6213. 'email' => trim((string)($g['email'] ?? '')),
  6214. 'phone' => trim((string)($g['phone'] ?? '')),
  6215. 'username' => trim((string)($g['username'] ?? '')),
  6216. ];
  6217. try {
  6218. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  6219. } catch (\Throwable $e) {
  6220. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6221. }
  6222. }
  6223. } catch (\Throwable $e) {
  6224. $this->error('通知发送失败:' . $e->getMessage());
  6225. }
  6226. if ($notifyErrors !== []) {
  6227. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6228. }
  6229. if ($this->isProcuremenNotifyDryRun()) {
  6230. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  6231. 'notify_dry_run' => true,
  6232. 'notify_preview' => $this->notifyDryRunPreview,
  6233. ]);
  6234. }
  6235. $nameLabels = [];
  6236. foreach ($targets as $g) {
  6237. if (!is_array($g)) {
  6238. continue;
  6239. }
  6240. $n = trim((string)($g['name'] ?? ''));
  6241. if ($n !== '') {
  6242. $nameLabels[] = $n;
  6243. }
  6244. }
  6245. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  6246. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  6247. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  6248. $seenLogSid = [];
  6249. foreach ($bundle['pos'] ?? [] as $poRow) {
  6250. if (!is_array($poRow)) {
  6251. continue;
  6252. }
  6253. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6254. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  6255. continue;
  6256. }
  6257. $seenLogSid[$sid] = true;
  6258. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6259. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6260. }
  6261. if ($seenLogSid === []) {
  6262. foreach ($mergeRows as $mr) {
  6263. if (!is_array($mr)) {
  6264. continue;
  6265. }
  6266. $sid = $this->extractScydgyRowId($mr);
  6267. if ($this->isValidScydgyRowId($sid)) {
  6268. $this->addOrderLog($sid, $logAction, $logMsg, null);
  6269. break;
  6270. }
  6271. }
  6272. }
  6273. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  6274. }
  6275. /**
  6276. * 协助下发 — 发送短信(一家供应商)
  6277. *
  6278. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  6279. */
  6280. protected function issueSendSupplierSms(array $bundle): void
  6281. {
  6282. $companyName = (string)($bundle['company_name'] ?? '');
  6283. $phone = (string)($bundle['phone'] ?? '');
  6284. $smsContent = (string)($bundle['sms_content'] ?? '');
  6285. $this->logIssueNotifyDebug('短信', [
  6286. 'company' => $companyName,
  6287. 'phone' => $phone,
  6288. 'sms_content' => $smsContent,
  6289. ]);
  6290. if ($this->isProcuremenNotifyDryRun()) {
  6291. $this->recordNotifyDryRunPreview([
  6292. 'scene' => 'issue_sms',
  6293. 'company_name' => $companyName,
  6294. 'phone' => $phone,
  6295. 'sms_content' => $smsContent,
  6296. ]);
  6297. return;
  6298. }
  6299. $this->smsbao($phone, $smsContent);
  6300. }
  6301. /**
  6302. * 协助下发 — 发送邮件(一家供应商)
  6303. *
  6304. * @param array<string, mixed> $bundle
  6305. * @param array<string, mixed> $mailConfig
  6306. */
  6307. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  6308. {
  6309. $companyName = (string)($bundle['company_name'] ?? '');
  6310. $toEmail = (string)($bundle['email'] ?? '');
  6311. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  6312. $mailBody = (string)($bundle['mail_body'] ?? '');
  6313. $this->logIssueNotifyDebug('邮件', [
  6314. 'company' => $companyName,
  6315. 'email' => $toEmail,
  6316. 'mail_subject' => $mailSubject,
  6317. 'mail_body' => $mailPlain,
  6318. ]);
  6319. if ($this->isProcuremenNotifyDryRun()) {
  6320. $this->recordNotifyDryRunPreview([
  6321. 'scene' => 'issue_email',
  6322. 'company_name' => $companyName,
  6323. 'email' => $toEmail,
  6324. 'mail_subject' => $mailSubject,
  6325. 'mail_body' => $mailPlain,
  6326. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  6327. 'notify_vars' => $bundle['notify_vars'] ?? [],
  6328. 'detail_links' => $bundle['detail_links'] ?? [],
  6329. ]);
  6330. return;
  6331. }
  6332. $mail = new PHPMailer(true);
  6333. $mail->isSMTP();
  6334. $mail->Host = $mailConfig['host'];
  6335. $mail->SMTPAuth = true;
  6336. $mail->Username = $mailConfig['addr'];
  6337. $mail->Password = $mailConfig['pass'];
  6338. $mail->SMTPSecure = $mailConfig['security'];
  6339. $mail->Port = $mailConfig['port'];
  6340. $mail->CharSet = $mailConfig['charset'];
  6341. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  6342. $mail->addAddress($toEmail, $companyName);
  6343. $mail->isHTML(true);
  6344. $mail->Subject = $mailSubject;
  6345. $mail->Body = $mailBody;
  6346. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  6347. $sendOk = true;
  6348. $failReason = '';
  6349. try {
  6350. $mail->send();
  6351. } catch (\Throwable $e) {
  6352. $sendOk = false;
  6353. $failReason = $e->getMessage();
  6354. $this->persistEmailSendLog([
  6355. 'from_email' => $fromEmail,
  6356. 'to_email' => $toEmail,
  6357. 'send_time' => date('Y-m-d H:i:s'),
  6358. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6359. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6360. 'company_name' => $companyName,
  6361. 'mail_subject' => $mailSubject,
  6362. 'status' => 0,
  6363. 'fail_reason' => $failReason,
  6364. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6365. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6366. ]);
  6367. throw $e;
  6368. }
  6369. $this->persistEmailSendLog([
  6370. 'from_email' => $fromEmail,
  6371. 'to_email' => $toEmail,
  6372. 'send_time' => date('Y-m-d H:i:s'),
  6373. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6374. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6375. 'company_name' => $companyName,
  6376. 'mail_subject' => $mailSubject,
  6377. 'status' => 1,
  6378. 'fail_reason' => '',
  6379. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6380. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6381. ]);
  6382. }
  6383. /**
  6384. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  6385. *
  6386. * @param array<int, array<string, mixed>> $mergeRows
  6387. * @return array<string, mixed>
  6388. */
  6389. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  6390. {
  6391. $head = $mergeRows[0] ?? [];
  6392. $isMerge = count($mergeRows) > 1;
  6393. return [
  6394. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  6395. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  6396. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  6397. 'is_merge' => $isMerge,
  6398. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  6399. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  6400. 'deadline' => $sysRqNotify,
  6401. ];
  6402. }
  6403. /**
  6404. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  6405. *
  6406. * @param array<string, mixed> $data
  6407. */
  6408. protected function logIssueNotifyDebug(string $type, array $data): void
  6409. {
  6410. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  6411. return;
  6412. }
  6413. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6414. }
  6415. protected function ensurePurchaseEmailSendLogTableOnce(): void
  6416. {
  6417. try {
  6418. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  6419. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6420. return;
  6421. } catch (\Throwable $e) {
  6422. }
  6423. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  6424. if (is_file($sqlFile)) {
  6425. $sql = file_get_contents($sqlFile);
  6426. if (is_string($sql) && $sql !== '') {
  6427. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  6428. $stmt = trim($stmt);
  6429. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  6430. continue;
  6431. }
  6432. try {
  6433. Db::execute($stmt);
  6434. } catch (\Throwable $ignore) {
  6435. }
  6436. }
  6437. }
  6438. }
  6439. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6440. }
  6441. /**
  6442. * @param array<string, mixed> $row
  6443. */
  6444. protected function persistEmailSendLog(array $row): void
  6445. {
  6446. try {
  6447. $this->ensurePurchaseEmailSendLogTableOnce();
  6448. } catch (\Throwable $e) {
  6449. return;
  6450. }
  6451. list($adminId, $adminName) = $this->GetUseName();
  6452. $cut = function ($s, $max) {
  6453. $s = (string)$s;
  6454. if (function_exists('mb_substr')) {
  6455. return mb_substr($s, 0, $max, 'UTF-8');
  6456. }
  6457. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6458. };
  6459. $data = [
  6460. 'from_email' => $cut($row['from_email'] ?? '', 128),
  6461. 'to_email' => $cut($row['to_email'] ?? '', 128),
  6462. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  6463. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  6464. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  6465. 'company_name' => $cut($row['company_name'] ?? '', 128),
  6466. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6467. 'status' => !empty($row['status']) ? 1 : 0,
  6468. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6469. 'admin_id' => (int)$adminId,
  6470. 'admin_name' => $cut($adminName, 64),
  6471. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6472. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6473. 'createtime' => date('Y-m-d H:i:s'),
  6474. ];
  6475. try {
  6476. Db::table('purchase_email_send_log')->insert($data);
  6477. } catch (\Throwable $e) {
  6478. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6479. }
  6480. }
  6481. protected function formatEmailLogSceneText(string $scene): string
  6482. {
  6483. $map = [
  6484. 'pick_issue' => '初选下发',
  6485. 'audit_resend' => '确认页重发',
  6486. ];
  6487. return $map[$scene] ?? $scene;
  6488. }
  6489. /**
  6490. * 邮件发送日志列表
  6491. */
  6492. public function emailLog()
  6493. {
  6494. $this->relationSearch = false;
  6495. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6496. $this->request->filter(['strip_tags', 'trim']);
  6497. $bakModel = $this->model;
  6498. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6499. if ($this->request->isAjax()) {
  6500. $this->ensurePurchaseEmailSendLogTableOnce();
  6501. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6502. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6503. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6504. $list = $this->model
  6505. ->where($where)
  6506. ->order($sortField, $orderDir)
  6507. ->paginate($limit);
  6508. $rows = [];
  6509. foreach ($list->items() as $item) {
  6510. $row = is_array($item) ? $item : $item->toArray();
  6511. $scene = trim((string)($row['scene'] ?? ''));
  6512. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6513. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6514. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6515. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6516. $rows[] = $row;
  6517. }
  6518. $this->model = $bakModel;
  6519. return json(['total' => $list->total(), 'rows' => $rows]);
  6520. }
  6521. $this->model = $bakModel;
  6522. return $this->view->fetch('procuremen/emaillog');
  6523. }
  6524. /**
  6525. * 协助下发弹窗(选多家供应商并通知)
  6526. */
  6527. public function pickReview()
  6528. {
  6529. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6530. $this->error(__('You have no permission'));
  6531. }
  6532. if ($this->request->isPost()) {
  6533. $this->error('请使用弹窗内「确认下发」提交');
  6534. }
  6535. $this->view->assign('pickMode', 1);
  6536. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  6537. }
  6538. /**
  6539. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6540. */
  6541. public function add()
  6542. {
  6543. if ($this->request->isPost()) {
  6544. $params = $this->request->post('row/a');
  6545. if (!is_array($params)) {
  6546. $this->error(__('Parameter %s can not be empty', ''));
  6547. }
  6548. [, $adminName] = $this->GetUseName();
  6549. $params['cywyxm'] = $adminName;
  6550. try {
  6551. $sid = $this->saveManualPickOrder($params);
  6552. } catch (\InvalidArgumentException $e) {
  6553. $this->error($e->getMessage());
  6554. } catch (\Throwable $e) {
  6555. $this->error($e->getMessage());
  6556. }
  6557. $this->success('新增成功', '', [
  6558. 'scydgy_id' => $sid,
  6559. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  6560. ]);
  6561. }
  6562. [, $adminName] = $this->GetUseName();
  6563. $this->view->assign('adminNickname', $adminName);
  6564. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6565. $this->view->assign('defaultCclbmmc', '营销中心');
  6566. return $this->view->fetch();
  6567. }
  6568. /**
  6569. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6570. */
  6571. public function rfqlist()
  6572. {
  6573. $this->relationSearch = false;
  6574. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6575. $this->request->filter(['strip_tags', 'trim']);
  6576. if ($this->request->isAjax()) {
  6577. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6578. $limit = max(10, min(500, (int)$limit));
  6579. $applyFilters = function ($query) use ($where) {
  6580. $query->where('scydgy_id', '<', 0);
  6581. $query->whereRaw(
  6582. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6583. );
  6584. if (!$this->auth->isSuperAdmin()) {
  6585. [, $adminName] = $this->GetUseName();
  6586. $query->where('cywyxm', $adminName);
  6587. }
  6588. if (!empty($where)) {
  6589. $query->where($where);
  6590. }
  6591. };
  6592. $countQuery = Db::table('purchase_order');
  6593. $applyFilters($countQuery);
  6594. $total = (int)$countQuery->count();
  6595. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6596. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6597. $listQuery = Db::table('purchase_order');
  6598. $applyFilters($listQuery);
  6599. $rows = $listQuery
  6600. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6601. ->order($sortField, $orderDir)
  6602. ->limit($offset, $limit)
  6603. ->select();
  6604. if (!is_array($rows)) {
  6605. $rows = [];
  6606. }
  6607. $out = [];
  6608. foreach ($rows as $r) {
  6609. if (!is_array($r)) {
  6610. continue;
  6611. }
  6612. $sid = (int)($r['scydgy_id'] ?? 0);
  6613. if ($sid >= 0) {
  6614. continue;
  6615. }
  6616. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6617. if ($createdText === '') {
  6618. $createdText = trim((string)($r['dStamp'] ?? ''));
  6619. }
  6620. $out[] = [
  6621. 'id' => (int)($r['id'] ?? 0),
  6622. 'scydgy_id' => $sid,
  6623. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6624. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6625. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6626. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6627. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6628. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6629. 'createtime' => $r['createtime'] ?? null,
  6630. 'createtime_text' => $createdText,
  6631. ];
  6632. }
  6633. return json(['total' => $total, 'rows' => $out]);
  6634. }
  6635. [, $adminName] = $this->GetUseName();
  6636. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6637. $this->view->assign('adminNickname', $adminName);
  6638. return $this->view->fetch('procuremen/rfqlist');
  6639. }
  6640. /**
  6641. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6642. */
  6643. public function rfqlistDetails()
  6644. {
  6645. return $this->details();
  6646. }
  6647. /**
  6648. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6649. */
  6650. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6651. {
  6652. if ($scydgyId >= 0) {
  6653. return;
  6654. }
  6655. try {
  6656. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6657. } catch (\Throwable $e) {
  6658. $po = null;
  6659. }
  6660. if (!is_array($po)) {
  6661. $this->error('订单不存在');
  6662. }
  6663. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6664. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6665. $this->error('订单不存在');
  6666. }
  6667. if ($this->auth->isSuperAdmin()) {
  6668. return;
  6669. }
  6670. [, $adminName] = $this->GetUseName();
  6671. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6672. if ($cywy !== '' && $cywy === $adminName) {
  6673. return;
  6674. }
  6675. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6676. try {
  6677. if ($this->auth->check($rule)) {
  6678. return;
  6679. }
  6680. } catch (\Throwable $e) {
  6681. }
  6682. }
  6683. $this->error('无权查看该订单');
  6684. }
  6685. /**
  6686. * 手工新增协助工序进度文案
  6687. */
  6688. protected function formatProcuremenRfqProgressText(array $row): string
  6689. {
  6690. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6691. return ProcuremenStatus::PO_COMPLETED;
  6692. }
  6693. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6694. return '待采购确认';
  6695. }
  6696. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6697. return '待确认供应商';
  6698. }
  6699. $sid = (int)($row['scydgy_id'] ?? 0);
  6700. if ($sid < 0) {
  6701. try {
  6702. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6703. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6704. $detCnt = (int)$detCntQuery->count();
  6705. if ($detCnt > 0) {
  6706. return '已下发待确认';
  6707. }
  6708. } catch (\Throwable $e) {
  6709. }
  6710. }
  6711. return '待协助下发';
  6712. }
  6713. /**
  6714. * 协助初选列表 — 批量软删除
  6715. */
  6716. public function pickDelete()
  6717. {
  6718. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6719. $this->error(__('Invalid parameters'));
  6720. }
  6721. if (!$this->procuremenCanPickDelete()) {
  6722. $this->error(__('You have no permission'));
  6723. }
  6724. $rowsRaw = $this->request->post('rows_json', '[]');
  6725. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6726. if (!is_array($rows) || $rows === []) {
  6727. $this->error('请至少勾选一条工序');
  6728. }
  6729. $done = 0;
  6730. Db::startTrans();
  6731. try {
  6732. foreach ($rows as $row) {
  6733. if (!is_array($row)) {
  6734. continue;
  6735. }
  6736. $this->softDeleteProcuremenPickRow($row);
  6737. $done++;
  6738. }
  6739. if ($done < 1) {
  6740. throw new \Exception('没有可删除的工序');
  6741. }
  6742. Db::commit();
  6743. } catch (\InvalidArgumentException $e) {
  6744. Db::rollback();
  6745. $this->error($e->getMessage());
  6746. } catch (\Throwable $e) {
  6747. Db::rollback();
  6748. $this->error($e->getMessage());
  6749. }
  6750. $this->pickHiddenScydgySetCache = null;
  6751. $this->success('已删除 ' . $done . ' 条工序');
  6752. }
  6753. /**
  6754. * 下发 — 手工新增工序(弹窗)
  6755. */
  6756. public function pickAdd()
  6757. {
  6758. if ($this->request->isPost()) {
  6759. $params = $this->request->post('row/a');
  6760. if (!is_array($params)) {
  6761. $this->error(__('Parameter %s can not be empty', ''));
  6762. }
  6763. try {
  6764. $sid = $this->saveManualPickOrder($params);
  6765. } catch (\InvalidArgumentException $e) {
  6766. $this->error($e->getMessage());
  6767. } catch (\Throwable $e) {
  6768. $this->error($e->getMessage());
  6769. }
  6770. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6771. }
  6772. return $this->view->fetch('procuremen/pick_add');
  6773. }
  6774. /**
  6775. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  6776. */
  6777. public function pickSubmit()
  6778. {
  6779. if (!$this->request->isPost()) {
  6780. $this->error(__('Invalid parameters'));
  6781. }
  6782. // ---------- 接口订单数据 ----------
  6783. $rowJson = $this->request->post('row_json', '');
  6784. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  6785. $companiesJson = $this->request->post('companies_json', '[]');
  6786. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  6787. $companies = json_decode($companiesJson, true);
  6788. if (!is_array($companies)) {
  6789. $this->error('供应商数据无效');
  6790. }
  6791. $issueCompanies = $this->normalizePickCompanies($companies);
  6792. if ($issueCompanies === []) {
  6793. $this->error('请至少选择一家合作供应商');
  6794. }
  6795. $issueNameLabels = [];
  6796. foreach ($issueCompanies as $pc) {
  6797. $issueNameLabels[] = $pc['name'];
  6798. }
  6799. $issueNamesSummary = implode('、', $issueNameLabels);
  6800. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  6801. if ($sysRq === '') {
  6802. $this->error('请选择招标截止日期');
  6803. }
  6804. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  6805. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  6806. (string)$this->request->post('delivery_deadline', ''),
  6807. true
  6808. );
  6809. $isMerge = count($mergeRows) > 1;
  6810. $ccydhLog = '';
  6811. foreach ($mergeRows as $row) {
  6812. if (!is_array($row)) {
  6813. continue;
  6814. }
  6815. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  6816. if ($ccydhLog !== '') {
  6817. break;
  6818. }
  6819. }
  6820. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  6821. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6822. $logMsg = '下发' . $orderPart . $procPart
  6823. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  6824. $issueTime = date('Y-m-d H:i:s');
  6825. $logSidList = [];
  6826. foreach ($mergeRows as $row) {
  6827. if (!is_array($row)) {
  6828. continue;
  6829. }
  6830. $sid = $this->extractScydgyRowId($row);
  6831. if ($this->isValidScydgyRowId($sid)) {
  6832. $logSidList[$sid] = true;
  6833. }
  6834. }
  6835. $existingBySid = [];
  6836. if ($logSidList !== []) {
  6837. try {
  6838. $existingRows = Db::table('purchase_order')
  6839. ->where('scydgy_id', 'in', array_keys($logSidList))
  6840. ->select();
  6841. if (is_array($existingRows)) {
  6842. foreach ($existingRows as $poRow) {
  6843. if (!is_array($poRow)) {
  6844. continue;
  6845. }
  6846. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6847. if ($this->isValidScydgyRowId($sid)) {
  6848. $existingBySid[$sid] = $poRow;
  6849. }
  6850. }
  6851. }
  6852. } catch (\Throwable $e) {
  6853. $existingBySid = [];
  6854. }
  6855. }
  6856. Db::startTrans();
  6857. try {
  6858. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  6859. foreach ($mergeRows as $row) {
  6860. if (!is_array($row)) {
  6861. continue;
  6862. }
  6863. $sid = $this->extractScydgyRowId($row);
  6864. $this->upsertPurchaseOrderFromRow(
  6865. $row,
  6866. $sysRqDb,
  6867. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6868. $issueTime,
  6869. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  6870. $deliveryDeadlineDb
  6871. );
  6872. }
  6873. foreach ($issueCompanies as $c) {
  6874. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  6875. }
  6876. Db::commit();
  6877. } catch (\Throwable $e) {
  6878. Db::rollback();
  6879. $this->error($e->getMessage());
  6880. }
  6881. $poIdBySid = [];
  6882. if ($logSidList !== []) {
  6883. try {
  6884. $poIdBySid = Db::table('purchase_order')
  6885. ->where('scydgy_id', 'in', array_keys($logSidList))
  6886. ->column('id', 'scydgy_id');
  6887. } catch (\Throwable $e) {
  6888. $poIdBySid = [];
  6889. }
  6890. }
  6891. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  6892. if ($logSidList !== []) {
  6893. list($adminId, $adminName) = $this->GetUseName();
  6894. $logRows = [];
  6895. $seenLogSid = [];
  6896. foreach ($mergeRows as $row) {
  6897. if (!is_array($row)) {
  6898. continue;
  6899. }
  6900. $ids = $this->extractScydgyRowId($row);
  6901. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  6902. continue;
  6903. }
  6904. $seenLogSid[$ids] = true;
  6905. $poIdLog = null;
  6906. if (isset($poIdBySid[$ids])) {
  6907. $tid = (int)$poIdBySid[$ids];
  6908. $poIdLog = $tid > 0 ? $tid : null;
  6909. }
  6910. $logRows[] = ProcuremenOperLog::buildInsertRow(
  6911. $ids,
  6912. 'issue_submit',
  6913. $logMsg,
  6914. $poIdLog,
  6915. (int)$adminId,
  6916. (string)$adminName
  6917. );
  6918. }
  6919. if ($logRows !== []) {
  6920. try {
  6921. Db::table('purchase_order_oper_log')->insertAll($logRows);
  6922. } catch (\Throwable $e) {
  6923. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  6924. }
  6925. }
  6926. }
  6927. $notifyErrors = [];
  6928. $posNotify = [];
  6929. if ($logSidList !== []) {
  6930. try {
  6931. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  6932. } catch (\Throwable $e) {
  6933. $posNotify = [];
  6934. }
  6935. }
  6936. if (!is_array($posNotify)) {
  6937. $posNotify = [];
  6938. }
  6939. foreach ($posNotify as $i => $prow) {
  6940. if (is_array($posNotify[$i])) {
  6941. $posNotify[$i]['sys_rq'] = $sysRqDb;
  6942. }
  6943. }
  6944. $ccydhPick = '';
  6945. foreach ($mergeRows as $row) {
  6946. if (!is_array($row)) {
  6947. continue;
  6948. }
  6949. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  6950. if ($ccydhPick !== '') {
  6951. break;
  6952. }
  6953. }
  6954. $notifyBundleBase = [
  6955. 'ccydh' => $ccydhPick,
  6956. 'pos' => $posNotify,
  6957. 'merge_rows' => $mergeRows,
  6958. ];
  6959. try {
  6960. $this->notifyDryRunPreview = [];
  6961. foreach ($issueCompanies as $c) {
  6962. if (!is_array($c)) {
  6963. continue;
  6964. }
  6965. $cname = trim((string)($c['name'] ?? ''));
  6966. if ($cname === '') {
  6967. continue;
  6968. }
  6969. try {
  6970. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  6971. } catch (\Throwable $e) {
  6972. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6973. }
  6974. }
  6975. } catch (\Throwable $e) {
  6976. $this->error('通知发送失败:' . $e->getMessage());
  6977. }
  6978. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  6979. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6980. }
  6981. if ($this->isProcuremenNotifyDryRun()) {
  6982. $this->success('【演练模式】已保存并生成通知预览', '', [
  6983. 'notify_dry_run' => true,
  6984. 'notify_preview' => $this->notifyDryRunPreview,
  6985. ]);
  6986. }
  6987. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  6988. }
  6989. /**
  6990. * 确认供应商弹窗
  6991. */
  6992. public function auditIssue()
  6993. {
  6994. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6995. if (is_array($ids)) {
  6996. $ids = isset($ids[0]) ? $ids[0] : '';
  6997. }
  6998. $ids = trim((string)$ids);
  6999. if ($ids === '') {
  7000. $this->error(__('Invalid parameters'));
  7001. }
  7002. if ($this->request->isPost()) {
  7003. $this->error('请使用弹窗内「确认」提交');
  7004. }
  7005. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7006. $pos = $bundle['pos'];
  7007. if ($pos === []) {
  7008. $this->error('该订单不在待确认供应商状态');
  7009. }
  7010. $po = $pos[0];
  7011. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7012. if ($quoteGroups === []) {
  7013. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  7014. }
  7015. $pickedName = '';
  7016. foreach ($pos as $poRow) {
  7017. if (!is_array($poRow)) {
  7018. continue;
  7019. }
  7020. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7021. if ($pn !== '') {
  7022. $pickedName = $pn;
  7023. break;
  7024. }
  7025. }
  7026. $this->view->assign('po', $po);
  7027. $this->view->assign('scydgyId', $ids);
  7028. $this->view->assign('orderCcydh', $bundle['ccydh']);
  7029. $mergeRows = $bundle['merge_rows'];
  7030. $this->view->assign('processRows', $mergeRows);
  7031. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  7032. $this->view->assign('processCount', count($mergeRows));
  7033. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  7034. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  7035. $this->view->assign('pickedCompanyName', $pickedName);
  7036. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7037. if ($sysRqForView === '') {
  7038. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7039. }
  7040. $this->view->assign('sysRq', $sysRqForView);
  7041. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  7042. if ($deliveryDeadlineForView === '') {
  7043. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7044. }
  7045. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7046. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  7047. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaText());
  7048. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  7049. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  7050. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  7051. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  7052. return $this->view->fetch('procuremen/audit_issue');
  7053. }
  7054. /**
  7055. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  7056. *
  7057. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7058. */
  7059. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  7060. {
  7061. return !$this->isProcuremenBidOpenVerifiedForBundle($bundle);
  7062. }
  7063. /**
  7064. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  7065. *
  7066. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7067. */
  7068. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  7069. {
  7070. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7071. return false;
  7072. }
  7073. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  7074. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  7075. return true;
  7076. }
  7077. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  7078. }
  7079. /**
  7080. * 确认页 — 补加供应商弹窗
  7081. */
  7082. public function auditAppend()
  7083. {
  7084. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  7085. $this->error(__('You have no permission'));
  7086. }
  7087. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  7088. if (is_array($ids)) {
  7089. $ids = isset($ids[0]) ? $ids[0] : '';
  7090. }
  7091. $ids = trim((string)$ids);
  7092. if ($ids === '') {
  7093. $this->error(__('Invalid parameters'));
  7094. }
  7095. if ($this->request->isPost()) {
  7096. $this->error('请使用弹窗内「确认」提交');
  7097. }
  7098. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7099. if (($bundle['pos'] ?? []) === []) {
  7100. $this->error('该订单不在待确认供应商状态');
  7101. }
  7102. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7103. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7104. $this->error('已开标验证,不能再补加供应商');
  7105. }
  7106. $this->error('已经超过了招标截止日期,不可操作');
  7107. }
  7108. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7109. $existingNames = [];
  7110. foreach ($quoteGroups as $g) {
  7111. if (!is_array($g)) {
  7112. continue;
  7113. }
  7114. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  7115. if ($n !== '') {
  7116. $existingNames[$n] = true;
  7117. }
  7118. }
  7119. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  7120. $mergeRows = $bundle['merge_rows'] ?? [];
  7121. $this->view->assign('scydgyId', $ids);
  7122. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  7123. $this->view->assign('po', $po);
  7124. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  7125. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  7126. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  7127. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7128. if ($sysRqForView === '') {
  7129. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7130. }
  7131. $this->view->assign('sysRq', $sysRqForView);
  7132. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7133. if ($deliveryDeadlineForView === '') {
  7134. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7135. }
  7136. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7137. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  7138. }
  7139. /**
  7140. * 确认页 — 补加供应商提交
  7141. */
  7142. public function auditAppendSubmit()
  7143. {
  7144. if (!$this->request->isPost()) {
  7145. $this->error(__('Invalid parameters'));
  7146. }
  7147. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  7148. $this->error(__('You have no permission'));
  7149. }
  7150. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  7151. if ($ids === '') {
  7152. $this->error(__('Invalid parameters'));
  7153. }
  7154. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7155. if (($bundle['pos'] ?? []) === []) {
  7156. $this->error('该订单不在待确认供应商状态');
  7157. }
  7158. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7159. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7160. $this->error('已开标验证,不能再补加供应商');
  7161. }
  7162. $this->error('已经超过了招标截止日期,不可操作');
  7163. }
  7164. $companiesJson = $this->request->post('companies_json', '[]');
  7165. $companies = json_decode((string)$companiesJson, true);
  7166. if (!is_array($companies)) {
  7167. $this->error('供应商数据无效');
  7168. }
  7169. $issueCompanies = $this->normalizePickCompanies($companies);
  7170. if ($issueCompanies === []) {
  7171. $this->error('请至少选择一家合作供应商');
  7172. }
  7173. $mergeRows = $bundle['merge_rows'] ?? [];
  7174. if (!is_array($mergeRows) || $mergeRows === []) {
  7175. $this->error('未找到工序行,无法补加');
  7176. }
  7177. $existingNames = [];
  7178. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  7179. if (!is_array($g)) {
  7180. continue;
  7181. }
  7182. $n = trim((string)($g['company_name'] ?? ''));
  7183. if ($n !== '') {
  7184. $existingNames[$n] = true;
  7185. }
  7186. }
  7187. $toAdd = [];
  7188. foreach ($issueCompanies as $c) {
  7189. if (!is_array($c)) {
  7190. continue;
  7191. }
  7192. $n = trim((string)($c['name'] ?? ''));
  7193. if ($n === '' || isset($existingNames[$n])) {
  7194. continue;
  7195. }
  7196. $toAdd[] = $c;
  7197. }
  7198. if ($toAdd === []) {
  7199. $this->error('所选供应商均已在本单中,请选择新的供应商');
  7200. }
  7201. $addedNames = [];
  7202. Db::startTrans();
  7203. try {
  7204. foreach ($toAdd as $c) {
  7205. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  7206. $addedNames[] = trim((string)($c['name'] ?? ''));
  7207. }
  7208. Db::commit();
  7209. } catch (\Throwable $e) {
  7210. Db::rollback();
  7211. $this->error($e->getMessage());
  7212. }
  7213. $notifyErrors = [];
  7214. $notifyBundleBase = [
  7215. 'ccydh' => $bundle['ccydh'] ?? '',
  7216. 'pos' => $bundle['pos'] ?? [],
  7217. 'merge_rows' => $mergeRows,
  7218. ];
  7219. foreach ($toAdd as $c) {
  7220. if (!is_array($c)) {
  7221. continue;
  7222. }
  7223. $cname = trim((string)($c['name'] ?? ''));
  7224. if ($cname === '') {
  7225. continue;
  7226. }
  7227. try {
  7228. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  7229. } catch (\Throwable $e) {
  7230. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7231. }
  7232. }
  7233. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  7234. $seenLogSid = [];
  7235. foreach ($bundle['pos'] ?? [] as $poRow) {
  7236. if (!is_array($poRow)) {
  7237. continue;
  7238. }
  7239. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7240. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7241. continue;
  7242. }
  7243. $seenLogSid[$sid] = true;
  7244. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7245. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7246. }
  7247. if ($seenLogSid === []) {
  7248. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  7249. if ($this->isValidScydgyRowId($logSid)) {
  7250. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  7251. }
  7252. }
  7253. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  7254. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  7255. }
  7256. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  7257. }
  7258. /**
  7259. * 开标双重验证 — 可选验证人列表
  7260. */
  7261. public function bidOpenUsers()
  7262. {
  7263. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7264. $this->error('无权限');
  7265. }
  7266. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  7267. if ($scydgyId !== '') {
  7268. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7269. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7270. $this->success('已完成开标验证', null, [
  7271. 'verified' => 1,
  7272. 'users' => [],
  7273. ]);
  7274. }
  7275. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7276. }
  7277. $this->success('', null, [
  7278. 'verified' => 0,
  7279. 'users' => $this->listBidOpenVerifierCandidates(),
  7280. ]);
  7281. }
  7282. /**
  7283. * 开标双重验证 — 向指定管理员发送短信验证码
  7284. */
  7285. public function bidOpenSendCode()
  7286. {
  7287. if (!$this->request->isPost()) {
  7288. $this->error(__('Invalid parameters'));
  7289. }
  7290. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7291. $this->error('无权限');
  7292. }
  7293. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7294. $adminId = (int)$this->request->post('admin_id', 0);
  7295. if ($scydgyId === '' || $adminId <= 0) {
  7296. $this->error('参数无效');
  7297. }
  7298. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7299. if ($bundle['pos'] === []) {
  7300. $this->error('该订单不在待确认供应商状态');
  7301. }
  7302. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7303. $this->success('已完成开标验证,无需重复发送');
  7304. }
  7305. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7306. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7307. if ($ccydh === '') {
  7308. $this->error('订单号无效');
  7309. }
  7310. $admin = $this->loadBidOpenAdminUser($adminId);
  7311. if ($admin === null) {
  7312. $this->error('验证人无效或未绑定手机号');
  7313. }
  7314. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  7315. $cd = max(30, min(120, $cd));
  7316. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  7317. $this->error('发送过于频繁,请稍后再试');
  7318. }
  7319. $code = (string)random_int(100000, 999999);
  7320. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  7321. $ttl = max(60, min(600, $ttl));
  7322. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  7323. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  7324. try {
  7325. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  7326. } catch (\Throwable $e) {
  7327. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  7328. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  7329. $this->error($e->getMessage());
  7330. }
  7331. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  7332. }
  7333. /**
  7334. * 开标双重验证 — 两人验证码校验并记录
  7335. */
  7336. public function bidOpenVerify()
  7337. {
  7338. if (!$this->request->isPost()) {
  7339. $this->error(__('Invalid parameters'));
  7340. }
  7341. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7342. $this->error('无权限');
  7343. }
  7344. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7345. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  7346. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  7347. $code1 = trim((string)$this->request->post('code1', ''));
  7348. $code2 = trim((string)$this->request->post('code2', ''));
  7349. if ($scydgyId === '') {
  7350. $this->error('参数无效');
  7351. }
  7352. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  7353. $this->error('请选择两位验证人');
  7354. }
  7355. if ($verifier1Id === $verifier2Id) {
  7356. $this->error('两位验证人不能相同');
  7357. }
  7358. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  7359. $this->error('请输入6位短信验证码');
  7360. }
  7361. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7362. if ($bundle['pos'] === []) {
  7363. $this->error('该订单不在待确认供应商状态');
  7364. }
  7365. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7366. if ($ccydh === '') {
  7367. $this->error('订单号无效');
  7368. }
  7369. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7370. $this->success('已完成开标验证');
  7371. }
  7372. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7373. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  7374. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  7375. if ($verifier1 === null || $verifier2 === null) {
  7376. $this->error('验证人无效或未绑定手机号');
  7377. }
  7378. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  7379. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  7380. }
  7381. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  7382. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  7383. }
  7384. try {
  7385. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  7386. } catch (\Throwable $e) {
  7387. $this->error($e->getMessage());
  7388. }
  7389. $this->success('开标验证成功,可查看供应商报价与交货日期');
  7390. }
  7391. /**
  7392. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  7393. */
  7394. public function auditSubmit()
  7395. {
  7396. if (!$this->request->isPost()) {
  7397. $this->error(__('Invalid parameters'));
  7398. }
  7399. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7400. if ($scydgyId === '') {
  7401. $this->error('参数无效');
  7402. }
  7403. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7404. $pos = $bundle['pos'];
  7405. $mergeRows = $bundle['merge_rows'];
  7406. if ($pos === [] || $mergeRows === []) {
  7407. $this->error('该订单不在待确认供应商状态');
  7408. }
  7409. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7410. if ($quoteGroups === []) {
  7411. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  7412. }
  7413. $companyName = trim((string)$this->request->post('selected_company', ''));
  7414. if ($companyName === '') {
  7415. $this->error('请选择一家供应商');
  7416. }
  7417. $matched = null;
  7418. foreach ($quoteGroups as $g) {
  7419. if (!is_array($g)) {
  7420. continue;
  7421. }
  7422. if (trim((string)($g['name'] ?? '')) === $companyName) {
  7423. $matched = $g;
  7424. break;
  7425. }
  7426. }
  7427. if ($matched === null) {
  7428. $this->error('所选供应商不在本单报价列表中');
  7429. }
  7430. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7431. if ($sysRqDb === '') {
  7432. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  7433. } else {
  7434. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true);
  7435. }
  7436. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7437. $this->error('请先完成开标双重验证后再确认供应商');
  7438. }
  7439. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7440. $procCnt = count($mergeRows);
  7441. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  7442. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  7443. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  7444. Db::startTrans();
  7445. try {
  7446. foreach ($pos as $poRow) {
  7447. if (!is_array($poRow)) {
  7448. continue;
  7449. }
  7450. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7451. if (!$this->isValidScydgyRowId($sid)) {
  7452. continue;
  7453. }
  7454. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7455. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  7456. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7457. 'pick_company_name' => $companyName,
  7458. 'sys_rq' => $sysRqDb,
  7459. ]);
  7460. }
  7461. Db::commit();
  7462. } catch (\Throwable $e) {
  7463. Db::rollback();
  7464. $this->error($e->getMessage());
  7465. }
  7466. foreach ($pos as $poRow) {
  7467. if (!is_array($poRow)) {
  7468. continue;
  7469. }
  7470. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7471. if (!$this->isValidScydgyRowId($sid)) {
  7472. continue;
  7473. }
  7474. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7475. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7476. }
  7477. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  7478. }
  7479. /**
  7480. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  7481. */
  7482. public function auditResendSms()
  7483. {
  7484. if (!$this->request->isPost()) {
  7485. $this->error(__('Invalid parameters'));
  7486. }
  7487. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7488. if ($scydgyId === '') {
  7489. $this->error('参数无效');
  7490. }
  7491. $loaded = $this->loadAuditResendBundle($scydgyId);
  7492. $mergeRows = $loaded['merge_rows'];
  7493. $bundle = $loaded['bundle'];
  7494. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7495. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7496. if ($quoteGroups === []) {
  7497. $this->error('暂无可通知的供应商');
  7498. }
  7499. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7500. $companiesJson = (string)$this->request->post('companies_json', '');
  7501. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7502. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  7503. }
  7504. /**
  7505. * 确认供应商 — 二次发送邮件(可选单家/批量)
  7506. */
  7507. public function auditResendEmail()
  7508. {
  7509. if (!$this->request->isPost()) {
  7510. $this->error(__('Invalid parameters'));
  7511. }
  7512. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7513. if ($scydgyId === '') {
  7514. $this->error('参数无效');
  7515. }
  7516. $loaded = $this->loadAuditResendBundle($scydgyId);
  7517. $mergeRows = $loaded['merge_rows'];
  7518. $bundle = $loaded['bundle'];
  7519. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7520. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7521. if ($quoteGroups === []) {
  7522. $this->error('暂无可通知的供应商');
  7523. }
  7524. $companiesJson = (string)$this->request->post('companies_json', '');
  7525. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7526. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7527. if ($companiesJson === '' && $selectedCompany === '') {
  7528. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  7529. }
  7530. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  7531. }
  7532. /**
  7533. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  7534. *
  7535. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  7536. * @return array<int, true> 已处理的 scydgy_id 集合
  7537. */
  7538. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  7539. {
  7540. $pos = $bundle['pos'] ?? [];
  7541. if (!is_array($pos) || $pos === []) {
  7542. return [];
  7543. }
  7544. $sids = [];
  7545. foreach ($pos as $poRow) {
  7546. if (!is_array($poRow)) {
  7547. continue;
  7548. }
  7549. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7550. if ($this->isValidScydgyRowId($sid)) {
  7551. $sids[$sid] = true;
  7552. }
  7553. }
  7554. if ($sids === []) {
  7555. return [];
  7556. }
  7557. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7558. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  7559. $suffix = trim((string)$logSuffix, ',, ');
  7560. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  7561. $logMsg .= ':从历史存证退回协助初选';
  7562. } else {
  7563. $logMsg .= ':退回协助初选';
  7564. }
  7565. Db::table('purchase_order')
  7566. ->where('scydgy_id', 'in', array_keys($sids))
  7567. ->update([
  7568. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  7569. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7570. 'pick_company_name' => '',
  7571. 'pick_time' => null,
  7572. 'sys_rq' => null,
  7573. 'mod_rq' => null,
  7574. ]);
  7575. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  7576. foreach (array_keys($sids) as $sid) {
  7577. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  7578. }
  7579. return $sids;
  7580. }
  7581. /**
  7582. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  7583. *
  7584. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  7585. */
  7586. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  7587. {
  7588. $scydgyId = trim($scydgyId);
  7589. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7590. if ($scydgyId === '') {
  7591. return $empty;
  7592. }
  7593. try {
  7594. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7595. } catch (\Throwable $e) {
  7596. $anchor = null;
  7597. }
  7598. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  7599. return $empty;
  7600. }
  7601. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7602. if ($ccydh === '') {
  7603. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  7604. }
  7605. try {
  7606. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7607. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7608. $pos = $query->order('scydgy_id', 'asc')->select();
  7609. } catch (\Throwable $e) {
  7610. $pos = [$anchor];
  7611. }
  7612. if (!is_array($pos) || $pos === []) {
  7613. $pos = [$anchor];
  7614. }
  7615. return [
  7616. 'ccydh' => $ccydh,
  7617. 'pos' => $pos,
  7618. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7619. ];
  7620. }
  7621. protected function purchaseOrderRowIsCompleted(array $po): bool
  7622. {
  7623. $st = $po['status'] ?? null;
  7624. if ($st === 1 || $st === '1') {
  7625. return true;
  7626. }
  7627. if (is_string($st) && trim($st) === '1') {
  7628. return true;
  7629. }
  7630. return is_numeric($st) && (int)$st === 1;
  7631. }
  7632. /**
  7633. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  7634. */
  7635. public function auditAbandon()
  7636. {
  7637. if (!$this->request->isPost()) {
  7638. $this->error(__('Invalid parameters'));
  7639. }
  7640. $anchorIds = [];
  7641. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7642. if ($batchRaw !== '') {
  7643. $decoded = json_decode($batchRaw, true);
  7644. if (is_array($decoded)) {
  7645. foreach ($decoded as $id) {
  7646. $s = trim((string)$id);
  7647. if ($s !== '') {
  7648. $anchorIds[] = $s;
  7649. }
  7650. }
  7651. }
  7652. }
  7653. if ($anchorIds === []) {
  7654. $single = trim((string)$this->request->post('scydgy_id', ''));
  7655. if ($single !== '') {
  7656. $anchorIds[] = $single;
  7657. }
  7658. }
  7659. if ($anchorIds === []) {
  7660. $this->error('请至少选择一条订单');
  7661. }
  7662. $processedCcydh = [];
  7663. $doneOrders = 0;
  7664. $allSids = [];
  7665. Db::startTrans();
  7666. try {
  7667. foreach ($anchorIds as $anchorId) {
  7668. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  7669. if (($bundle['pos'] ?? []) === []) {
  7670. continue;
  7671. }
  7672. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7673. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7674. if (isset($processedCcydh[$dedupeKey])) {
  7675. continue;
  7676. }
  7677. $processedCcydh[$dedupeKey] = true;
  7678. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  7679. if ($sids === []) {
  7680. continue;
  7681. }
  7682. $doneOrders++;
  7683. foreach (array_keys($sids) as $sid) {
  7684. $allSids[(int)$sid] = true;
  7685. }
  7686. }
  7687. if ($doneOrders < 1) {
  7688. throw new \Exception('所选订单均不在待确认供应商状态');
  7689. }
  7690. Db::commit();
  7691. } catch (\Throwable $e) {
  7692. Db::rollback();
  7693. $this->error($e->getMessage());
  7694. }
  7695. $this->pickHiddenScydgySetCache = null;
  7696. $msg = $doneOrders > 1
  7697. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7698. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7699. $this->success($msg);
  7700. }
  7701. /**
  7702. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7703. */
  7704. public function archiveAbandon()
  7705. {
  7706. if (!$this->request->isPost()) {
  7707. $this->error(__('Invalid parameters'));
  7708. }
  7709. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7710. $this->error(__('You have no permission'));
  7711. }
  7712. $anchorIds = [];
  7713. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7714. if ($batchRaw !== '') {
  7715. $decoded = json_decode($batchRaw, true);
  7716. if (is_array($decoded)) {
  7717. foreach ($decoded as $id) {
  7718. $s = trim((string)$id);
  7719. if ($s !== '') {
  7720. $anchorIds[] = $s;
  7721. }
  7722. }
  7723. }
  7724. }
  7725. if ($anchorIds === []) {
  7726. $single = trim((string)$this->request->post('scydgy_id', ''));
  7727. if ($single !== '') {
  7728. $anchorIds[] = $single;
  7729. }
  7730. }
  7731. if ($anchorIds === []) {
  7732. $this->error('请至少选择一条订单');
  7733. }
  7734. $processedCcydh = [];
  7735. $doneOrders = 0;
  7736. Db::startTrans();
  7737. try {
  7738. foreach ($anchorIds as $anchorId) {
  7739. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7740. if (($bundle['pos'] ?? []) === []) {
  7741. continue;
  7742. }
  7743. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7744. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7745. if (isset($processedCcydh[$dedupeKey])) {
  7746. continue;
  7747. }
  7748. $processedCcydh[$dedupeKey] = true;
  7749. $sids = $this->abandonOrderBundleToPick(
  7750. $bundle,
  7751. 'archive_abandon',
  7752. ',从历史存证退回协助初选'
  7753. );
  7754. if ($sids === []) {
  7755. continue;
  7756. }
  7757. $doneOrders++;
  7758. }
  7759. if ($doneOrders < 1) {
  7760. throw new \Exception('所选订单均不是已完结状态');
  7761. }
  7762. Db::commit();
  7763. } catch (\Throwable $e) {
  7764. Db::rollback();
  7765. $this->error($e->getMessage());
  7766. }
  7767. $this->pickHiddenScydgySetCache = null;
  7768. $msg = $doneOrders > 1
  7769. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  7770. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7771. $this->success($msg);
  7772. }
  7773. /**
  7774. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  7775. */
  7776. public function purchaseApprovalReject()
  7777. {
  7778. if (!$this->request->isPost() || !$this->request->isAjax()) {
  7779. $this->error(__('Invalid parameters'));
  7780. }
  7781. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  7782. $this->error(__('You have no permission'));
  7783. }
  7784. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  7785. $decoded = json_decode($batchRaw, true);
  7786. if (!is_array($decoded) || $decoded === []) {
  7787. $this->error('提交数据无效');
  7788. }
  7789. $done = 0;
  7790. Db::startTrans();
  7791. try {
  7792. foreach ($decoded as $item) {
  7793. if (!is_array($item)) {
  7794. continue;
  7795. }
  7796. $sid = (int)($item['scydgy_id'] ?? 0);
  7797. if (!$this->isValidScydgyRowId($sid)) {
  7798. continue;
  7799. }
  7800. $this->runPurchaseApprovalRejectForSid($sid);
  7801. $done++;
  7802. }
  7803. if ($done < 1) {
  7804. throw new \Exception('所选订单均不在待审批状态');
  7805. }
  7806. Db::commit();
  7807. } catch (\Throwable $e) {
  7808. Db::rollback();
  7809. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  7810. }
  7811. $this->pickHiddenScydgySetCache = null;
  7812. $this->success('已驳回并退回「协助审批下发」');
  7813. }
  7814. /**
  7815. * @throws \Exception
  7816. */
  7817. protected function runPurchaseApprovalRejectForSid(int $sid): void
  7818. {
  7819. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  7820. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  7821. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  7822. $allIds = $this->purchaseOrderDetail($sid);
  7823. if ($allIds === []) {
  7824. throw new \Exception('未找到下发明细');
  7825. }
  7826. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7827. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7828. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7829. 'pick_company_name' => '',
  7830. ]);
  7831. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  7832. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  7833. $poId = 0;
  7834. try {
  7835. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  7836. if (is_array($po)) {
  7837. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7838. }
  7839. } catch (\Throwable $e) {
  7840. }
  7841. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  7842. }
  7843. /**
  7844. * 审核弹窗(旧入口,POST 已关闭)
  7845. */
  7846. public function review()
  7847. {
  7848. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  7849. $this->error(__('You have no permission'));
  7850. }
  7851. if ($this->request->isPost()) {
  7852. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  7853. }
  7854. $this->view->assign('pickMode', 0);
  7855. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  7856. }
  7857. /**
  7858. * 审核弹窗获取公司列表
  7859. */
  7860. public function reviewCompanies()
  7861. {
  7862. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  7863. $this->error(__('You have no permission'));
  7864. }
  7865. if (!$this->request->isAjax()) {
  7866. $this->error(__('Invalid parameters'));
  7867. }
  7868. $list = [];
  7869. try {
  7870. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  7871. $rows = Db::table('customer')
  7872. ->where(function ($q) {
  7873. $q->where('status', 1)
  7874. ->whereOr('status', '1')
  7875. ->whereOr('status', '')
  7876. ->whereNull('status');
  7877. })
  7878. ->order('id', 'desc')
  7879. ->select();
  7880. } catch (\Throwable $e) {
  7881. $this->success('', '', []);
  7882. return;
  7883. }
  7884. if (!is_array($rows)) {
  7885. $this->success('', '', []);
  7886. return;
  7887. }
  7888. $detailColCandidates = [
  7889. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  7890. 'company_detail', 'company_desc', 'address',
  7891. ];
  7892. foreach ($rows as $row) {
  7893. if (!is_array($row)) {
  7894. continue;
  7895. }
  7896. $norm = [];
  7897. foreach ($row as $k => $v) {
  7898. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7899. }
  7900. $row = $norm;
  7901. $st = $row['status'] ?? '';
  7902. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7903. continue;
  7904. }
  7905. $payload = $this->buildCustomerContactPayloadFromRow($row);
  7906. if ($payload === null) {
  7907. continue;
  7908. }
  7909. $detail = '';
  7910. foreach ($detailColCandidates as $dk) {
  7911. if (!isset($row[$dk])) {
  7912. continue;
  7913. }
  7914. $dv = trim((string)$row[$dk]);
  7915. if ($dv !== '') {
  7916. $detail = $dv;
  7917. break;
  7918. }
  7919. }
  7920. $payload['detail'] = $detail;
  7921. $list[] = $this->maskSupplierContactFields($payload);
  7922. }
  7923. $this->success('', '', $list);
  7924. }
  7925. /**
  7926. * 采购确认-下发明细弹窗:
  7927. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  7928. */
  7929. public function outward_detail()
  7930. {
  7931. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7932. if (is_array($ids)) {
  7933. $ids = isset($ids[0]) ? $ids[0] : '';
  7934. }
  7935. $ids = trim((string)$ids);
  7936. if ($ids === '') {
  7937. $this->error(__('Invalid parameters'));
  7938. }
  7939. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  7940. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  7941. $wffTab = 'all';
  7942. }
  7943. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  7944. $purchaseOrderId = 0;
  7945. $po = null;
  7946. try {
  7947. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7948. if (is_array($po)) {
  7949. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7950. }
  7951. } catch (\Throwable $e) {
  7952. $purchaseOrderId = 0;
  7953. $po = null;
  7954. }
  7955. if (!$isPurchaseConfirm && is_array($po)) {
  7956. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  7957. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  7958. $isPurchaseConfirm = true;
  7959. }
  7960. }
  7961. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  7962. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7963. $confirmProcessCount = 1;
  7964. $confirmPickGroups = [];
  7965. $processDisplayRows = [];
  7966. $allDetailsBySid = [];
  7967. $requiredSidList = [];
  7968. $sidList = [$ids];
  7969. if ($isPurchaseConfirm) {
  7970. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  7971. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  7972. if ($mergeRows !== []) {
  7973. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7974. }
  7975. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  7976. if ($confirmBundle['pos'] !== []) {
  7977. $sidList = [];
  7978. foreach ($confirmBundle['pos'] as $poRow) {
  7979. if (!is_array($poRow)) {
  7980. continue;
  7981. }
  7982. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7983. if (!$this->isValidScydgyRowId($sid)) {
  7984. continue;
  7985. }
  7986. $sidList[] = (string)$sid;
  7987. $requiredSidList[] = $sid;
  7988. }
  7989. }
  7990. if ($sidList === []) {
  7991. $sidList = [$ids];
  7992. $requiredSidList = [(int)$ids];
  7993. }
  7994. $confirmProcessCount = max(1, count($requiredSidList));
  7995. if (is_array($po) && $purchaseOrderId <= 0) {
  7996. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7997. }
  7998. }
  7999. $rows = [];
  8000. try {
  8001. if (count($sidList) === 1) {
  8002. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  8003. } else {
  8004. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  8005. }
  8006. } catch (\Throwable $e) {
  8007. $rows = [];
  8008. }
  8009. if ($isPurchaseConfirm) {
  8010. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  8011. }
  8012. foreach ($rows as &$r) {
  8013. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  8014. $r['id'] = $r['ID'];
  8015. }
  8016. if (isset($r['createtime'])) {
  8017. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  8018. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  8019. } else {
  8020. $r['createtime_text'] = (string)$r['createtime'];
  8021. }
  8022. } else {
  8023. $r['createtime_text'] = '';
  8024. }
  8025. if (is_array($r)) {
  8026. $r = $this->maskSupplierContactFields($r);
  8027. }
  8028. }
  8029. unset($r);
  8030. $pickedCompanyName = '';
  8031. if ($isPurchaseConfirm) {
  8032. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  8033. if (!is_array($poRow)) {
  8034. continue;
  8035. }
  8036. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  8037. if ($pn !== '') {
  8038. $pickedCompanyName = $pn;
  8039. break;
  8040. }
  8041. }
  8042. }
  8043. $this->view->assign('rows', $rows ?: []);
  8044. $this->view->assign('rowCount', count($rows ?: []));
  8045. $this->view->assign('scydgyId', $ids);
  8046. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  8047. $this->view->assign('headTitle', $headTitle);
  8048. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  8049. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  8050. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  8051. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  8052. $this->view->assign('processDisplayRows', $processDisplayRows);
  8053. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  8054. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  8055. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  8056. $this->view->assign('bidOpenVerified', ($isPurchaseConfirm && $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle)) ? 1 : 0);
  8057. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaText());
  8058. $sysRqDisplay = '—';
  8059. if ($isPurchaseConfirm) {
  8060. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  8061. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  8062. );
  8063. }
  8064. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  8065. $this->view->assign('sysRq', $isPurchaseConfirm
  8066. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  8067. : '');
  8068. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  8069. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  8070. : '');
  8071. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  8072. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  8073. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  8074. if ($isPurchaseConfirm) {
  8075. return $this->view->fetch();
  8076. }
  8077. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8078. $this->view->engine->layout(false);
  8079. try {
  8080. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  8081. $this->view->assign('dialogBody', $bodyHtml);
  8082. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  8083. } finally {
  8084. if ($restoreLayout) {
  8085. $this->view->engine->layout($restoreLayout);
  8086. }
  8087. }
  8088. }
  8089. /**
  8090. * 月度导出记录表(不存在时自动创建)
  8091. */
  8092. protected function ensurePurchaseMonthExportLogTable(): void
  8093. {
  8094. try {
  8095. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  8096. } catch (\Throwable $e) {
  8097. Db::execute(
  8098. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  8099. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  8100. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  8101. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  8102. `admin_name` varchar(64) NOT NULL DEFAULT '',
  8103. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  8104. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  8105. `createtime` int(10) unsigned DEFAULT NULL,
  8106. PRIMARY KEY (`id`),
  8107. KEY `idx_ym` (`ym`),
  8108. KEY `idx_ct` (`createtime`)
  8109. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  8110. );
  8111. }
  8112. }
  8113. /**
  8114. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  8115. *
  8116. * @param array<int, mixed> $dbRows
  8117. * @return array<int, array<string, mixed>>
  8118. */
  8119. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  8120. {
  8121. $keyword = trim((string)$this->request->get('search', ''));
  8122. if ($keyword === '') {
  8123. $keyword = trim((string)$this->request->request('search', ''));
  8124. }
  8125. $filter = $this->request->get('filter', '');
  8126. $op = $this->request->get('op', '');
  8127. if (is_string($filter) && $filter !== '') {
  8128. $filterArr = (array)json_decode($filter, true);
  8129. } else {
  8130. $filterArr = is_array($filter) ? $filter : [];
  8131. }
  8132. if (is_string($op) && $op !== '') {
  8133. $opArr = (array)json_decode($op, true);
  8134. } else {
  8135. $opArr = is_array($op) ? $op : [];
  8136. }
  8137. if ($keyword === '' && $filterArr === []) {
  8138. return array_values(array_filter($dbRows, 'is_array'));
  8139. }
  8140. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  8141. $out = [];
  8142. foreach ($dbRows as $row) {
  8143. if (!is_array($row)) {
  8144. continue;
  8145. }
  8146. if ($keyword !== '') {
  8147. $hit = false;
  8148. foreach ($searchFields as $f) {
  8149. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  8150. $hit = true;
  8151. break;
  8152. }
  8153. }
  8154. if (!$hit) {
  8155. continue;
  8156. }
  8157. }
  8158. $passFilter = true;
  8159. foreach ($filterArr as $field => $val) {
  8160. $field = (string)$field;
  8161. $val = trim((string)$val);
  8162. if ($field === '' || $val === '') {
  8163. continue;
  8164. }
  8165. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  8166. continue;
  8167. }
  8168. $cell = (string)($row[$field] ?? '');
  8169. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  8170. if ($mode === '=' || $mode === 'EQUAL') {
  8171. if (strcasecmp($cell, $val) !== 0) {
  8172. $passFilter = false;
  8173. break;
  8174. }
  8175. } elseif (mb_stripos($cell, $val) === false) {
  8176. $passFilter = false;
  8177. break;
  8178. }
  8179. }
  8180. if (!$passFilter) {
  8181. continue;
  8182. }
  8183. $out[] = $row;
  8184. }
  8185. return $out;
  8186. }
  8187. /**
  8188. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  8189. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  8190. */
  8191. public function export_month_outward()
  8192. {
  8193. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  8194. $this->error(__('You have no permission'));
  8195. }
  8196. $this->request->filter(['strip_tags', 'trim']);
  8197. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  8198. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8199. $ym = date('Y-m');
  8200. }
  8201. $dbRows = [];
  8202. try {
  8203. $query = Db::table('purchase_order');
  8204. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  8205. $dbRows = $query->select();
  8206. } catch (\Throwable $e) {
  8207. $dbRows = [];
  8208. }
  8209. if (!is_array($dbRows)) {
  8210. $dbRows = [];
  8211. }
  8212. $completeTsMap = [];
  8213. $sidList = [];
  8214. foreach ($dbRows as $dbRow) {
  8215. if (!is_array($dbRow)) {
  8216. continue;
  8217. }
  8218. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  8219. if ($sid > 0) {
  8220. $sidList[$sid] = true;
  8221. }
  8222. }
  8223. if ($sidList !== []) {
  8224. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  8225. }
  8226. $searchKw = trim((string)$this->request->get('search', ''));
  8227. if ($searchKw === '') {
  8228. $searchKw = trim((string)$this->request->request('search', ''));
  8229. }
  8230. $filterRaw = $this->request->get('filter', '');
  8231. $filterArrTmp = [];
  8232. if (is_string($filterRaw) && $filterRaw !== '') {
  8233. $filterArrTmp = (array)json_decode($filterRaw, true);
  8234. } elseif (is_array($filterRaw)) {
  8235. $filterArrTmp = $filterRaw;
  8236. }
  8237. $hasSearch = ($searchKw !== '');
  8238. if (!$hasSearch) {
  8239. foreach ($filterArrTmp as $fv) {
  8240. if (trim((string)$fv) !== '') {
  8241. $hasSearch = true;
  8242. break;
  8243. }
  8244. }
  8245. }
  8246. // 有搜索时跨月份导出(与列表一致);无搜索时仍按查看月份
  8247. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  8248. if (!is_array($dbRow)) {
  8249. return false;
  8250. }
  8251. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  8252. if ($done['ts'] <= 0) {
  8253. return false;
  8254. }
  8255. if ($hasSearch) {
  8256. return true;
  8257. }
  8258. return date('Y-m', $done['ts']) === $ym;
  8259. }));
  8260. // 与列表页一致:按搜索关键字 / 通用搜索过滤
  8261. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  8262. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  8263. $filtered = $pool;
  8264. $mainBySid = [];
  8265. foreach ($filtered as $rw) {
  8266. if (!is_array($rw)) {
  8267. continue;
  8268. }
  8269. $rid = (int)($rw['ID'] ?? 0);
  8270. if ($rid > 0) {
  8271. $mainBySid[$rid] = $rw;
  8272. }
  8273. }
  8274. if ($mainBySid === []) {
  8275. $detailRows = [];
  8276. } else {
  8277. try {
  8278. $detailRows = Db::table('purchase_order_detail')
  8279. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8280. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8281. ->order('status', 'desc')
  8282. ->order('CCYDH', 'asc')
  8283. ->order('company_name', 'asc')
  8284. ->order('id', 'asc')
  8285. ->select();
  8286. } catch (\Throwable $e) {
  8287. try {
  8288. $detailRows = Db::table('purchase_order_detail')
  8289. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8290. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8291. ->order('status', 'desc')
  8292. ->order('CCYDH', 'asc')
  8293. ->order('company_name', 'asc')
  8294. ->order('ID', 'asc')
  8295. ->select();
  8296. } catch (\Throwable $e2) {
  8297. $detailRows = [];
  8298. }
  8299. }
  8300. }
  8301. if (!is_array($detailRows)) {
  8302. $detailRows = [];
  8303. }
  8304. $exportLines = [];
  8305. $detailSidSeen = [];
  8306. foreach ($detailRows as $dr) {
  8307. if (!is_array($dr)) {
  8308. continue;
  8309. }
  8310. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8311. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8312. continue;
  8313. }
  8314. if (isset($detailSidSeen[$sid])) {
  8315. continue;
  8316. }
  8317. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  8318. continue;
  8319. }
  8320. $detailSidSeen[$sid] = true;
  8321. $m = $mainBySid[$sid];
  8322. $exportLines[] = [
  8323. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8324. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8325. 'company_name' => (string)($dr['company_name'] ?? ''),
  8326. 'CDF' => (string)($m['CDF'] ?? ''),
  8327. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8328. 'gx' => $this->procuremenExportGxText($m),
  8329. 'detail' => $dr,
  8330. ];
  8331. }
  8332. foreach ($detailRows as $dr) {
  8333. if (!is_array($dr)) {
  8334. continue;
  8335. }
  8336. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8337. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  8338. continue;
  8339. }
  8340. $detailSidSeen[$sid] = true;
  8341. $m = $mainBySid[$sid];
  8342. $exportLines[] = [
  8343. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8344. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8345. 'company_name' => (string)($dr['company_name'] ?? ''),
  8346. 'CDF' => (string)($m['CDF'] ?? ''),
  8347. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8348. 'gx' => $this->procuremenExportGxText($m),
  8349. 'detail' => $dr,
  8350. ];
  8351. }
  8352. foreach ($mainBySid as $sid => $m) {
  8353. if (isset($detailSidSeen[$sid])) {
  8354. continue;
  8355. }
  8356. $company = trim((string)($m['pick_company_name'] ?? ''));
  8357. $exportLines[] = [
  8358. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  8359. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  8360. 'company_name' => $company,
  8361. 'CDF' => (string)($m['CDF'] ?? ''),
  8362. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8363. 'gx' => $this->procuremenExportGxText($m),
  8364. 'detail' => [],
  8365. ];
  8366. }
  8367. $groups = [];
  8368. foreach ($exportLines as $line) {
  8369. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  8370. if (!isset($groups[$k])) {
  8371. $groups[$k] = [];
  8372. }
  8373. $groups[$k][] = $line;
  8374. }
  8375. ksort($groups, SORT_STRING);
  8376. $spreadsheet = new Spreadsheet();
  8377. $sheet = $spreadsheet->getActiveSheet();
  8378. $sheet->setTitle('外协加工明细');
  8379. $mon = (int)substr($ym, 5, 2);
  8380. $sheet->mergeCells('A1:H1');
  8381. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  8382. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  8383. $sheet->getStyle('A1')->getAlignment()
  8384. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8385. ->setVertical(Alignment::VERTICAL_CENTER);
  8386. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  8387. $col = 'A';
  8388. foreach ($headers as $h) {
  8389. $sheet->setCellValue($col . '2', $h);
  8390. $col++;
  8391. }
  8392. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  8393. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8394. $rowNum = 3;
  8395. $sumSubtotalCounts = 0;
  8396. $grandAmount = 0.0;
  8397. $globalSeq = 0;
  8398. if ($groups === []) {
  8399. $sheet->mergeCells('A3:H3');
  8400. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  8401. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8402. $rowNum = 4;
  8403. } else {
  8404. foreach ($groups as $items) {
  8405. if ($items === []) {
  8406. continue;
  8407. }
  8408. $groupLineCount = count($items);
  8409. $subAmount = 0.0;
  8410. foreach ($items as $line) {
  8411. $globalSeq++;
  8412. $dr = $line['detail'];
  8413. $amt = $this->procuremenExportAmount($dr);
  8414. $subAmount += $amt;
  8415. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  8416. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  8417. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  8418. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  8419. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  8420. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  8421. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  8422. $sheet->setCellValue('H' . $rowNum, $amt);
  8423. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  8424. $rowNum++;
  8425. }
  8426. $sumSubtotalCounts += $groupLineCount;
  8427. $grandAmount += $subAmount;
  8428. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8429. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  8430. $sheet->getStyle('G' . $rowNum)->getAlignment()
  8431. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8432. ->setVertical(Alignment::VERTICAL_CENTER);
  8433. $rowNum++;
  8434. }
  8435. }
  8436. $sheet->setCellValue('A' . $rowNum, '总计');
  8437. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  8438. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8439. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  8440. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8441. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  8442. $lastRow = $rowNum;
  8443. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  8444. 'borders' => [
  8445. 'allBorders' => [
  8446. 'borderStyle' => Border::BORDER_THIN,
  8447. 'color' => ['rgb' => '000000'],
  8448. ],
  8449. ],
  8450. ]);
  8451. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8452. if ($lastRow >= 3) {
  8453. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8454. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8455. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8456. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8457. }
  8458. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  8459. $sheet->getColumnDimension('A')->setWidth(7);
  8460. $sheet->getColumnDimension('B')->setWidth(16);
  8461. $sheet->getColumnDimension('C')->setWidth(52);
  8462. $sheet->getColumnDimension('D')->setWidth(32);
  8463. $sheet->getColumnDimension('E')->setWidth(12);
  8464. $sheet->getColumnDimension('F')->setWidth(44);
  8465. $sheet->getColumnDimension('G')->setWidth(26);
  8466. $sheet->getColumnDimension('H')->setWidth(13);
  8467. $sheet->getRowDimension(1)->setRowHeight(28);
  8468. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  8469. $quoteStartRow = $lastRow + 3;
  8470. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
  8471. if ($quoteLastRow >= $quoteStartRow) {
  8472. $sheet->getColumnDimension('E')->setWidth(28);
  8473. }
  8474. $ymCompact = str_replace('-', '', $ym);
  8475. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  8476. $filename = $fileBase . '.xlsx';
  8477. try {
  8478. $this->ensurePurchaseMonthExportLogTable();
  8479. list($adminId, $adminName) = $this->GetUseName();
  8480. Db::table('purchase_month_export_log')->insert([
  8481. 'ym' => $ym,
  8482. 'admin_id' => (int)$adminId,
  8483. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  8484. 'row_count' => count($exportLines),
  8485. 'total_amount' => round($grandAmount, 2),
  8486. 'createtime' => time(),
  8487. ]);
  8488. } catch (\Throwable $e) {
  8489. Log::write('month export log: ' . $e->getMessage(), 'error');
  8490. }
  8491. if (ob_get_length()) {
  8492. ob_end_clean();
  8493. }
  8494. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  8495. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8496. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  8497. header('Cache-Control: max-age=0');
  8498. $writer = new Xlsx($spreadsheet);
  8499. $writer->save('php://output');
  8500. $spreadsheet->disconnectWorksheets();
  8501. unset($spreadsheet);
  8502. exit;
  8503. }
  8504. /**
  8505. * 导出用:工序列文案
  8506. */
  8507. protected function procuremenExportGxText(array $r)
  8508. {
  8509. $a = trim((string)($r['CDXMC'] ?? ''));
  8510. $b = trim((string)($r['CGYMC'] ?? ''));
  8511. if ($a !== '' && $b !== '') {
  8512. return $a . ':' . $b;
  8513. }
  8514. return $a !== '' ? $a : $b;
  8515. }
  8516. /**
  8517. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  8518. */
  8519. protected function procuremenExportAmount(array $r)
  8520. {
  8521. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  8522. if (!array_key_exists($k, $r)) {
  8523. continue;
  8524. }
  8525. $v = $r[$k];
  8526. if ($v === null || $v === '') {
  8527. continue;
  8528. }
  8529. if (is_numeric($v)) {
  8530. return (float)$v;
  8531. }
  8532. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  8533. if ($v !== '' && is_numeric($v)) {
  8534. return (float)$v;
  8535. }
  8536. }
  8537. return 0.0;
  8538. }
  8539. /**
  8540. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  8541. *
  8542. * @param array<int, array<string, mixed>> $detailRows
  8543. * @param array<int, array<string, mixed>> $mainBySid
  8544. * @return array<int, array<string, mixed>>
  8545. */
  8546. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  8547. {
  8548. $lines = [];
  8549. foreach ($detailRows as $dr) {
  8550. if (!is_array($dr)) {
  8551. continue;
  8552. }
  8553. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8554. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8555. continue;
  8556. }
  8557. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  8558. continue;
  8559. }
  8560. $cn = trim((string)($dr['company_name'] ?? ''));
  8561. if ($cn === '') {
  8562. continue;
  8563. }
  8564. $m = $mainBySid[$sid];
  8565. $am = trim((string)($dr['amount'] ?? ''));
  8566. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  8567. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  8568. $amountText = $amountFilled
  8569. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  8570. : '未填写';
  8571. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  8572. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  8573. if ($deliveryShow === '' && $deliveryRaw !== '') {
  8574. $deliveryShow = $deliveryRaw;
  8575. }
  8576. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  8577. ? $deliveryShow
  8578. : '未填写';
  8579. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  8580. $lines[] = [
  8581. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8582. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8583. 'gx' => $this->procuremenExportGxText($m),
  8584. 'company_name' => $cn,
  8585. 'amount_text' => $amountText,
  8586. 'amount_num' => $amountFilled ? $amountNum : null,
  8587. 'delivery_text' => $deliveryText,
  8588. 'picked_text' => $picked ? '中标' : '未中标',
  8589. 'picked' => $picked,
  8590. ];
  8591. }
  8592. $winnerSupplierByOrder = [];
  8593. foreach ($lines as $line) {
  8594. $dh = trim((string)($line['CCYDH'] ?? ''));
  8595. $cn = trim((string)($line['company_name'] ?? ''));
  8596. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  8597. $winnerSupplierByOrder[$dh][$cn] = true;
  8598. }
  8599. }
  8600. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  8601. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  8602. if ($c !== 0) {
  8603. return $c;
  8604. }
  8605. $dh = trim((string)($a['CCYDH'] ?? ''));
  8606. $aCn = trim((string)($a['company_name'] ?? ''));
  8607. $bCn = trim((string)($b['company_name'] ?? ''));
  8608. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  8609. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  8610. if ($aSupplierWin !== $bSupplierWin) {
  8611. return $aSupplierWin ? -1 : 1;
  8612. }
  8613. $c = strcmp($aCn, $bCn);
  8614. if ($c !== 0) {
  8615. return $c;
  8616. }
  8617. if (!empty($a['picked']) !== !empty($b['picked'])) {
  8618. return !empty($a['picked']) ? -1 : 1;
  8619. }
  8620. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  8621. if ($c !== 0) {
  8622. return $c;
  8623. }
  8624. return 0;
  8625. });
  8626. return $lines;
  8627. }
  8628. /**
  8629. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  8630. *
  8631. * @param array<int, array<string, mixed>> $quoteLines
  8632. */
  8633. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  8634. {
  8635. $mon = (int)substr($ym, 5, 2);
  8636. $titleRow = $startRow;
  8637. $headerRow = $startRow + 1;
  8638. $dataStartRow = $startRow + 2;
  8639. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  8640. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  8641. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  8642. $sheet->getStyle('A' . $titleRow)->getAlignment()
  8643. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8644. ->setVertical(Alignment::VERTICAL_CENTER);
  8645. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  8646. $col = 'A';
  8647. foreach ($headers as $h) {
  8648. $sheet->setCellValue($col . $headerRow, $h);
  8649. $col++;
  8650. }
  8651. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  8652. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8653. $rowNum = $dataStartRow;
  8654. if ($quoteLines === []) {
  8655. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  8656. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  8657. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8658. $rowNum = $dataStartRow + 1;
  8659. } else {
  8660. $i = 0;
  8661. foreach ($quoteLines as $line) {
  8662. $i++;
  8663. $sheet->setCellValue('A' . $rowNum, $i);
  8664. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  8665. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  8666. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  8667. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  8668. if ($line['amount_num'] !== null) {
  8669. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  8670. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  8671. } else {
  8672. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  8673. }
  8674. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  8675. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  8676. if (!empty($line['picked'])) {
  8677. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8678. }
  8679. $rowNum++;
  8680. }
  8681. }
  8682. $lastRow = $rowNum - 1;
  8683. if ($lastRow >= $headerRow) {
  8684. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  8685. 'borders' => [
  8686. 'allBorders' => [
  8687. 'borderStyle' => Border::BORDER_THIN,
  8688. 'color' => ['rgb' => '000000'],
  8689. ],
  8690. ],
  8691. ]);
  8692. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8693. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8694. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8695. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8696. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  8697. if ($lastRow >= $dataStartRow) {
  8698. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  8699. }
  8700. }
  8701. return $lastRow;
  8702. }
  8703. /**
  8704. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  8705. */
  8706. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  8707. {
  8708. if ($lastRow < $dataStartRow || $headerRow < 1) {
  8709. return;
  8710. }
  8711. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  8712. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8713. ->setVertical(Alignment::VERTICAL_CENTER);
  8714. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  8715. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8716. ->setVertical(Alignment::VERTICAL_CENTER);
  8717. if ($lastCol > 'B') {
  8718. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  8719. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8720. ->setVertical(Alignment::VERTICAL_CENTER);
  8721. }
  8722. }
  8723. /**
  8724. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  8725. */
  8726. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  8727. {
  8728. $s = trim($ccydh);
  8729. if ($s === '') {
  8730. return 'ORDER';
  8731. }
  8732. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  8733. $s = trim($s, '._-');
  8734. if ($s === '') {
  8735. return 'ORDER';
  8736. }
  8737. if (function_exists('mb_substr')) {
  8738. return mb_substr($s, 0, 80, 'UTF-8');
  8739. }
  8740. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  8741. }
  8742. /**
  8743. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  8744. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  8745. *
  8746. * @return array{objectKey: string, webPath: string}
  8747. */
  8748. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  8749. {
  8750. $sid = (int)$scydgyId;
  8751. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  8752. $y = date('Y');
  8753. $m = date('m');
  8754. $d = date('d');
  8755. $basename = $safeOrder . '_' . $sid . '.pdf';
  8756. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  8757. return [
  8758. 'objectKey' => $objectKey,
  8759. 'webPath' => '/' . $objectKey,
  8760. ];
  8761. }
  8762. /**
  8763. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  8764. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  8765. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  8766. *
  8767. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  8768. */
  8769. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  8770. {
  8771. if (!$this->isValidScydgyRowId($scydgyId)) {
  8772. return '';
  8773. }
  8774. $ids = trim((string)$scydgyId);
  8775. $prep = $this->prepareProcuremenDetailsView($ids);
  8776. if (!$prep['ok']) {
  8777. return '';
  8778. }
  8779. $ccydh = $prep['ccydh'];
  8780. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  8781. $objectKey = $paths['objectKey'];
  8782. $webPath = $paths['webPath'];
  8783. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  8784. $this->view->assign([
  8785. 'pdf_export' => 1,
  8786. 'pdfMetaLine' => $meta,
  8787. ]);
  8788. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  8789. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8790. $this->view->engine->layout(false);
  8791. try {
  8792. $html = $this->view->fetch('procuremen/details_pdf_shell');
  8793. } catch (\Throwable $e) {
  8794. if ($restoreLayout) {
  8795. $this->view->engine->layout($restoreLayout);
  8796. }
  8797. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  8798. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8799. return '';
  8800. }
  8801. if ($restoreLayout) {
  8802. $this->view->engine->layout($restoreLayout);
  8803. }
  8804. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8805. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  8806. if (!is_dir($tempDir)) {
  8807. @mkdir($tempDir, 0755, true);
  8808. }
  8809. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  8810. try {
  8811. $mpdf = new \Mpdf\Mpdf([
  8812. 'mode' => 'utf-8',
  8813. 'format' => 'A4',
  8814. 'margin_left' => 12,
  8815. 'margin_right' => 12,
  8816. 'margin_top' => 14,
  8817. 'margin_bottom' => 14,
  8818. 'tempDir' => $tempDir,
  8819. 'autoScriptToLang' => true,
  8820. 'autoLangToFont' => true,
  8821. ]);
  8822. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  8823. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  8824. $mpdf->SetBasePath('http://127.0.0.1/');
  8825. $mpdf->WriteHTML($html);
  8826. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  8827. } catch (\Throwable $e) {
  8828. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  8829. if (is_file($tempPdf)) {
  8830. @unlink($tempPdf);
  8831. }
  8832. return '';
  8833. }
  8834. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  8835. if ($ossUrl !== '') {
  8836. @unlink($tempPdf);
  8837. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8838. return $ossUrl;
  8839. }
  8840. $pi = pathinfo($objectKey);
  8841. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  8842. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  8843. if ($baseFile === '') {
  8844. @unlink($tempPdf);
  8845. return '';
  8846. }
  8847. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  8848. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  8849. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  8850. @unlink($tempPdf);
  8851. return '';
  8852. }
  8853. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  8854. if (!@copy($tempPdf, $fullPath)) {
  8855. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  8856. @unlink($tempPdf);
  8857. return '';
  8858. }
  8859. @unlink($tempPdf);
  8860. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8861. return $webPath;
  8862. }
  8863. /**
  8864. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  8865. */
  8866. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  8867. {
  8868. if ($scydgyId <= 0 || $webPath === '') {
  8869. return;
  8870. }
  8871. try {
  8872. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  8873. } catch (\Throwable $e) {
  8874. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  8875. }
  8876. }
  8877. /**
  8878. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  8879. *
  8880. * @param array<string, string> $vars
  8881. * @return array<string, string>
  8882. */
  8883. protected function normalizeSmsTemplateVars(array $vars): array
  8884. {
  8885. $out = [];
  8886. foreach ($vars as $k => $v) {
  8887. $out[(string)$k] = trim((string)$v);
  8888. }
  8889. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  8890. $out['contact_name'] = $out['company_name'];
  8891. }
  8892. return $out;
  8893. }
  8894. /**
  8895. * 按手机号或公司名称查 customer 表联系人姓名
  8896. */
  8897. protected function resolveCustomerContactName(string $phone, string $companyName): string
  8898. {
  8899. $phone = trim($phone);
  8900. $companyName = trim($companyName);
  8901. try {
  8902. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  8903. $row = Db::table('customer')
  8904. ->where(function ($q) use ($phone) {
  8905. $q->where('phone', $phone)->whereOr('account', $phone);
  8906. })
  8907. ->order('id', 'asc')
  8908. ->find();
  8909. if (is_array($row)) {
  8910. $nm = trim((string)($row['username'] ?? ''));
  8911. if ($nm !== '') {
  8912. return $nm;
  8913. }
  8914. }
  8915. }
  8916. if ($companyName !== '') {
  8917. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  8918. if (is_array($row)) {
  8919. return trim((string)($row['username'] ?? ''));
  8920. }
  8921. }
  8922. } catch (\Throwable $e) {
  8923. }
  8924. return '';
  8925. }
  8926. /**
  8927. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  8928. */
  8929. protected function plainTextToHtmlEmailBody(string $text): string
  8930. {
  8931. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  8932. $parts = explode("\n", $text);
  8933. $out = [];
  8934. foreach ($parts as $line) {
  8935. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  8936. $out[] = $line;
  8937. } else {
  8938. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  8939. }
  8940. }
  8941. return implode("<br>\n", $out);
  8942. }
  8943. /**
  8944. * 短信场景:去掉链接类变量,避免误填 URL
  8945. *
  8946. * @param array<string, string> $vars
  8947. * @return array<string, string>
  8948. */
  8949. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  8950. {
  8951. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  8952. return $vars;
  8953. }
  8954. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  8955. $vars[$k] = '';
  8956. }
  8957. return $vars;
  8958. }
  8959. /**
  8960. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  8961. *
  8962. * @param array<string, string> $vars
  8963. */
  8964. protected function renderNotifyTemplate(string $scene, array $vars): string
  8965. {
  8966. $vars = $this->normalizeSmsTemplateVars($vars);
  8967. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  8968. $row = $this->loadNotifyTemplateRow($scene);
  8969. if ($row === null) {
  8970. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8971. }
  8972. $tpl = trim((string)($row['content'] ?? ''));
  8973. if ($tpl === '') {
  8974. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8975. }
  8976. foreach ($vars as $k => $v) {
  8977. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  8978. }
  8979. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  8980. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  8981. return $tpl;
  8982. }
  8983. protected function resolveProcuremenEmailSubject(string $scene): string
  8984. {
  8985. $map = [
  8986. 'review_email' => '您有新的协助加工订单',
  8987. ];
  8988. $subject = trim((string)($map[$scene] ?? ''));
  8989. if ($subject === '') {
  8990. $this->error('未配置邮件主题:' . $scene);
  8991. }
  8992. return $subject;
  8993. }
  8994. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  8995. {
  8996. $map = [
  8997. 'review_email' => '协助下发-邮箱',
  8998. 'review_sms' => '协助下发-短信',
  8999. 'confirm_ok' => '采购确认-通过',
  9000. 'confirm_fail' => '采购确认-未通过',
  9001. 'bid_open' => '开标双重验证',
  9002. ];
  9003. $label = $map[$scene] ?? $scene;
  9004. if ($titleRequired) {
  9005. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  9006. }
  9007. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  9008. }
  9009. /**
  9010. * 是否开启协助通知演练(不发真实短信/邮件)
  9011. */
  9012. protected function isProcuremenNotifyDryRun(): bool
  9013. {
  9014. return (bool)Config::get('procuremen_notify_dry_run');
  9015. }
  9016. /**
  9017. * @param array<string, mixed> $payload
  9018. */
  9019. protected function recordNotifyDryRunPreview(array $payload): void
  9020. {
  9021. $this->notifyDryRunPreview[] = $payload;
  9022. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  9023. }
  9024. /**
  9025. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  9026. * @throws \Exception
  9027. */
  9028. protected function smsbao($phone, $content)
  9029. {
  9030. if ($this->isProcuremenNotifyDryRun()) {
  9031. $this->recordNotifyDryRunPreview([
  9032. 'scene' => 'sms_only',
  9033. 'phone' => $phone,
  9034. 'sms_content' => $content,
  9035. ]);
  9036. return;
  9037. }
  9038. $statusStr = [
  9039. '0' => '短信发送成功',
  9040. '-1' => '参数不全',
  9041. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  9042. '30' => '密码错误',
  9043. '40' => '账号不存在',
  9044. '41' => '余额不足',
  9045. '42' => '帐户已过期',
  9046. '43' => 'IP地址限制',
  9047. '50' => '内容含有敏感词',
  9048. ];
  9049. $smsapi = 'http://api.smsbao.com/';
  9050. $user = 'zhuwei123';
  9051. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  9052. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  9053. $result = @file_get_contents($sendurl);
  9054. if ($result === false) {
  9055. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  9056. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  9057. }
  9058. $result = trim((string)$result);
  9059. if ($result !== '0') {
  9060. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  9061. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  9062. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  9063. }
  9064. }
  9065. }