Procuremen.php 343 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenStatus;
  8. use app\common\library\ProcuremenTime;
  9. use PHPMailer\PHPMailer\PHPMailer;
  10. use think\Config;
  11. use think\Cache;
  12. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  13. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  14. use PhpOffice\PhpSpreadsheet\Style\Border;
  15. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  16. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  17. use think\Db;
  18. use think\Log;
  19. class Procuremen extends Backend
  20. {
  21. /**
  22. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  23. */
  24. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  25. /**
  26. * Procuremen模型对象
  27. * @var \app\admin\model\Procuremen
  28. */
  29. protected $model = null;
  30. /**
  31. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  32. */
  33. protected $notifyDryRunPreview = [];
  34. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  35. protected $procuremenRedisCache = null;
  36. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  37. protected $pickHiddenScydgySetCache = null;
  38. /** 邮件发送日志表结构已就绪缓存键 */
  39. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  40. /**
  41. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  42. * @var array
  43. */
  44. protected $noNeedRight = [
  45. 'pickreview', 'review', 'reviewcompanies',
  46. ];
  47. public function _initialize()
  48. {
  49. parent::_initialize();
  50. $this->model = new \app\admin\model\Procuremen;
  51. $this->maybeMigrateLegacyWflowStatusText();
  52. $this->assignProcuremenAuthConfig();
  53. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  54. $this->ensurePurchaseEmailSendLogTableOnce();
  55. }
  56. }
  57. /**
  58. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  59. */
  60. protected function maybeMigrateLegacyWflowStatusText(): void
  61. {
  62. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  63. if (is_file($flagFile)) {
  64. return;
  65. }
  66. $map = [
  67. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  68. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  69. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  70. '3' => ProcuremenStatus::WFLOW_APPROVED,
  71. ];
  72. try {
  73. foreach ($map as $num => $text) {
  74. Db::table('purchase_order')
  75. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  76. ->update(['wflow_status' => $text]);
  77. }
  78. @file_put_contents($flagFile, date('c'));
  79. } catch (\Throwable $e) {
  80. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  81. }
  82. }
  83. /**
  84. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  85. *
  86. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  87. */
  88. protected function hasProcuremenPerm(array $actions): bool
  89. {
  90. foreach ($actions as $action) {
  91. $action = strtolower(trim((string)$action));
  92. if ($action === '') {
  93. continue;
  94. }
  95. if (strpos($action, 'procuremen/') !== 0) {
  96. $action = 'procuremen/' . $action;
  97. }
  98. if ($this->auth->check($action)) {
  99. return true;
  100. }
  101. }
  102. $suffixes = [];
  103. foreach ($actions as $action) {
  104. $action = strtolower(trim((string)$action));
  105. $action = preg_replace('#^procuremen/#', '', $action);
  106. if ($action !== '') {
  107. $suffixes[$action] = true;
  108. }
  109. }
  110. if ($suffixes === []) {
  111. return false;
  112. }
  113. try {
  114. foreach ($this->auth->getRuleList() as $rule) {
  115. $rule = strtolower((string)$rule);
  116. if (strpos($rule, 'procuremen/') !== 0) {
  117. continue;
  118. }
  119. foreach (array_keys($suffixes) as $suffix) {
  120. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  121. return true;
  122. }
  123. }
  124. }
  125. } catch (\Throwable $e) {
  126. }
  127. return false;
  128. }
  129. /**
  130. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  131. *
  132. * @param string[] $actions
  133. */
  134. protected function hasProcuremenPermStrict(array $actions): bool
  135. {
  136. foreach ($actions as $action) {
  137. $action = strtolower(trim((string)$action));
  138. if ($action === '') {
  139. continue;
  140. }
  141. if (strpos($action, 'procuremen/') !== 0) {
  142. $action = 'procuremen/' . $action;
  143. }
  144. if ($this->auth->check($action)) {
  145. return true;
  146. }
  147. }
  148. return false;
  149. }
  150. /**
  151. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  152. *
  153. * @param string[] $titles
  154. */
  155. protected function authHasAssignedRuleTitle(array $titles): bool
  156. {
  157. $titles = array_values(array_filter(array_map('trim', $titles)));
  158. if ($titles === []) {
  159. return false;
  160. }
  161. try {
  162. $ids = $this->auth->getRuleIds();
  163. if (in_array('*', $ids, true)) {
  164. return true;
  165. }
  166. if ($ids === []) {
  167. return false;
  168. }
  169. $rows = Db::name('auth_rule')
  170. ->where('status', 'normal')
  171. ->whereIn('id', $ids)
  172. ->column('title');
  173. foreach ($rows as $title) {
  174. $t = trim((string)$title);
  175. if ($t !== '' && in_array($t, $titles, true)) {
  176. return true;
  177. }
  178. }
  179. } catch (\Throwable $e) {
  180. }
  181. return false;
  182. }
  183. protected function procuremenCanPickDelete(): bool
  184. {
  185. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  186. return true;
  187. }
  188. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  189. }
  190. protected function procuremenCanComplete(): bool
  191. {
  192. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  193. return true;
  194. }
  195. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  196. }
  197. protected function procuremenCanDispatch(): bool
  198. {
  199. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  200. }
  201. /**
  202. * 前端按钮显隐(Config.procuremenAuth)
  203. */
  204. protected function assignProcuremenAuthConfig(): void
  205. {
  206. $authMap = [
  207. 'pickreview' => $this->procuremenCanDispatch(),
  208. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  209. 'pickdelete' => $this->procuremenCanPickDelete(),
  210. 'completedirectly' => $this->procuremenCanComplete(),
  211. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  212. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  213. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  214. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  215. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  216. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  217. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  218. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  219. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  220. 'details' => $this->hasProcuremenPerm(['details']),
  221. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  222. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  223. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  224. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  225. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  226. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  227. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  228. 'add' => $this->hasProcuremenPerm(['add']),
  229. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  230. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  231. ];
  232. $this->assignconfig('procuremenAuth', $authMap);
  233. }
  234. /**
  235. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  236. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  237. *
  238. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  239. */
  240. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  241. {
  242. static $mprocCfgLoaded = false;
  243. if (!$mprocCfgLoaded) {
  244. $mprocCfgLoaded = true;
  245. if (is_file(APP_PATH . 'extra/mproc.php')) {
  246. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  247. }
  248. }
  249. $eid = (int)$purchaseOrderDetailId;
  250. $base = $this->resolveMprocMobilePublicBaseUrl();
  251. if ($base === '') {
  252. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  253. }
  254. $path = trim((string)Config::get('mproc.mobile_index_path'));
  255. if ($path === '') {
  256. $path = '/index.php/index/index/index';
  257. } else {
  258. $path = '/' . ltrim($path, '/');
  259. }
  260. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  261. if ($eid > 0) {
  262. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  263. }
  264. return $base . $path . '?main_tab=orders';
  265. }
  266. /**
  267. * 邮件/短信外链:须为带点的公网域名
  268. */
  269. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  270. {
  271. $u = trim((string)$baseUrl);
  272. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  273. return false;
  274. }
  275. $host = parse_url($u, PHP_URL_HOST);
  276. if (!is_string($host) || $host === '') {
  277. return false;
  278. }
  279. if (strcasecmp($host, 'localhost') === 0) {
  280. return false;
  281. }
  282. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  283. return false;
  284. }
  285. if (strpos($host, '.') === false) {
  286. return false;
  287. }
  288. return true;
  289. }
  290. /**
  291. * 解析用于协助邮件/短信的手机端站点根
  292. */
  293. protected function resolveMprocMobilePublicBaseUrl()
  294. {
  295. $candidates = [];
  296. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  297. $candidates[] = trim((string)Config::get('site.indexurl'));
  298. $cdn = trim((string)Config::get('site.cdnurl'));
  299. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  300. $candidates[] = rtrim($cdn, '/');
  301. }
  302. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  303. $candidates[] = $reqBase;
  304. foreach ($candidates as $c) {
  305. if ($c === '') {
  306. continue;
  307. }
  308. $c = rtrim($c, '/');
  309. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  310. return $c;
  311. }
  312. }
  313. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  314. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  315. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  316. return $reqBase;
  317. }
  318. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  319. return '';
  320. }
  321. /**
  322. * 获取 Redis 中 procuremen_redis
  323. */
  324. protected function ProcuremenRedis(): array
  325. {
  326. if ($this->procuremenRedisCache !== null) {
  327. return $this->procuremenRedisCache;
  328. }
  329. try {
  330. $redis = redis();
  331. $raw = $redis->get('procuremen_redis');
  332. if ($raw === false || $raw === '') {
  333. $this->procuremenRedisCache = [];
  334. return $this->procuremenRedisCache;
  335. }
  336. $decoded = json_decode($raw, true);
  337. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  338. $this->procuremenRedisCache = [];
  339. return $this->procuremenRedisCache;
  340. }
  341. $this->procuremenRedisCache = $decoded['data'];
  342. return $this->procuremenRedisCache;
  343. } catch (\Throwable $e) {
  344. $this->procuremenRedisCache = [];
  345. return $this->procuremenRedisCache;
  346. }
  347. }
  348. /**
  349. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  350. *
  351. * @return array<int, array<string, mixed>>
  352. */
  353. protected function procuremenFetchErpPoolFromDb(): array
  354. {
  355. try {
  356. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  357. $endTime = date('Y-m-d 23:59:59');
  358. $list = Db::table('scydgy')
  359. ->alias('a')
  360. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  361. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  362. ->where([
  363. 'a.bwjg' => 1,
  364. 'a.iEndBz' => 0,
  365. 'a.iType' => 0,
  366. 'a.iStatus' => 10,
  367. ])
  368. ->where('a.dStamp', '>=', $startTime)
  369. ->where('a.dStamp', '<=', $endTime)
  370. ->order('a.dStamp', 'desc')
  371. ->select();
  372. if (!is_array($list)) {
  373. return [];
  374. }
  375. try {
  376. $redis = redis();
  377. $payload = [
  378. 'code' => 200,
  379. 'msg' => 'success',
  380. 'data' => $list,
  381. ];
  382. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  383. $this->procuremenRedisCache = $list;
  384. } catch (\Throwable $e) {
  385. }
  386. return $list;
  387. } catch (\Throwable $e) {
  388. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  389. return [];
  390. }
  391. }
  392. /**
  393. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  394. *
  395. * @return array<int, array<string, mixed>>
  396. */
  397. protected function procuremenEnsureRedisPool(): array
  398. {
  399. $pool = $this->ProcuremenRedis();
  400. if (is_array($pool) && $pool !== []) {
  401. return $pool;
  402. }
  403. static $warmed = false;
  404. if ($warmed) {
  405. return is_array($pool) ? $pool : [];
  406. }
  407. $warmed = true;
  408. return $this->procuremenFetchErpPoolFromDb();
  409. }
  410. /**
  411. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  412. *
  413. * @param array<string, mixed> $row
  414. */
  415. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  416. {
  417. $t = $this->procuremenRowListSortTime($row, $primary);
  418. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  419. return null;
  420. }
  421. $mo = (int)$m[2];
  422. if ($mo < 1 || $mo > 12) {
  423. return null;
  424. }
  425. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  426. }
  427. /**
  428. * @param array<int, array{year:string, months:array}> $sidebar
  429. * @return array<int, array{year:string, months:array}>
  430. */
  431. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  432. {
  433. $ym = trim($ym);
  434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  435. return $sidebar;
  436. }
  437. foreach ($sidebar as $block) {
  438. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  439. continue;
  440. }
  441. foreach ($block['months'] as $item) {
  442. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  443. return $sidebar;
  444. }
  445. }
  446. }
  447. $y = substr($ym, 0, 4);
  448. $mo = (int)substr($ym, 5, 2);
  449. $sidebar[] = [
  450. 'year' => $y,
  451. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  452. ];
  453. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  454. }
  455. /**
  456. * @param array<int, array{year:string, months:array}> $sidebar
  457. * @return string[]
  458. */
  459. protected function flattenProcuremenSidebarYms(array $sidebar): array
  460. {
  461. $yms = [];
  462. foreach ($sidebar as $block) {
  463. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  464. continue;
  465. }
  466. foreach ($block['months'] as $item) {
  467. if (!is_array($item)) {
  468. continue;
  469. }
  470. $ym = trim((string)($item['ym'] ?? ''));
  471. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  472. $yms[$ym] = true;
  473. }
  474. }
  475. }
  476. return array_keys($yms);
  477. }
  478. /**
  479. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  480. */
  481. protected function GetIndexYearMonths()
  482. {
  483. $ymSet = [];
  484. $pool = $this->procuremenEnsureRedisPool();
  485. foreach ($pool as $r) {
  486. if (!is_array($r)) {
  487. continue;
  488. }
  489. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  490. if ($ym !== null) {
  491. $ymSet[$ym] = true;
  492. }
  493. }
  494. foreach ($this->loadPickManualOrderRows() as $r) {
  495. if (!is_array($r)) {
  496. continue;
  497. }
  498. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  499. if ($ym !== null) {
  500. $ymSet[$ym] = true;
  501. }
  502. }
  503. $ymList = array_keys($ymSet);
  504. if ($ymList === []) {
  505. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  506. }
  507. return $this->buildYearMonthSidebar($ymList);
  508. }
  509. /**
  510. * @param string[] $ymList 形如 2026-06
  511. * @return array<int, array{year:string, months:array}>
  512. */
  513. protected function buildYearMonthSidebar(array $ymList): array
  514. {
  515. rsort($ymList, SORT_STRING);
  516. $byYear = [];
  517. foreach ($ymList as $ym) {
  518. $y = substr($ym, 0, 4);
  519. $mo = (int)substr($ym, 5, 2);
  520. if (!isset($byYear[$y])) {
  521. $byYear[$y] = [];
  522. }
  523. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  524. }
  525. krsort($byYear, SORT_NUMERIC);
  526. foreach ($byYear as $y => $items) {
  527. usort($byYear[$y], function ($a, $b) {
  528. return strcmp($b['ym'], $a['ym']);
  529. });
  530. }
  531. $sidebar = [];
  532. foreach ($byYear as $y => $months) {
  533. $sidebar[] = ['year' => $y, 'months' => $months];
  534. }
  535. return $sidebar;
  536. }
  537. /**
  538. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  539. */
  540. protected function GetIssuedOrderYearMonths(string $stage): array
  541. {
  542. $ymSet = [];
  543. try {
  544. $query = Db::table('purchase_order');
  545. $this->applyPurchaseOrderNotDeletedWhere($query);
  546. if ($stage === 'audit') {
  547. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  548. } elseif ($stage === 'confirm') {
  549. $this->applyPurchaseOrderConfirmStageWhere($query);
  550. } else {
  551. return $this->GetIndexYearMonths();
  552. }
  553. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  554. if (is_array($rows)) {
  555. foreach ($rows as $r) {
  556. if (!is_array($r)) {
  557. continue;
  558. }
  559. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  560. if ($ym !== null) {
  561. $ymSet[$ym] = true;
  562. }
  563. }
  564. }
  565. } catch (\Throwable $e) {
  566. $ymSet = [];
  567. }
  568. $ymList = array_keys($ymSet);
  569. if ($ymList === []) {
  570. $def = $this->resolveProcuremenDefaultYm($stage);
  571. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  572. }
  573. return $this->buildYearMonthSidebar($ymList);
  574. }
  575. /**
  576. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  577. */
  578. protected function resolveProcuremenDefaultYm(string $stage): string
  579. {
  580. if ($stage === 'pick') {
  581. return date('Y-m');
  582. }
  583. try {
  584. $query = Db::table('purchase_order');
  585. $this->applyPurchaseOrderNotDeletedWhere($query);
  586. if ($stage === 'audit') {
  587. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  588. } elseif ($stage === 'confirm') {
  589. $this->applyPurchaseOrderConfirmStageWhere($query);
  590. } else {
  591. return date('Y-m');
  592. }
  593. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  594. if ($latest === null || $latest === '') {
  595. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  596. }
  597. $t = $this->formatProcuremenDetailTime($latest);
  598. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  599. return $m[1] . '-' . $m[2];
  600. }
  601. } catch (\Throwable $e) {
  602. }
  603. return date('Y-m');
  604. }
  605. protected function applyPurchaseOrderNotDeletedWhere($query): void
  606. {
  607. $query->whereRaw(
  608. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  609. );
  610. }
  611. /**
  612. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  613. */
  614. protected function applyPurchaseOrderConfirmStageWhere($query): void
  615. {
  616. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  617. $quoted = [];
  618. foreach ($vals as $v) {
  619. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  620. }
  621. if ($quoted === []) {
  622. $query->whereRaw('1 = 0');
  623. return;
  624. }
  625. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  626. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  627. }
  628. /**
  629. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  630. *
  631. * @param array<string, mixed> $row
  632. * @return array<string, mixed>
  633. */
  634. protected function normalizePurchaseOrderListTimeRow(array $row): array
  635. {
  636. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  637. $pick = trim((string)($row['pick_time'] ?? ''));
  638. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  639. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  640. $t = trim((string)($row[$key] ?? ''));
  641. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  642. $row['pick_time'] = $t;
  643. break;
  644. }
  645. }
  646. }
  647. return $row;
  648. }
  649. /**
  650. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  651. */
  652. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  653. {
  654. if (!in_array($stage, ['audit', 'confirm'], true)) {
  655. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  656. }
  657. if ($pool === []) {
  658. $def = $this->resolveProcuremenDefaultYm($stage);
  659. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  660. }
  661. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  662. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  663. return false;
  664. }
  665. $monthStart = $ym . '-01 00:00:00';
  666. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  667. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  668. return $probe !== [];
  669. };
  670. if ($tryYm($requestedYm)) {
  671. return $requestedYm;
  672. }
  673. $fallback = $this->resolveProcuremenDefaultYm($stage);
  674. if ($tryYm($fallback)) {
  675. return $fallback;
  676. }
  677. $bestYm = '';
  678. $bestTime = '';
  679. foreach ($pool as $row) {
  680. if (!is_array($row)) {
  681. continue;
  682. }
  683. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  684. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  685. continue;
  686. }
  687. $ymRow = $m[1];
  688. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  689. $bestTime = $t;
  690. $bestYm = $ymRow;
  691. }
  692. }
  693. if ($bestYm !== '') {
  694. return $bestYm;
  695. }
  696. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  697. }
  698. protected function isPurchaseOrderDetailVoid(array $row): bool
  699. {
  700. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  701. return true;
  702. }
  703. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  704. }
  705. /**
  706. * 仅当前有效下发明细(排除废弃归档)
  707. */
  708. protected function applyActivePurchaseOrderDetailWhere($query): void
  709. {
  710. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  711. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  712. }
  713. /**
  714. * @param array<string, mixed> $detailRow
  715. */
  716. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  717. {
  718. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  719. return false;
  720. }
  721. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  722. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  723. }
  724. /**
  725. * 废弃退回初选:下发明细标记归档,不物理删除
  726. *
  727. * @param array<int, int|string> $scydgyIds
  728. */
  729. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  730. {
  731. $ids = [];
  732. foreach ($scydgyIds as $sid) {
  733. $n = (int)$sid;
  734. if ($this->isValidScydgyRowId($n) || $n < 0) {
  735. $ids[$n] = true;
  736. }
  737. }
  738. if ($ids === []) {
  739. return;
  740. }
  741. $void = ProcuremenStatus::POD_VOID;
  742. Db::table('purchase_order_detail')
  743. ->where('scydgy_id', 'in', array_keys($ids))
  744. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  745. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  746. ->update([
  747. 'status' => $void,
  748. 'status_name' => $void,
  749. ]);
  750. }
  751. /**
  752. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  753. */
  754. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  755. {
  756. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  757. $norm = function (string $col) use ($p): string {
  758. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  759. };
  760. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  761. $parts = [];
  762. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  763. if ($key === 'createtime') {
  764. $parts[] = $createtime;
  765. } else {
  766. $parts[] = $norm($key);
  767. }
  768. }
  769. return 'COALESCE(' . implode(', ', $parts) . ')';
  770. }
  771. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  772. {
  773. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  774. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  775. }
  776. /**
  777. * @return array<int, array<string, mixed>>
  778. */
  779. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  780. {
  781. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  782. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  783. try {
  784. $query = Db::table('purchase_order')->field($fields);
  785. $this->applyPurchaseOrderNotDeletedWhere($query);
  786. if ($stage === 'audit') {
  787. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  788. } elseif ($stage === 'confirm') {
  789. $this->applyPurchaseOrderConfirmStageWhere($query);
  790. } else {
  791. return [];
  792. }
  793. $query->order('pick_time', 'desc')->order('id', 'desc');
  794. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  795. $monthStart = $ym . '-01 00:00:00';
  796. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  797. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  798. }
  799. $rows = $query->select();
  800. } catch (\Throwable $e) {
  801. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  802. $rows = [];
  803. }
  804. return is_array($rows) ? $rows : [];
  805. }
  806. /**
  807. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  808. */
  809. protected function resolveProcuremenListStage(): string
  810. {
  811. $tab = trim((string)$this->request->request('wff_tab', ''));
  812. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  813. return $tab;
  814. }
  815. $action = strtolower((string)$this->request->action());
  816. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  817. return $action;
  818. }
  819. return 'pick';
  820. }
  821. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  822. {
  823. $rootTrue = rtrim((string)$this->request->root(true), '/');
  824. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  825. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  826. $indexPhpRoot = $rootTrue . '/index.php';
  827. }
  828. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  829. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  830. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  831. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  832. $this->view->assign('defaultYm', $defaultYm);
  833. $this->view->assign('sidebarYearMonths', $sidebar);
  834. $this->view->assign('procuremenStage', $stage);
  835. $this->view->assign('procuremenPageTitle', $pageTitle);
  836. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  837. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  838. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  839. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  840. }
  841. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  842. public function pick()
  843. {
  844. $this->request->filter(['strip_tags', 'trim']);
  845. if (!$this->request->isAjax()) {
  846. $this->assignProcuremenListPage('pick', '协助下发');
  847. return $this->view->fetch('procuremen/index');
  848. }
  849. return $this->index();
  850. }
  851. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  852. public function audit()
  853. {
  854. $this->request->filter(['strip_tags', 'trim']);
  855. if (!$this->request->isAjax()) {
  856. $this->assignProcuremenListPage('audit', '确认供应商');
  857. return $this->view->fetch('procuremen/index');
  858. }
  859. return $this->index();
  860. }
  861. /** 采购确认(定标) */
  862. public function confirm()
  863. {
  864. $this->request->filter(['strip_tags', 'trim']);
  865. if (!$this->request->isAjax()) {
  866. $this->assignProcuremenListPage('confirm', '采购确认');
  867. return $this->view->fetch('procuremen/index');
  868. }
  869. return $this->index();
  870. }
  871. /**
  872. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  873. */
  874. public function index()
  875. {
  876. $this->request->filter(['strip_tags', 'trim']);
  877. if (!$this->request->isAjax()) {
  878. $this->assignProcuremenListPage('pick', '协助下发');
  879. return $this->view->fetch('procuremen/index');
  880. }
  881. if ($this->request->request('keyField')) {
  882. return $this->selectpage();
  883. }
  884. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  885. $limit = max(10, min(500, (int)$limit));
  886. $ym = $this->request->request('ym', '');
  887. $ym = is_string($ym) ? trim($ym) : '';
  888. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  889. $wffTab = $this->resolveProcuremenListStage();
  890. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  891. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  892. ? $this->resolveProcuremenDefaultYm($wffTab)
  893. : date('Y-m');
  894. }
  895. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  896. $ym = date('Y-m');
  897. }
  898. $monthStart = $ym . '-01 00:00:00';
  899. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  900. $search = trim((string)$this->request->get('search', ''));
  901. $hasActiveSearch = ($search !== '');
  902. if (!$hasActiveSearch) {
  903. $filterStr = $this->request->get('filter', '');
  904. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  905. $arr = json_decode($filterStr, true);
  906. if (is_array($arr) && count($arr) > 0) {
  907. foreach ($arr as $v) {
  908. if (is_array($v)) {
  909. if (array_filter($v, function ($x) {
  910. return $x !== '' && $x !== null;
  911. })) {
  912. $hasActiveSearch = true;
  913. break;
  914. }
  915. } elseif ($v !== '' && $v !== null) {
  916. $hasActiveSearch = true;
  917. break;
  918. }
  919. }
  920. }
  921. }
  922. }
  923. $applyMonthRange = !$hasActiveSearch;
  924. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  925. $opArr = (array)json_decode($this->request->get('op', ''), true);
  926. try {
  927. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  928. if ($wffTab === 'audit') {
  929. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  930. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  931. );
  932. } elseif ($wffTab === 'confirm') {
  933. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  934. if ($dbRows === []) {
  935. try {
  936. $dbRows = Db::table('purchase_order')
  937. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  938. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  939. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  940. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  941. ->order('pick_time', 'desc')->order('id', 'desc')
  942. ->select();
  943. } catch (\Throwable $e) {
  944. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  945. $dbRows = [];
  946. }
  947. }
  948. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  949. if ($pool === []) {
  950. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  951. }
  952. } else {
  953. $pool = $this->procuremenEnsureRedisPool();
  954. if (!is_array($pool)) {
  955. $pool = [];
  956. }
  957. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  958. $hideSet = $this->loadPickHiddenScydgySet();
  959. if ($pool !== [] && $hideSet !== []) {
  960. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  961. if (!is_array($r)) {
  962. return false;
  963. }
  964. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  965. return $id <= 0 || !isset($hideSet[$id]);
  966. }));
  967. }
  968. $manualPool = $this->loadPickManualOrderRows();
  969. if ($manualPool !== []) {
  970. $pool = array_merge($pool, $manualPool);
  971. }
  972. if ($pool === []) {
  973. return json([
  974. 'total' => 0,
  975. 'rows' => [],
  976. ]);
  977. }
  978. }
  979. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  980. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  981. $monthStart = $ym . '-01 00:00:00';
  982. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  983. }
  984. $filtered = $this->filterProcuremenIndexPool(
  985. $pool,
  986. $monthStart,
  987. $monthEnd,
  988. $applyMonthRange,
  989. $search,
  990. $filterArr,
  991. $opArr,
  992. $listTimePrimary
  993. );
  994. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  995. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  996. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  997. }
  998. $sortField = 'ID';
  999. if (is_string($sort) && $sort !== '') {
  1000. $parts = explode(',', $sort);
  1001. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1002. if ($sortField === '') {
  1003. $sortField = 'ID';
  1004. }
  1005. }
  1006. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1007. $nFiltered = count($filtered);
  1008. if ($nFiltered > 1) {
  1009. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1010. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1011. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1012. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1013. if ($ta === $tb) {
  1014. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1015. }
  1016. if ($ta === '') {
  1017. return 1;
  1018. }
  1019. if ($tb === '') {
  1020. return -1;
  1021. }
  1022. return strcmp($ta, $tb) * $ord;
  1023. });
  1024. } elseif ($sortField === 'ID') {
  1025. $sortKeys = [];
  1026. foreach ($filtered as $i => $row) {
  1027. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1028. }
  1029. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1030. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1031. } elseif ($sortField === 'CCYDH') {
  1032. usort($filtered, function ($a, $b) use ($ord) {
  1033. $sa = trim((string)($a['CCYDH'] ?? ''));
  1034. $sb = trim((string)($b['CCYDH'] ?? ''));
  1035. if ($sa === $sb) {
  1036. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1037. }
  1038. if ($sa === '') {
  1039. return 1;
  1040. }
  1041. if ($sb === '') {
  1042. return -1;
  1043. }
  1044. return strcmp($sa, $sb) * $ord;
  1045. });
  1046. } else {
  1047. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1048. $va = $a[$sortField] ?? null;
  1049. $vb = $b[$sortField] ?? null;
  1050. $sa = (string)$va;
  1051. $sb = (string)$vb;
  1052. if ($sa === $sb) {
  1053. return 0;
  1054. }
  1055. return strcmp($sa, $sb) * $ord;
  1056. });
  1057. }
  1058. }
  1059. $offset = max(0, (int)$offset);
  1060. $limit = max(1, (int)$limit);
  1061. $rows = array_slice($filtered, $offset, $limit);
  1062. foreach ($rows as &$rw) {
  1063. if (!is_array($rw)) {
  1064. continue;
  1065. }
  1066. $rid = (int)($rw['ID'] ?? 0);
  1067. $rw['_iss_out'] = ($wffTab !== 'pick');
  1068. }
  1069. unset($rw);
  1070. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1071. $idList = [];
  1072. foreach ($rows as $rw) {
  1073. if (!is_array($rw)) {
  1074. continue;
  1075. }
  1076. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1077. foreach ($rw['_order_merge_rows'] as $mr) {
  1078. $mid = (int)($mr['ID'] ?? 0);
  1079. if ($this->isValidScydgyRowId($mid)) {
  1080. $idList[$mid] = true;
  1081. }
  1082. }
  1083. }
  1084. $id = (int)($rw['ID'] ?? 0);
  1085. if ($this->isValidScydgyRowId($id)) {
  1086. $idList[$id] = true;
  1087. }
  1088. }
  1089. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1090. foreach ($rows as &$rw) {
  1091. if (!is_array($rw)) {
  1092. continue;
  1093. }
  1094. $mergeIds = [];
  1095. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1096. foreach ($rw['_order_merge_rows'] as $mr) {
  1097. $mid = (int)($mr['ID'] ?? 0);
  1098. if ($this->isValidScydgyRowId($mid)) {
  1099. $mergeIds[$mid] = true;
  1100. }
  1101. }
  1102. }
  1103. $rid = (int)($rw['ID'] ?? 0);
  1104. if ($this->isValidScydgyRowId($rid)) {
  1105. $mergeIds[$rid] = true;
  1106. }
  1107. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1108. $rw['po_detail_count'] = $s['cnt'];
  1109. $rw['po_amount_fill_cnt'] = $s['amt'];
  1110. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1111. }
  1112. unset($rw);
  1113. }
  1114. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1115. $idList = [];
  1116. foreach ($rows as $rw) {
  1117. if (!is_array($rw)) {
  1118. continue;
  1119. }
  1120. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1121. foreach ($rw['_order_merge_rows'] as $mr) {
  1122. $mid = (int)($mr['ID'] ?? 0);
  1123. if ($this->isValidScydgyRowId($mid)) {
  1124. $idList[$mid] = true;
  1125. }
  1126. }
  1127. }
  1128. $id = (int)($rw['ID'] ?? 0);
  1129. if ($this->isValidScydgyRowId($id)) {
  1130. $idList[$id] = true;
  1131. }
  1132. }
  1133. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1134. $bidOpenSet = [];
  1135. if ($wffTab === 'audit') {
  1136. $ccydhList = [];
  1137. foreach ($rows as $rw0) {
  1138. if (!is_array($rw0)) {
  1139. continue;
  1140. }
  1141. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1142. if ($c0 !== '') {
  1143. $ccydhList[] = $c0;
  1144. }
  1145. }
  1146. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1147. }
  1148. foreach ($rows as &$rw) {
  1149. if (!is_array($rw)) {
  1150. continue;
  1151. }
  1152. $mergeIds = [];
  1153. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1154. foreach ($rw['_order_merge_rows'] as $mr) {
  1155. $mid = (int)($mr['ID'] ?? 0);
  1156. if ($this->isValidScydgyRowId($mid)) {
  1157. $mergeIds[$mid] = true;
  1158. }
  1159. }
  1160. }
  1161. $rid = (int)($rw['ID'] ?? 0);
  1162. if ($this->isValidScydgyRowId($rid)) {
  1163. $mergeIds[$rid] = true;
  1164. }
  1165. $buckets = [];
  1166. foreach (array_keys($mergeIds) as $mid) {
  1167. if (isset($quoteBucket[$mid])) {
  1168. $buckets[] = $quoteBucket[$mid];
  1169. }
  1170. }
  1171. $supplierText = $buckets !== []
  1172. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1173. : '';
  1174. if ($wffTab === 'confirm') {
  1175. $rw['picked_supplier_name'] = $supplierText;
  1176. } else {
  1177. $rw['notify_supplier_text'] = $supplierText;
  1178. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1179. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1180. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1181. $rw['bid_open_status_text'] = $verified ? '已开标' : '待开标';
  1182. }
  1183. }
  1184. unset($rw);
  1185. }
  1186. if ($wffTab === 'all' && count($rows) > 0) {
  1187. $this->mergePurchaseOrder($rows);
  1188. }
  1189. if ($wffTab === 'pick' && count($rows) > 0) {
  1190. $this->mergePurchaseOrder($rows);
  1191. }
  1192. foreach ($rows as &$rwClean) {
  1193. if (is_array($rwClean)) {
  1194. unset($rwClean['_order_merge_rows']);
  1195. if (array_key_exists('NGZL', $rwClean)) {
  1196. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1197. }
  1198. }
  1199. }
  1200. unset($rwClean);
  1201. return json([
  1202. 'total' => count($filtered),
  1203. 'rows' => $rows,
  1204. 'activeYm' => $ym,
  1205. ]);
  1206. } catch (\Throwable $e) {
  1207. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1208. return json([
  1209. 'total' => 0,
  1210. 'rows' => [],
  1211. ]);
  1212. }
  1213. }
  1214. /**
  1215. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1216. *
  1217. * @return array<int, true>
  1218. */
  1219. protected function loadPickHiddenScydgySet(): array
  1220. {
  1221. if ($this->pickHiddenScydgySetCache !== null) {
  1222. return $this->pickHiddenScydgySetCache;
  1223. }
  1224. $hideSet = [];
  1225. try {
  1226. $poIds = Db::table('purchase_order')
  1227. ->where(function ($q) {
  1228. $q->whereIn('wflow_status', array_merge(
  1229. ProcuremenStatus::wflowPendingConfirmValues(),
  1230. ProcuremenStatus::wflowPendingApprovalValues()
  1231. ))
  1232. ->whereOr(function ($q1) {
  1233. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1234. })
  1235. ->whereOr(function ($q2) {
  1236. $q2->whereNotNull('pick_time')
  1237. ->where('pick_time', '<>', '')
  1238. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1239. })
  1240. ->whereOr(function ($q3) {
  1241. $q3->whereNotNull('mod_rq')
  1242. ->where('mod_rq', '<>', '')
  1243. ->where('mod_rq', 'not like', '0000-00-00%');
  1244. });
  1245. })
  1246. ->column('scydgy_id');
  1247. if (is_array($poIds)) {
  1248. foreach ($poIds as $pid) {
  1249. $k = (int)$pid;
  1250. if ($k !== 0) {
  1251. $hideSet[$k] = true;
  1252. }
  1253. }
  1254. }
  1255. } catch (\Throwable $e) {
  1256. }
  1257. try {
  1258. $detIdsQuery = Db::table('purchase_order_detail');
  1259. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1260. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1261. if (is_array($detIds)) {
  1262. foreach ($detIds as $pid) {
  1263. $k = (int)$pid;
  1264. if ($this->isValidScydgyRowId($k)) {
  1265. $hideSet[$k] = true;
  1266. }
  1267. }
  1268. }
  1269. } catch (\Throwable $e) {
  1270. }
  1271. $this->pickHiddenScydgySetCache = $hideSet;
  1272. return $hideSet;
  1273. }
  1274. /**
  1275. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1276. *
  1277. * @return array<int, array<string, mixed>>
  1278. */
  1279. protected function loadPickManualOrderRows(): array
  1280. {
  1281. try {
  1282. $dbRows = Db::table('purchase_order')
  1283. ->where('scydgy_id', '<', 0)
  1284. ->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%\')')
  1285. ->order('scydgy_id', 'asc')
  1286. ->select();
  1287. } catch (\Throwable $e) {
  1288. try {
  1289. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1290. } catch (\Throwable $e2) {
  1291. return [];
  1292. }
  1293. }
  1294. if (!is_array($dbRows) || $dbRows === []) {
  1295. return [];
  1296. }
  1297. $detailSidSet = [];
  1298. try {
  1299. $negIds = [];
  1300. foreach ($dbRows as $dbRow) {
  1301. if (!is_array($dbRow)) {
  1302. continue;
  1303. }
  1304. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1305. if ($sid < 0) {
  1306. $negIds[$sid] = true;
  1307. }
  1308. }
  1309. if ($negIds !== []) {
  1310. $detQuery = Db::table('purchase_order_detail')
  1311. ->where('scydgy_id', 'in', array_keys($negIds));
  1312. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1313. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1314. if (is_array($detRows)) {
  1315. foreach ($detRows as $did) {
  1316. $detailSidSet[(int)$did] = true;
  1317. }
  1318. }
  1319. }
  1320. } catch (\Throwable $e) {
  1321. }
  1322. $pool = [];
  1323. foreach ($dbRows as $dbRow) {
  1324. if (!is_array($dbRow)) {
  1325. continue;
  1326. }
  1327. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1328. if ($sid >= 0) {
  1329. continue;
  1330. }
  1331. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1332. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1333. continue;
  1334. }
  1335. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1336. // 仅排除已完结;「进行中」含待下发的新建手工单,必须出现在初选
  1337. if ($st === ProcuremenStatus::PO_COMPLETED) {
  1338. continue;
  1339. }
  1340. if (isset($detailSidSet[$sid])) {
  1341. continue;
  1342. }
  1343. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1344. $r['_is_manual'] = 1;
  1345. $pool[] = $r;
  1346. }
  1347. return $pool;
  1348. }
  1349. /**
  1350. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1351. */
  1352. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1353. {
  1354. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1355. foreach ($keys as $k) {
  1356. $t = trim((string)($row[$k] ?? ''));
  1357. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1358. return $t;
  1359. }
  1360. }
  1361. return '';
  1362. }
  1363. /**
  1364. * 分配手工新增工序行 ID(负数递减)
  1365. */
  1366. protected function allocateManualScydgyId(): int
  1367. {
  1368. try {
  1369. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1370. $min = (int)$min;
  1371. return $min < 0 ? $min - 1 : -1;
  1372. } catch (\Throwable $e) {
  1373. return -1;
  1374. }
  1375. }
  1376. /**
  1377. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1378. */
  1379. protected function allocateManualOrderCcydh(): string
  1380. {
  1381. $prefix = 'YW' . date('Ymd');
  1382. $maxSeq = 0;
  1383. try {
  1384. $rows = Db::table('purchase_order')
  1385. ->where('CCYDH', 'like', $prefix . '%')
  1386. ->column('CCYDH');
  1387. if (is_array($rows)) {
  1388. foreach ($rows as $ccydh) {
  1389. $ccydh = trim((string)$ccydh);
  1390. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1391. $maxSeq = max($maxSeq, (int)$m[1]);
  1392. }
  1393. }
  1394. }
  1395. } catch (\Throwable $e) {
  1396. }
  1397. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1398. }
  1399. /**
  1400. * purchase_order.mod_rq 是否有有效软删除时间
  1401. */
  1402. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1403. {
  1404. $t = trim((string)$modRq);
  1405. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1406. }
  1407. /**
  1408. * 列表行 → purchase_order 写入字段
  1409. *
  1410. * @return array<string, mixed>
  1411. */
  1412. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1413. {
  1414. return [
  1415. 'scydgy_id' => $scydgyId,
  1416. 'CCYDH' => $row['CCYDH'] ?? null,
  1417. 'CYJMC' => $row['CYJMC'] ?? null,
  1418. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1419. 'CDXMC' => $row['CDXMC'] ?? null,
  1420. 'CGYBH' => $row['CGYBH'] ?? null,
  1421. 'CGYMC' => $row['CGYMC'] ?? null,
  1422. 'CDW' => $row['CDW'] ?? null,
  1423. 'NGZL' => $row['NGZL'] ?? null,
  1424. 'CDF' => $row['CDF'] ?? null,
  1425. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1426. 'MBZ' => $row['MBZ'] ?? null,
  1427. 'bwjg' => $row['bwjg'] ?? null,
  1428. 'iStatus' => $row['iStatus'] ?? null,
  1429. 'dStamp' => $row['dStamp'] ?? null,
  1430. 'dputrecord' => $row['dputrecord'] ?? null,
  1431. 'cywyxm' => $row['cywyxm'] ?? null,
  1432. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1433. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1434. ];
  1435. }
  1436. /**
  1437. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1438. *
  1439. * @return array{po:?array<string,mixed>, hidden:bool}
  1440. */
  1441. protected function resolvePickRowPoContext(int $sid): array
  1442. {
  1443. $po = null;
  1444. try {
  1445. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1446. if (is_array($found)) {
  1447. $po = $found;
  1448. }
  1449. } catch (\Throwable $e) {
  1450. }
  1451. $hideSet = $this->loadPickHiddenScydgySet();
  1452. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1453. }
  1454. /**
  1455. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1456. */
  1457. protected function assertPickRowCanDelete(int $sid, array $row): void
  1458. {
  1459. $ctx = $this->resolvePickRowPoContext($sid);
  1460. $po = $ctx['po'];
  1461. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1462. return;
  1463. }
  1464. if (is_array($po)) {
  1465. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1466. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1467. }
  1468. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1469. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1470. }
  1471. }
  1472. if ($ctx['hidden']) {
  1473. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1474. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1475. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1476. }
  1477. }
  1478. /**
  1479. * 初选直接完结前校验
  1480. */
  1481. protected function assertPickRowCanComplete(int $sid, array $row): void
  1482. {
  1483. $ctx = $this->resolvePickRowPoContext($sid);
  1484. $po = $ctx['po'];
  1485. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1486. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1487. }
  1488. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1489. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1490. }
  1491. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1492. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1493. }
  1494. }
  1495. /**
  1496. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1497. */
  1498. protected function softDeleteProcuremenPickRow(array $row): void
  1499. {
  1500. $sid = $this->extractScydgyRowId($row);
  1501. if (!$this->isValidScydgyRowId($sid)) {
  1502. throw new \InvalidArgumentException('无效的行主键');
  1503. }
  1504. $this->assertPickRowCanDelete($sid, $row);
  1505. $po = $this->resolvePickRowPoContext($sid)['po'];
  1506. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1507. return;
  1508. }
  1509. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1510. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1511. }
  1512. $now = date('Y-m-d H:i:s');
  1513. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1514. if (is_array($exists)) {
  1515. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1516. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1517. } else {
  1518. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1519. $data['mod_rq'] = $now;
  1520. $data['createtime'] = $now;
  1521. Db::table('purchase_order')->insert($data);
  1522. $poIdLog = (int)Db::getLastInsID();
  1523. }
  1524. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1525. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1526. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1527. if ($gymcLog !== '') {
  1528. $logTail .= ' / ' . $gymcLog;
  1529. }
  1530. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1531. }
  1532. /**
  1533. * 手工新增协助工序(写入 purchase_order)
  1534. *
  1535. * @param array<string, mixed> $params
  1536. * @return int scydgy_id
  1537. */
  1538. protected function saveManualPickOrder(array $params): int
  1539. {
  1540. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1541. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1542. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1543. if ($ccydh === '') {
  1544. $ccydh = $this->allocateManualOrderCcydh();
  1545. }
  1546. $now = date('Y-m-d H:i:s');
  1547. $sid = $this->allocateManualScydgyId();
  1548. $data = [
  1549. 'scydgy_id' => $sid,
  1550. 'CCYDH' => $ccydh,
  1551. 'CYJMC' => $cyjmc,
  1552. 'CGYMC' => $cgymc,
  1553. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1554. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1555. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1556. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1557. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1558. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1559. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1560. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1561. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1562. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1563. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  1564. 'createtime' => $now,
  1565. 'dStamp' => $now,
  1566. 'dputrecord' => $now,
  1567. ];
  1568. Db::table('purchase_order')->insert($data);
  1569. $poId = (int)Db::getLastInsID();
  1570. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1571. return $sid;
  1572. }
  1573. protected function formatProcuremenRowLabel(array $row): string
  1574. {
  1575. $dh = trim((string)($row['CCYDH'] ?? ''));
  1576. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1577. if ($dh !== '' && $gymc !== '') {
  1578. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1579. }
  1580. if ($dh !== '') {
  1581. return '订单「' . $dh . '」';
  1582. }
  1583. if ($gymc !== '') {
  1584. return '工序「' . $gymc . '」';
  1585. }
  1586. $id = $this->extractScydgyRowId($row);
  1587. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1588. }
  1589. /**
  1590. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1591. */
  1592. protected function extractScydgyRowId(array $row): int
  1593. {
  1594. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1595. }
  1596. protected function isValidScydgyRowId(int $id): bool
  1597. {
  1598. return ProcuremenGuard::isValidScydgyId($id);
  1599. }
  1600. protected function isManualScydgyRowId(int $id): bool
  1601. {
  1602. return $id < 0;
  1603. }
  1604. /**
  1605. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1606. *
  1607. * @param int[] $scydgyIds
  1608. * @return array<int, string[]>
  1609. */
  1610. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1611. {
  1612. $out = [];
  1613. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1614. if ($scydgyIds === []) {
  1615. return $out;
  1616. }
  1617. try {
  1618. $rows = Db::table('purchase_order_detail')
  1619. ->where('scydgy_id', 'in', $scydgyIds)
  1620. ->field('scydgy_id,company_name')
  1621. ->order('company_name', 'asc')
  1622. ->select();
  1623. } catch (\Throwable $e) {
  1624. $rows = [];
  1625. }
  1626. if (!is_array($rows)) {
  1627. return $out;
  1628. }
  1629. foreach ($rows as $r) {
  1630. if (!is_array($r)) {
  1631. continue;
  1632. }
  1633. $sid = (int)($r['scydgy_id'] ?? 0);
  1634. $cn = trim((string)($r['company_name'] ?? ''));
  1635. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1636. continue;
  1637. }
  1638. if (!isset($out[$sid])) {
  1639. $out[$sid] = [];
  1640. }
  1641. if (!in_array($cn, $out[$sid], true)) {
  1642. $out[$sid][] = $cn;
  1643. }
  1644. }
  1645. return $out;
  1646. }
  1647. /**
  1648. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1649. *
  1650. * @param string[] $names
  1651. */
  1652. protected function formatNotifySupplierDisplay(array $names): string
  1653. {
  1654. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1655. return trim((string)$n);
  1656. }, $names))));
  1657. if ($names === []) {
  1658. return '';
  1659. }
  1660. sort($names, SORT_STRING);
  1661. return implode("\n", $names);
  1662. }
  1663. /**
  1664. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1665. *
  1666. * @param int[] $scydgyIds
  1667. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1668. */
  1669. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1670. {
  1671. $out = [];
  1672. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1673. if ($scydgyIds === []) {
  1674. return $out;
  1675. }
  1676. try {
  1677. $rows = Db::table('purchase_order_detail')
  1678. ->where('scydgy_id', 'in', $scydgyIds)
  1679. ->field('scydgy_id,company_name,amount')
  1680. ->select();
  1681. } catch (\Throwable $e) {
  1682. $rows = [];
  1683. }
  1684. if (!is_array($rows)) {
  1685. return $out;
  1686. }
  1687. foreach ($rows as $r) {
  1688. if (!is_array($r)) {
  1689. continue;
  1690. }
  1691. $sid = (int)($r['scydgy_id'] ?? 0);
  1692. $cn = trim((string)($r['company_name'] ?? ''));
  1693. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1694. continue;
  1695. }
  1696. if (!isset($out[$sid])) {
  1697. $out[$sid] = ['all' => [], 'quoted' => []];
  1698. }
  1699. $out[$sid]['all'][$cn] = true;
  1700. $am = trim((string)($r['amount'] ?? ''));
  1701. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1702. $out[$sid]['quoted'][$cn] = true;
  1703. }
  1704. }
  1705. return $out;
  1706. }
  1707. /**
  1708. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1709. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1710. */
  1711. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1712. {
  1713. $merged = ['all' => [], 'quoted' => []];
  1714. foreach ($buckets as $b) {
  1715. if (!is_array($b)) {
  1716. continue;
  1717. }
  1718. foreach ($b['all'] ?? [] as $cn => $_) {
  1719. $merged['all'][$cn] = true;
  1720. }
  1721. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1722. $merged['quoted'][$cn] = true;
  1723. }
  1724. }
  1725. return $merged;
  1726. }
  1727. /**
  1728. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1729. */
  1730. protected function formatQuotedSupplierLines(array $bucket): string
  1731. {
  1732. $all = array_keys($bucket['all'] ?? []);
  1733. if ($all === []) {
  1734. return '';
  1735. }
  1736. sort($all, SORT_STRING);
  1737. $lines = [];
  1738. foreach ($all as $cn) {
  1739. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1740. $lines[] = $cn . '(' . $status . ')';
  1741. }
  1742. return implode("\n", $lines);
  1743. }
  1744. /**
  1745. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1746. */
  1747. protected function resolveBundleSysRq(array $bundle): string
  1748. {
  1749. foreach ($bundle['pos'] ?? [] as $po) {
  1750. if (!is_array($po)) {
  1751. continue;
  1752. }
  1753. $sr = trim((string)($po['sys_rq'] ?? ''));
  1754. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1755. return $sr;
  1756. }
  1757. }
  1758. return '';
  1759. }
  1760. /**
  1761. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1762. */
  1763. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1764. {
  1765. $raw = trim((string)$sysRq);
  1766. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1767. return true;
  1768. }
  1769. $ts = strtotime(str_replace('T', ' ', $raw));
  1770. if ($ts === false || $ts <= 0) {
  1771. return true;
  1772. }
  1773. return time() >= $ts;
  1774. }
  1775. /**
  1776. * 开标前校验:必须已过报价截止时间
  1777. *
  1778. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1779. */
  1780. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1781. {
  1782. $sysRq = $this->resolveBundleSysRq($bundle);
  1783. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1784. $this->error('未到截止时间');
  1785. }
  1786. }
  1787. /**
  1788. * 截止时间前:隐藏单价/交期真实值,统一展示文案
  1789. *
  1790. * @param array<string, mixed> $line
  1791. */
  1792. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  1793. {
  1794. $amountFilled = !empty($line['amount_filled']);
  1795. $deliveryFilled = !empty($line['delivery_filled']);
  1796. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  1797. $line['amount_show'] = '';
  1798. if (array_key_exists('amount_text', $line)) {
  1799. $line['amount_text'] = $line['unit_price_text'];
  1800. }
  1801. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  1802. $line['delivery_show'] = $deliveryText;
  1803. if (array_key_exists('delivery_text', $line)) {
  1804. $line['delivery_text'] = $deliveryText;
  1805. }
  1806. $line['delivery_ymd'] = '';
  1807. $line['subtotal_text'] = $amountFilled ? '' : '';
  1808. $line['subtotal_num'] = null;
  1809. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  1810. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  1811. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled) ? 1 : 0;
  1812. $line['amount_filled'] = false;
  1813. $line['delivery_filled'] = false;
  1814. $line['is_quoted'] = false;
  1815. if (array_key_exists('quote_label', $line)) {
  1816. $line['quote_label'] = ($amountFilled || $deliveryFilled) ? '未开标验证' : '未报价';
  1817. }
  1818. }
  1819. protected function ensurePurchaseOrderBidOpenTable(): void
  1820. {
  1821. try {
  1822. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  1823. } catch (\Throwable $e) {
  1824. Db::execute(
  1825. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  1826. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  1827. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  1828. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  1829. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  1830. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  1831. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  1832. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  1833. `operator_name` varchar(64) NOT NULL DEFAULT '',
  1834. `createtime` datetime DEFAULT NULL,
  1835. PRIMARY KEY (`id`),
  1836. UNIQUE KEY `uk_ccydh` (`ccydh`)
  1837. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  1838. );
  1839. }
  1840. }
  1841. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  1842. {
  1843. $ccydh = trim($ccydh);
  1844. if ($ccydh === '') {
  1845. return false;
  1846. }
  1847. $this->ensurePurchaseOrderBidOpenTable();
  1848. try {
  1849. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1850. return is_array($row);
  1851. } catch (\Throwable $e) {
  1852. return false;
  1853. }
  1854. }
  1855. /**
  1856. * 批量查询订单是否已开标验证
  1857. *
  1858. * @param array<int, string> $ccydhs
  1859. * @return array<string, bool> ccydh => true
  1860. */
  1861. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  1862. {
  1863. $set = [];
  1864. $list = [];
  1865. foreach ($ccydhs as $c) {
  1866. $c = trim((string)$c);
  1867. if ($c !== '') {
  1868. $list[$c] = true;
  1869. }
  1870. }
  1871. if ($list === []) {
  1872. return $set;
  1873. }
  1874. $this->ensurePurchaseOrderBidOpenTable();
  1875. try {
  1876. $rows = Db::table('purchase_order_bid_open')
  1877. ->where('ccydh', 'in', array_keys($list))
  1878. ->field('ccydh')
  1879. ->select();
  1880. foreach ($rows as $row) {
  1881. if (!is_array($row)) {
  1882. continue;
  1883. }
  1884. $c = trim((string)($row['ccydh'] ?? ''));
  1885. if ($c !== '') {
  1886. $set[$c] = true;
  1887. }
  1888. }
  1889. } catch (\Throwable $e) {
  1890. return [];
  1891. }
  1892. return $set;
  1893. }
  1894. /**
  1895. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  1896. *
  1897. * @param array<string, mixed> $group
  1898. */
  1899. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  1900. {
  1901. if ($quoteVisible) {
  1902. $group['remark_quote_pending'] = 0;
  1903. return;
  1904. }
  1905. $group['remark'] = '';
  1906. $group['remark_quote_pending'] = 0;
  1907. }
  1908. /**
  1909. * @param array{ccydh?:string} $bundle
  1910. */
  1911. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  1912. {
  1913. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  1914. }
  1915. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  1916. {
  1917. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  1918. }
  1919. protected function loadBidOpenAdminUser(int $adminId): ?array
  1920. {
  1921. if ($adminId <= 0) {
  1922. return null;
  1923. }
  1924. try {
  1925. $row = Db::name('admin')->where('id', $adminId)->find();
  1926. } catch (\Throwable $e) {
  1927. return null;
  1928. }
  1929. if (!is_array($row)) {
  1930. return null;
  1931. }
  1932. $status = strtolower(trim((string)($row['status'] ?? '')));
  1933. if ($status !== '' && $status !== 'normal') {
  1934. return null;
  1935. }
  1936. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  1937. return null;
  1938. }
  1939. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  1940. if (!preg_match('/^1\d{10}$/', $phone)) {
  1941. return null;
  1942. }
  1943. $name = trim((string)($row['nickname'] ?? ''));
  1944. if ($name === '') {
  1945. $name = trim((string)($row['username'] ?? ''));
  1946. }
  1947. return [
  1948. 'id' => (int)$row['id'],
  1949. 'username' => trim((string)($row['username'] ?? '')),
  1950. 'nickname' => $name,
  1951. 'mobile' => $phone,
  1952. ];
  1953. }
  1954. /**
  1955. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  1956. */
  1957. protected function bidOpenVerifierAuthGroupRootId(): int
  1958. {
  1959. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  1960. return $id > 0 ? $id : 10;
  1961. }
  1962. /**
  1963. * @return int[]
  1964. */
  1965. protected function loadBidOpenVerifierAuthGroupIds(): array
  1966. {
  1967. static $memo = [];
  1968. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  1969. if (isset($memo[$rootId])) {
  1970. return $memo[$rootId];
  1971. }
  1972. try {
  1973. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  1974. } catch (\Throwable $e) {
  1975. $memo[$rootId] = [$rootId];
  1976. return $memo[$rootId];
  1977. }
  1978. if (!is_array($groups) || $groups === []) {
  1979. $memo[$rootId] = [$rootId];
  1980. return $memo[$rootId];
  1981. }
  1982. $groupList = [];
  1983. foreach ($groups as $g) {
  1984. if (is_array($g)) {
  1985. $groupList[] = $g;
  1986. }
  1987. }
  1988. if ($groupList === []) {
  1989. $memo[$rootId] = [$rootId];
  1990. return $memo[$rootId];
  1991. }
  1992. $tree = \fast\Tree::instance();
  1993. $tree->init($groupList);
  1994. $ids = $tree->getChildrenIds($rootId, true);
  1995. if (!is_array($ids) || $ids === []) {
  1996. $memo[$rootId] = [$rootId];
  1997. return $memo[$rootId];
  1998. }
  1999. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2000. return $memo[$rootId];
  2001. }
  2002. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2003. {
  2004. if ($adminId <= 0) {
  2005. return false;
  2006. }
  2007. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2008. if ($groupIds === []) {
  2009. return false;
  2010. }
  2011. try {
  2012. return (bool)Db::name('auth_group_access')
  2013. ->where('uid', $adminId)
  2014. ->where('group_id', 'in', $groupIds)
  2015. ->count();
  2016. } catch (\Throwable $e) {
  2017. return false;
  2018. }
  2019. }
  2020. /**
  2021. * @return array<int, array<string, mixed>>
  2022. */
  2023. protected function listBidOpenVerifierCandidates(): array
  2024. {
  2025. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2026. if ($groupIds === []) {
  2027. return [];
  2028. }
  2029. try {
  2030. $adminIds = Db::name('auth_group_access')
  2031. ->where('group_id', 'in', $groupIds)
  2032. ->column('uid');
  2033. } catch (\Throwable $e) {
  2034. $adminIds = [];
  2035. }
  2036. $adminIds = is_array($adminIds)
  2037. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  2038. : [];
  2039. if ($adminIds === []) {
  2040. return [];
  2041. }
  2042. try {
  2043. $rows = Db::name('admin')
  2044. ->where('status', 'normal')
  2045. ->where('id', 'in', $adminIds)
  2046. ->where('mobile', '<>', '')
  2047. ->order('id', 'asc')
  2048. ->select();
  2049. } catch (\Throwable $e) {
  2050. return [];
  2051. }
  2052. if (!is_array($rows)) {
  2053. return [];
  2054. }
  2055. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  2056. $out = [];
  2057. foreach ($rows as $row) {
  2058. if (!is_array($row)) {
  2059. continue;
  2060. }
  2061. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  2062. if ($one === null) {
  2063. continue;
  2064. }
  2065. $out[] = [
  2066. 'id' => $one['id'],
  2067. 'username' => $one['username'],
  2068. 'nickname' => $one['nickname'],
  2069. 'group_name' => $groupNameMap[$one['id']] ?? '',
  2070. 'mobile' => mask_phone($one['mobile']),
  2071. ];
  2072. }
  2073. return $out;
  2074. }
  2075. /**
  2076. * @param int[] $adminIds
  2077. * @return array<int, string>
  2078. */
  2079. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2080. {
  2081. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2082. if ($adminIds === []) {
  2083. return [];
  2084. }
  2085. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2086. try {
  2087. $rows = Db::name('auth_group_access')
  2088. ->alias('aga')
  2089. ->join('auth_group ag', 'aga.group_id = ag.id')
  2090. ->where('aga.uid', 'in', $adminIds)
  2091. ->where('aga.group_id', 'in', $groupIds)
  2092. ->field('aga.uid,ag.name')
  2093. ->order('aga.uid', 'asc')
  2094. ->order('aga.group_id', 'asc')
  2095. ->select();
  2096. } catch (\Throwable $e) {
  2097. return [];
  2098. }
  2099. if (!is_array($rows)) {
  2100. return [];
  2101. }
  2102. $out = [];
  2103. foreach ($rows as $row) {
  2104. if (!is_array($row)) {
  2105. continue;
  2106. }
  2107. $uid = (int)($row['uid'] ?? 0);
  2108. $name = trim((string)($row['name'] ?? ''));
  2109. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2110. continue;
  2111. }
  2112. $out[$uid] = $name;
  2113. }
  2114. return $out;
  2115. }
  2116. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2117. {
  2118. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2119. }
  2120. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2121. {
  2122. return 'procuremen_bidopen_wait_' . $adminId;
  2123. }
  2124. protected function renderBidOpenVerifySms(string $code): string
  2125. {
  2126. $tpl = '';
  2127. try {
  2128. $row = $this->loadNotifyTemplateRow('bid_open');
  2129. if (is_array($row)) {
  2130. $tpl = trim((string)($row['content'] ?? ''));
  2131. }
  2132. } catch (\Throwable $e) {
  2133. $tpl = '';
  2134. }
  2135. if ($tpl === '') {
  2136. $tpl = '【可集达】您的短信验证码是{code}';
  2137. }
  2138. return str_replace('{code}', $code, $tpl);
  2139. }
  2140. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2141. {
  2142. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2143. }
  2144. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2145. {
  2146. $code = trim($code);
  2147. if (!preg_match('/^\d{6}$/', $code)) {
  2148. return false;
  2149. }
  2150. $mock = Config::get('mproc.mock_sms_code');
  2151. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2152. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2153. return true;
  2154. }
  2155. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2156. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2157. return false;
  2158. }
  2159. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2160. return true;
  2161. }
  2162. /**
  2163. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2164. */
  2165. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2166. {
  2167. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2168. if ($ccydh === '') {
  2169. throw new \InvalidArgumentException('订单号无效');
  2170. }
  2171. $this->ensurePurchaseOrderBidOpenTable();
  2172. list($operatorId, $operatorName) = $this->GetUseName();
  2173. $now = date('Y-m-d H:i:s');
  2174. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2175. $payload = [
  2176. 'ccydh' => $ccydh,
  2177. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2178. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2179. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2180. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2181. 'operator_id' => (int)$operatorId,
  2182. 'operator_name' => trim((string)$operatorName),
  2183. 'createtime' => $now,
  2184. ];
  2185. if (is_array($exists)) {
  2186. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2187. } else {
  2188. Db::table('purchase_order_bid_open')->insert($payload);
  2189. }
  2190. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2191. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2192. $orderPart = '(订单' . $ccydh . ')';
  2193. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2194. $seenSid = [];
  2195. foreach ($bundle['pos'] ?? [] as $poRow) {
  2196. if (!is_array($poRow)) {
  2197. continue;
  2198. }
  2199. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2200. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2201. continue;
  2202. }
  2203. $seenSid[$sid] = true;
  2204. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2205. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2206. }
  2207. if ($seenSid === []) {
  2208. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2209. if ($this->isValidScydgyRowId($anchor)) {
  2210. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2211. }
  2212. }
  2213. }
  2214. /**
  2215. * 报价行展示字段默认值(模板安全访问)
  2216. *
  2217. * @param array<string, mixed> $line
  2218. * @return array<string, mixed>
  2219. */
  2220. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2221. {
  2222. if (!array_key_exists('amount_quote_pending', $line)) {
  2223. $line['amount_quote_pending'] = 0;
  2224. }
  2225. if (!array_key_exists('delivery_quote_pending', $line)) {
  2226. $line['delivery_quote_pending'] = 0;
  2227. }
  2228. if (!array_key_exists('quote_before_deadline', $line)) {
  2229. $line['quote_before_deadline'] = 0;
  2230. }
  2231. if (!array_key_exists('amount_filled', $line)) {
  2232. $line['amount_filled'] = 0;
  2233. }
  2234. if (!array_key_exists('delivery_filled', $line)) {
  2235. $line['delivery_filled'] = 0;
  2236. }
  2237. return $line;
  2238. }
  2239. /**
  2240. * 审核弹窗:按供应商汇总报价明细
  2241. *
  2242. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2243. * @return array<int, array<string, mixed>>
  2244. */
  2245. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2246. {
  2247. $sids = [];
  2248. foreach ($bundle['pos'] ?? [] as $po) {
  2249. if (!is_array($po)) {
  2250. continue;
  2251. }
  2252. $sid = (int)($po['scydgy_id'] ?? 0);
  2253. if ($this->isValidScydgyRowId($sid)) {
  2254. $sids[$sid] = true;
  2255. }
  2256. }
  2257. if ($sids === []) {
  2258. return [];
  2259. }
  2260. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2261. $gymcMap = [];
  2262. $qtyBySid = [];
  2263. $orderedSids = [];
  2264. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2265. if (!is_array($mr)) {
  2266. continue;
  2267. }
  2268. $gid = $this->extractScydgyRowId($mr);
  2269. if ($this->isValidScydgyRowId($gid)) {
  2270. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2271. $orderedSids[] = $gid;
  2272. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2273. if ($qty === '') {
  2274. $qty = trim((string)($mr['NGZL'] ?? ''));
  2275. }
  2276. $qtyBySid[$gid] = $qty;
  2277. }
  2278. }
  2279. foreach ($bundle['pos'] ?? [] as $po) {
  2280. if (!is_array($po)) {
  2281. continue;
  2282. }
  2283. $gid = (int)($po['scydgy_id'] ?? 0);
  2284. if ($this->isValidScydgyRowId($gid)) {
  2285. $nm = trim((string)($po['CGYMC'] ?? ''));
  2286. if ($nm !== '') {
  2287. $gymcMap[$gid] = $nm;
  2288. }
  2289. if (!in_array($gid, $orderedSids, true)) {
  2290. $orderedSids[] = $gid;
  2291. }
  2292. }
  2293. }
  2294. try {
  2295. $detailsQuery = Db::table('purchase_order_detail')
  2296. ->where('scydgy_id', 'in', array_keys($sids));
  2297. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2298. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2299. } catch (\Throwable $e) {
  2300. try {
  2301. $detailsQuery = Db::table('purchase_order_detail')
  2302. ->where('scydgy_id', 'in', array_keys($sids));
  2303. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2304. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2305. } catch (\Throwable $e2) {
  2306. $details = [];
  2307. }
  2308. }
  2309. if (!is_array($details)) {
  2310. $details = [];
  2311. }
  2312. $byCompany = [];
  2313. foreach ($details as $d) {
  2314. if (!is_array($d)) {
  2315. continue;
  2316. }
  2317. $cn = trim((string)($d['company_name'] ?? ''));
  2318. if ($cn === '') {
  2319. continue;
  2320. }
  2321. if (!isset($byCompany[$cn])) {
  2322. $ph = trim((string)($d['phone'] ?? ''));
  2323. $username = trim((string)($d['username'] ?? ''));
  2324. if ($username === '') {
  2325. $username = $this->resolveCustomerContactName($ph, $cn);
  2326. }
  2327. $byCompany[$cn] = [
  2328. 'name' => $cn,
  2329. 'email' => trim((string)($d['email'] ?? '')),
  2330. 'phone' => $ph,
  2331. 'username' => $username,
  2332. 'remark' => '',
  2333. 'has_quote' => false,
  2334. 'lines_map' => [],
  2335. ];
  2336. }
  2337. if ($byCompany[$cn]['remark'] === '') {
  2338. $rm = '';
  2339. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2340. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2341. $rm = trim((string)$d[$rk]);
  2342. break;
  2343. }
  2344. }
  2345. if ($rm !== '') {
  2346. $byCompany[$cn]['remark'] = $rm;
  2347. }
  2348. }
  2349. $sid = (int)($d['scydgy_id'] ?? 0);
  2350. $am = trim((string)($d['amount'] ?? ''));
  2351. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2352. if ($gymc === '') {
  2353. $gymc = '工序';
  2354. }
  2355. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2356. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2357. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2358. $deliveryShow = $deliveryRaw;
  2359. }
  2360. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2361. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2362. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2363. $subtotal = null;
  2364. if ($amountNum !== null) {
  2365. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2366. }
  2367. $unitPriceText = $amountFilled
  2368. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2369. : '未填写';
  2370. $lineRow = [
  2371. 'cgymc' => $gymc,
  2372. 'amount' => $am,
  2373. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2374. 'amount_filled' => $amountFilled,
  2375. 'unit_price_text' => $unitPriceText,
  2376. 'delivery' => $deliveryRaw,
  2377. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2378. 'delivery_filled' => $deliveryFilled,
  2379. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2380. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2381. 'subtotal_num' => $subtotal,
  2382. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2383. 'is_quoted' => $amountFilled,
  2384. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2385. ];
  2386. if (!$quoteVisible) {
  2387. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2388. }
  2389. // 按工序 id 暂存,下面再按上方工序表顺序输出
  2390. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2391. }
  2392. foreach ($byCompany as $cn => $g) {
  2393. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  2394. $lines = [];
  2395. $usedSids = [];
  2396. foreach ($orderedSids as $sid) {
  2397. if (!isset($linesMap[$sid])) {
  2398. continue;
  2399. }
  2400. $lines[] = $linesMap[$sid];
  2401. $usedSids[$sid] = true;
  2402. }
  2403. foreach ($linesMap as $sid => $ln) {
  2404. if (isset($usedSids[$sid])) {
  2405. continue;
  2406. }
  2407. $lines[] = $ln;
  2408. }
  2409. $total = count($lines);
  2410. $quoted = 0;
  2411. $groupTotal = 0.0;
  2412. $groupHasTotal = false;
  2413. if ($quoteVisible) {
  2414. foreach ($lines as $ln) {
  2415. $am = trim((string)($ln['amount'] ?? ''));
  2416. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2417. $quoted++;
  2418. }
  2419. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2420. $groupTotal += (float)$ln['subtotal_num'];
  2421. $groupHasTotal = true;
  2422. }
  2423. }
  2424. }
  2425. unset($byCompany[$cn]['lines_map']);
  2426. $byCompany[$cn]['lines'] = $lines;
  2427. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2428. $byCompany[$cn]['line_count'] = $total;
  2429. $byCompany[$cn]['has_total'] = $total > 0;
  2430. $byCompany[$cn]['has_remark'] = $total > 0;
  2431. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  2432. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2433. // 工序行 + 备注行 + 总计行
  2434. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  2435. }
  2436. return array_values($byCompany);
  2437. }
  2438. /**
  2439. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2440. *
  2441. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2442. * @return array<int, array<string, mixed>>
  2443. */
  2444. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2445. {
  2446. $sids = [];
  2447. $poIdMap = [];
  2448. foreach ($bundle['pos'] ?? [] as $po) {
  2449. if (!is_array($po)) {
  2450. continue;
  2451. }
  2452. $sid = (int)($po['scydgy_id'] ?? 0);
  2453. if ($this->isValidScydgyRowId($sid)) {
  2454. $sids[$sid] = true;
  2455. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2456. }
  2457. }
  2458. if ($sids === []) {
  2459. return [];
  2460. }
  2461. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2462. $gymcMap = [];
  2463. $qtyBySid = [];
  2464. $orderedSids = [];
  2465. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2466. if (!is_array($mr)) {
  2467. continue;
  2468. }
  2469. $gid = $this->extractScydgyRowId($mr);
  2470. if ($this->isValidScydgyRowId($gid)) {
  2471. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2472. $orderedSids[] = $gid;
  2473. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2474. if ($qty === '') {
  2475. $qty = trim((string)($mr['NGZL'] ?? ''));
  2476. }
  2477. $qtyBySid[$gid] = $qty;
  2478. }
  2479. }
  2480. foreach ($bundle['pos'] ?? [] as $po) {
  2481. if (!is_array($po)) {
  2482. continue;
  2483. }
  2484. $gid = (int)($po['scydgy_id'] ?? 0);
  2485. if ($this->isValidScydgyRowId($gid)) {
  2486. $nm = trim((string)($po['CGYMC'] ?? ''));
  2487. if ($nm !== '') {
  2488. $gymcMap[$gid] = $nm;
  2489. }
  2490. }
  2491. }
  2492. try {
  2493. $details = Db::table('purchase_order_detail')
  2494. ->where('scydgy_id', 'in', array_keys($sids))
  2495. ->order('company_name', 'asc')
  2496. ->order('id', 'asc')
  2497. ->select();
  2498. } catch (\Throwable $e) {
  2499. try {
  2500. $details = Db::table('purchase_order_detail')
  2501. ->where('scydgy_id', 'in', array_keys($sids))
  2502. ->order('company_name', 'asc')
  2503. ->order('ID', 'asc')
  2504. ->select();
  2505. } catch (\Throwable $e2) {
  2506. $details = [];
  2507. }
  2508. }
  2509. if (!is_array($details)) {
  2510. $details = [];
  2511. }
  2512. $byCompany = [];
  2513. foreach ($details as $d) {
  2514. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2515. continue;
  2516. }
  2517. $cn = trim((string)($d['company_name'] ?? ''));
  2518. if ($cn === '') {
  2519. continue;
  2520. }
  2521. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2522. $sid = (int)($d['scydgy_id'] ?? 0);
  2523. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2524. continue;
  2525. }
  2526. if (!isset($byCompany[$cn])) {
  2527. $ph = trim((string)($d['phone'] ?? ''));
  2528. $username = trim((string)($d['username'] ?? ''));
  2529. if ($username === '') {
  2530. $username = $this->resolveCustomerContactName($ph, $cn);
  2531. }
  2532. $byCompany[$cn] = [
  2533. 'name' => $cn,
  2534. 'email' => trim((string)($d['email'] ?? '')),
  2535. 'phone' => $ph,
  2536. 'username' => $username,
  2537. 'remark' => '',
  2538. 'pick_lines' => [],
  2539. 'detail_picks' => [],
  2540. ];
  2541. }
  2542. if ($byCompany[$cn]['remark'] === '') {
  2543. $rm = '';
  2544. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2545. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2546. $rm = trim((string)$d[$rk]);
  2547. break;
  2548. }
  2549. }
  2550. if ($rm !== '') {
  2551. $byCompany[$cn]['remark'] = $rm;
  2552. }
  2553. }
  2554. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2555. if ($gymc === '') {
  2556. $gymc = '工序';
  2557. }
  2558. $am = trim((string)($d['amount'] ?? ''));
  2559. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2560. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2561. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2562. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2563. $deliveryShow = $deliveryRaw;
  2564. }
  2565. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2566. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2567. $subtotal = null;
  2568. if ($amountNum !== null) {
  2569. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2570. }
  2571. $unitPriceText = $amountFilled
  2572. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2573. : '未填写';
  2574. $pickLine = [
  2575. 'cgymc' => $gymc,
  2576. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2577. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2578. 'amount_filled' => $amountFilled,
  2579. 'delivery_filled' => $deliveryFilled,
  2580. 'unit_price_text' => $unitPriceText,
  2581. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2582. 'subtotal_num' => $subtotal,
  2583. 'is_quoted' => $amountFilled,
  2584. ];
  2585. if (!$quoteVisible) {
  2586. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2587. }
  2588. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2589. $byCompany[$cn]['detail_picks'][$sid] = [
  2590. 'scydgy_id' => $sid,
  2591. 'detail_id' => $detailId,
  2592. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2593. 'cgymc' => $gymc,
  2594. ];
  2595. }
  2596. $out = [];
  2597. foreach ($byCompany as $g) {
  2598. $pickLinesMap = $g['pick_lines'] ?? [];
  2599. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2600. continue;
  2601. }
  2602. $pickLines = [];
  2603. $usedLineSids = [];
  2604. foreach ($orderedSids as $sid) {
  2605. if (!isset($pickLinesMap[$sid])) {
  2606. continue;
  2607. }
  2608. $pickLines[] = $pickLinesMap[$sid];
  2609. $usedLineSids[$sid] = true;
  2610. }
  2611. foreach ($pickLinesMap as $sid => $ln) {
  2612. if (isset($usedLineSids[$sid])) {
  2613. continue;
  2614. }
  2615. $pickLines[] = $ln;
  2616. }
  2617. $groupTotal = 0.0;
  2618. $groupHasTotal = false;
  2619. if ($quoteVisible) {
  2620. foreach ($pickLines as $ln) {
  2621. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2622. $groupTotal += (float)$ln['subtotal_num'];
  2623. $groupHasTotal = true;
  2624. }
  2625. }
  2626. }
  2627. $lineCount = count($pickLines);
  2628. $g['pick_lines'] = $pickLines;
  2629. $g['line_count'] = $lineCount;
  2630. $g['has_total'] = $lineCount > 0;
  2631. $g['has_remark'] = $lineCount > 0;
  2632. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  2633. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2634. // 工序行 + 备注行 + 总计行
  2635. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  2636. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  2637. $detailPicks = [];
  2638. $usedPickSids = [];
  2639. foreach ($orderedSids as $sid) {
  2640. if (!isset($detailPicksMap[$sid])) {
  2641. continue;
  2642. }
  2643. $detailPicks[] = $detailPicksMap[$sid];
  2644. $usedPickSids[$sid] = true;
  2645. }
  2646. foreach ($detailPicksMap as $sid => $dp) {
  2647. if (isset($usedPickSids[$sid])) {
  2648. continue;
  2649. }
  2650. $detailPicks[] = $dp;
  2651. }
  2652. $g['detail_picks'] = $detailPicks;
  2653. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2654. unset($g['detail_picks']);
  2655. $out[] = $g;
  2656. }
  2657. return $out;
  2658. }
  2659. /**
  2660. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2661. * @return array<int, int[]> scydgy_id => detail_id[]
  2662. */
  2663. protected function mapDetailIdsByScydgyId(array $details): array
  2664. {
  2665. $out = [];
  2666. foreach ($details as $d) {
  2667. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2668. continue;
  2669. }
  2670. $sid = (int)($d['scydgy_id'] ?? 0);
  2671. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2672. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2673. continue;
  2674. }
  2675. if (!isset($out[$sid])) {
  2676. $out[$sid] = [];
  2677. }
  2678. $out[$sid][] = $pk;
  2679. }
  2680. foreach ($out as $sid => $ids) {
  2681. $out[$sid] = array_values(array_unique($ids));
  2682. }
  2683. return $out;
  2684. }
  2685. /**
  2686. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2687. *
  2688. * @param array<string, mixed> $dbRow
  2689. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2690. */
  2691. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2692. {
  2693. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2694. $r = [
  2695. 'ID' => $sid,
  2696. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2697. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2698. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2699. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2700. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2701. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2702. 'CDW' => $dbRow['CDW'] ?? '',
  2703. 'NGZL' => $dbRow['NGZL'] ?? '',
  2704. 'CDF' => $dbRow['CDF'] ?? '',
  2705. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2706. 'MBZ' => $dbRow['MBZ'] ?? '',
  2707. 'bwjg' => $dbRow['bwjg'] ?? '',
  2708. 'iStatus' => $dbRow['iStatus'] ?? '',
  2709. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2710. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2711. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2712. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2713. 'dStamp' => $dbRow['dStamp'] ?? '',
  2714. 'pick_time' => $dbRow['pick_time'] ?? '',
  2715. ];
  2716. if ($sid > 0 && isset($dStampMap[$sid])) {
  2717. $t = trim((string)$dStampMap[$sid]);
  2718. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2719. $r['dStamp'] = $dStampMap[$sid];
  2720. }
  2721. }
  2722. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2723. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2724. $ct = $dbRow['createtime'];
  2725. if (is_numeric($ct) && (int)$ct > 946684800) {
  2726. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2727. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2728. $r['dStamp'] = trim($ct);
  2729. }
  2730. }
  2731. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2732. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2733. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2734. $fallback = trim((string)($r['dStamp'] ?? ''));
  2735. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2736. $r['dputrecord'] = $fallback;
  2737. }
  2738. }
  2739. if (array_key_exists('id', $dbRow)) {
  2740. $r['purchase_order_id'] = (int)$dbRow['id'];
  2741. }
  2742. if ($sid < 0) {
  2743. $r['_is_manual'] = 1;
  2744. }
  2745. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2746. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2747. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2748. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2749. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2750. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2751. $r['pick_time'] = $pickFallback;
  2752. break;
  2753. }
  2754. }
  2755. }
  2756. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2757. if ($pickNm !== '') {
  2758. $r['pick_company_name'] = $pickNm;
  2759. $r['picked_supplier_name'] = $pickNm;
  2760. }
  2761. return $r;
  2762. }
  2763. /**
  2764. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2765. *
  2766. * @return array<int, array<string, mixed>>
  2767. */
  2768. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2769. {
  2770. $pool = [];
  2771. if (!is_array($dbRows) || $dbRows === []) {
  2772. return $pool;
  2773. }
  2774. $dStampMap = [];
  2775. $sidList = [];
  2776. foreach ($dbRows as $tmpRow) {
  2777. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2778. $sid = (int)$tmpRow['scydgy_id'];
  2779. if ($sid > 0) {
  2780. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2781. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2782. $sidList[$sid] = true;
  2783. }
  2784. }
  2785. }
  2786. }
  2787. if ($sidList !== []) {
  2788. try {
  2789. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2790. } catch (\Throwable $e) {
  2791. $dStampMap = [];
  2792. }
  2793. }
  2794. foreach ($dbRows as $dbRow) {
  2795. if (!is_array($dbRow)) {
  2796. continue;
  2797. }
  2798. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2799. }
  2800. return $pool;
  2801. }
  2802. /**
  2803. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2804. *
  2805. * @param int[] $scydgyIds
  2806. * @return array<int, array<string, mixed>>
  2807. */
  2808. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2809. {
  2810. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2811. if ($scydgyIds === []) {
  2812. return [];
  2813. }
  2814. try {
  2815. $list = Db::table('purchase_order_detail')
  2816. ->where('scydgy_id', 'in', $scydgyIds)
  2817. ->field('scydgy_id,company_name,amount,delivery')
  2818. ->select();
  2819. } catch (\Throwable $e) {
  2820. $list = [];
  2821. }
  2822. return is_array($list) ? $list : [];
  2823. }
  2824. /**
  2825. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2826. *
  2827. * @param int[] $scydgyIds
  2828. * @param array<int, array<string, mixed>> $allRows
  2829. * @return array{cnt:int, amt:int, deliv:int}
  2830. */
  2831. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2832. {
  2833. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2834. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2835. if ($scydgyIds === [] || $allRows === []) {
  2836. return $out;
  2837. }
  2838. $idSet = array_flip($scydgyIds);
  2839. $all = [];
  2840. $withAmt = [];
  2841. $withDeliv = [];
  2842. foreach ($allRows as $r) {
  2843. if (!is_array($r)) {
  2844. continue;
  2845. }
  2846. $sid = (int)($r['scydgy_id'] ?? 0);
  2847. if (!isset($idSet[$sid])) {
  2848. continue;
  2849. }
  2850. $cn = trim((string)($r['company_name'] ?? ''));
  2851. if ($cn === '') {
  2852. continue;
  2853. }
  2854. $all[$cn] = true;
  2855. $am = $r['amount'] ?? null;
  2856. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2857. $withAmt[$cn] = true;
  2858. }
  2859. $dv = $r['delivery'] ?? null;
  2860. if ($dv !== null && trim((string)$dv) !== '') {
  2861. $withDeliv[$cn] = true;
  2862. }
  2863. }
  2864. return [
  2865. 'cnt' => count($all),
  2866. 'amt' => count($withAmt),
  2867. 'deliv' => count($withDeliv),
  2868. ];
  2869. }
  2870. /**
  2871. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2872. *
  2873. * @param int[] $scydgyIds
  2874. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2875. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2876. */
  2877. protected function OrderDetailSummary(array $scydgyIds)
  2878. {
  2879. $out = [];
  2880. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2881. if ($scydgyIds === []) {
  2882. return $out;
  2883. }
  2884. $list = [];
  2885. try {
  2886. $list = Db::table('purchase_order_detail')
  2887. ->where('scydgy_id', 'in', $scydgyIds)
  2888. ->field('id,scydgy_id,amount,delivery')
  2889. ->select();
  2890. } catch (\Throwable $e) {
  2891. $list = [];
  2892. }
  2893. if (!is_array($list)) {
  2894. return $out;
  2895. }
  2896. foreach ($list as $r) {
  2897. if (!is_array($r)) {
  2898. continue;
  2899. }
  2900. $ids = (int)($r['scydgy_id'] ?? 0);
  2901. if (!$this->isValidScydgyRowId($ids)) {
  2902. continue;
  2903. }
  2904. if (!isset($out[$ids])) {
  2905. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2906. }
  2907. $out[$ids]['cnt']++;
  2908. $am = $r['amount'] ?? null;
  2909. if ($am !== null && $am !== '') {
  2910. if (!(is_string($am) && trim($am) === '')) {
  2911. $out[$ids]['amt']++;
  2912. }
  2913. }
  2914. $dv = $r['delivery'] ?? null;
  2915. if ($dv !== null && trim((string)$dv) !== '') {
  2916. $out[$ids]['deliv']++;
  2917. }
  2918. }
  2919. return $out;
  2920. }
  2921. /**
  2922. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  2923. *
  2924. * @return array
  2925. */
  2926. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  2927. {
  2928. $strContains = function ($haystack, $needle) {
  2929. if ($needle === '') {
  2930. return false;
  2931. }
  2932. $haystack = (string)$haystack;
  2933. if (function_exists('mb_stripos')) {
  2934. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  2935. }
  2936. return stripos($haystack, $needle) !== false;
  2937. };
  2938. $stripAlias = function ($f) {
  2939. return preg_replace('/^[ab]\./i', '', (string)$f);
  2940. };
  2941. $searchColNames = [];
  2942. foreach (explode(',', $this->searchFields) as $colRaw) {
  2943. $c = $stripAlias(trim($colRaw));
  2944. if ($c !== '') {
  2945. $searchColNames[] = $c;
  2946. }
  2947. }
  2948. $filtered = [];
  2949. foreach ($pool as $r) {
  2950. if (!is_array($r)) {
  2951. continue;
  2952. }
  2953. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  2954. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  2955. if (!$isManual) {
  2956. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  2957. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  2958. continue;
  2959. }
  2960. if ($applyMonthRange) {
  2961. $mo = (int)$m[2];
  2962. if ($mo < 1 || $mo > 12) {
  2963. continue;
  2964. }
  2965. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2966. $rowMonthStart = $ymRow . '-01 00:00:00';
  2967. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2968. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2969. continue;
  2970. }
  2971. }
  2972. } elseif ($applyMonthRange) {
  2973. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  2974. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2975. $ds = $listTime;
  2976. }
  2977. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  2978. continue;
  2979. }
  2980. $mo = (int)$m[2];
  2981. if ($mo < 1 || $mo > 12) {
  2982. continue;
  2983. }
  2984. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2985. $rowMonthStart = $ymRow . '-01 00:00:00';
  2986. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2987. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2988. continue;
  2989. }
  2990. }
  2991. if ($search !== '') {
  2992. $hitSearch = false;
  2993. foreach ($searchColNames as $c) {
  2994. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  2995. if ($cell !== '' && $strContains($cell, $search)) {
  2996. $hitSearch = true;
  2997. break;
  2998. }
  2999. }
  3000. if (!$hitSearch) {
  3001. continue;
  3002. }
  3003. }
  3004. foreach ($filterArr as $fk => $fv) {
  3005. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  3006. continue;
  3007. }
  3008. if (is_array($fv)) {
  3009. continue;
  3010. }
  3011. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  3012. continue;
  3013. }
  3014. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  3015. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  3016. $field = $stripAlias($fk);
  3017. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  3018. $cellStr = trim((string)$cell);
  3019. switch ($sym) {
  3020. case '=':
  3021. if ((string)$cell !== (string)$fv) {
  3022. continue 3;
  3023. }
  3024. break;
  3025. case '<>':
  3026. if ((string)$cell === (string)$fv) {
  3027. continue 3;
  3028. }
  3029. break;
  3030. case 'LIKE':
  3031. case 'NOT LIKE':
  3032. $needle = trim((string)$fv);
  3033. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  3034. if ($sym === 'LIKE' && !$hit) {
  3035. continue 3;
  3036. }
  3037. if ($sym === 'NOT LIKE' && $hit) {
  3038. continue 3;
  3039. }
  3040. break;
  3041. case '>':
  3042. case '>=':
  3043. case '<':
  3044. case '<=':
  3045. if (!is_numeric($cell) && $cellStr === '') {
  3046. continue 3;
  3047. }
  3048. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  3049. $vv = (float)$fv;
  3050. if ($sym === '>' && !($cv > $vv)) {
  3051. continue 3;
  3052. }
  3053. if ($sym === '>=' && !($cv >= $vv)) {
  3054. continue 3;
  3055. }
  3056. if ($sym === '<' && !($cv < $vv)) {
  3057. continue 3;
  3058. }
  3059. if ($sym === '<=' && !($cv <= $vv)) {
  3060. continue 3;
  3061. }
  3062. break;
  3063. case 'RANGE':
  3064. case 'NOT RANGE':
  3065. case 'BETWEEN':
  3066. case 'NOT BETWEEN':
  3067. case 'BETWEEN TIME':
  3068. case 'NOT BETWEEN TIME':
  3069. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  3070. $rawR = str_replace(' - ', ',', $rawR);
  3071. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  3072. if (count($arr) < 2) {
  3073. break;
  3074. }
  3075. $lo = $arr[0];
  3076. $hi = $arr[1];
  3077. if ($lo === '' && $hi === '') {
  3078. break;
  3079. }
  3080. $isNot = (strpos($sym, 'NOT') !== false);
  3081. if ($lo === '') {
  3082. $in = ($cellStr !== '' && $cellStr <= $hi);
  3083. if ($isNot ? $in : !$in) {
  3084. continue 3;
  3085. }
  3086. break;
  3087. }
  3088. if ($hi === '') {
  3089. $in = ($cellStr !== '' && $cellStr >= $lo);
  3090. if ($isNot ? $in : !$in) {
  3091. continue 3;
  3092. }
  3093. break;
  3094. }
  3095. $in = ($cellStr >= $lo && $cellStr <= $hi);
  3096. if ($isNot ? $in : !$in) {
  3097. continue 3;
  3098. }
  3099. break;
  3100. case 'NULL':
  3101. case 'IS NULL':
  3102. if ($cell !== null && $cell !== '') {
  3103. continue 3;
  3104. }
  3105. break;
  3106. case 'NOT NULL':
  3107. case 'IS NOT NULL':
  3108. if ($cell === null || $cell === '') {
  3109. continue 3;
  3110. }
  3111. break;
  3112. default:
  3113. break;
  3114. }
  3115. }
  3116. $filtered[] = $r;
  3117. }
  3118. return $filtered;
  3119. }
  3120. /**
  3121. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  3122. */
  3123. public function snapshotToProcure()
  3124. {
  3125. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3126. $this->error(__('Invalid parameters'));
  3127. }
  3128. $row = json_decode($this->request->post('row_json', ''), true);
  3129. if (!is_array($row)) {
  3130. $this->error(__('Invalid parameters'));
  3131. }
  3132. try {
  3133. $ids = $this->extractScydgyRowId($row);
  3134. if (!$this->isValidScydgyRowId($ids)) {
  3135. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3136. }
  3137. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3138. $data = [
  3139. 'scydgy_id' => $ids,
  3140. 'CCYDH' => $row['CCYDH'] ?? null,
  3141. 'CYJMC' => $row['CYJMC'] ?? null,
  3142. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3143. 'CDXMC' => $row['CDXMC'] ?? null,
  3144. 'CGYBH' => $row['CGYBH'] ?? null,
  3145. 'CGYMC' => $row['CGYMC'] ?? null,
  3146. 'CDW' => $row['CDW'] ?? null,
  3147. 'NGZL' => $row['NGZL'] ?? null,
  3148. 'CDF' => $row['CDF'] ?? null,
  3149. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3150. 'MBZ' => $row['MBZ'] ?? null,
  3151. 'bwjg' => $row['bwjg'] ?? null,
  3152. 'iStatus' => $row['iStatus'] ?? null,
  3153. 'dStamp' => $row['dStamp'] ?? null,
  3154. 'dputrecord' => $row['dputrecord'] ?? null,
  3155. 'cywyxm' => $row['cywyxm'] ?? null,
  3156. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3157. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3158. ];
  3159. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3160. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3161. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3162. $this->success('操作成功');
  3163. return;
  3164. }
  3165. if ($exists) {
  3166. $upd = $data;
  3167. unset($upd['scydgy_id'], $upd['status']);
  3168. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3169. } else {
  3170. // 新增:不写 status(空/走库默认);仅写创建时间
  3171. $data['createtime'] = date('Y-m-d H:i:s');
  3172. Db::table('purchase_order')->insert($data);
  3173. }
  3174. } catch (\Throwable $e) {
  3175. $this->error($e->getMessage());
  3176. }
  3177. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3178. $this->success('操作成功');
  3179. }
  3180. /**
  3181. * 未发列表
  3182. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3183. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3184. */
  3185. public function completeDirectly()
  3186. {
  3187. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3188. $this->error(__('参数错误'));
  3189. }
  3190. if (!$this->procuremenCanComplete()) {
  3191. $this->error(__('You have no permission'));
  3192. }
  3193. $row = json_decode($this->request->post('row_json', ''), true);
  3194. if (!is_array($row)) {
  3195. $this->error(__('Invalid parameters'));
  3196. }
  3197. $finishRaw = $this->request->post('finish', '1');
  3198. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3199. $poIdLog = null;
  3200. try {
  3201. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3202. $ids = $this->extractScydgyRowId($row);
  3203. if (!$this->isValidScydgyRowId($ids)) {
  3204. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3205. }
  3206. if ($asComplete) {
  3207. $this->assertPickRowCanComplete($ids, $row);
  3208. }
  3209. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3210. $data = [
  3211. 'scydgy_id' => $ids,
  3212. 'CCYDH' => $row['CCYDH'] ?? null,
  3213. 'CYJMC' => $row['CYJMC'] ?? null,
  3214. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3215. 'CDXMC' => $row['CDXMC'] ?? null,
  3216. 'CGYBH' => $row['CGYBH'] ?? null,
  3217. 'CGYMC' => $row['CGYMC'] ?? null,
  3218. 'CDW' => $row['CDW'] ?? null,
  3219. 'NGZL' => $row['NGZL'] ?? null,
  3220. 'CDF' => $row['CDF'] ?? null,
  3221. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3222. 'MBZ' => $row['MBZ'] ?? null,
  3223. 'bwjg' => $row['bwjg'] ?? null,
  3224. 'iStatus' => $row['iStatus'] ?? null,
  3225. 'dStamp' => $row['dStamp'] ?? null,
  3226. 'dputrecord' => $row['dputrecord'] ?? null,
  3227. 'cywyxm' => $row['cywyxm'] ?? null,
  3228. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3229. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3230. ];
  3231. if ($asComplete) {
  3232. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3233. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3234. }
  3235. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3236. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3237. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3238. $this->success('操作成功');
  3239. return;
  3240. }
  3241. if ($exists) {
  3242. $upd = $data;
  3243. unset($upd['scydgy_id']);
  3244. if (!$asComplete) {
  3245. unset($upd['status']);
  3246. }
  3247. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3248. } else {
  3249. // 新增:不写 status;完结时 $data 已含 status=1
  3250. $data['createtime'] = date('Y-m-d H:i:s');
  3251. Db::table('purchase_order')->insert($data);
  3252. }
  3253. } catch (\Throwable $e) {
  3254. $this->error($e->getMessage());
  3255. }
  3256. try {
  3257. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3258. if (is_array($rpo)) {
  3259. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3260. $poIdLog = $tid > 0 ? $tid : null;
  3261. }
  3262. } catch (\Throwable $e) {
  3263. $poIdLog = null;
  3264. }
  3265. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3266. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3267. if ($asComplete) {
  3268. $this->addOrderLog(
  3269. $ids,
  3270. 'mark_complete',
  3271. '点击「完结」,已标记为已完结',
  3272. $poIdLog
  3273. );
  3274. try {
  3275. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3276. if ($pdfPublicPath === '') {
  3277. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3278. }
  3279. } catch (\Throwable $e) {
  3280. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3281. }
  3282. } else {
  3283. $this->addOrderLog(
  3284. $ids,
  3285. 'save_qty_price',
  3286. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3287. $poIdLog
  3288. );
  3289. }
  3290. $this->pickHiddenScydgySetCache = null;
  3291. $this->success("操作成功");
  3292. }
  3293. /**
  3294. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3295. *
  3296. * @param array<int, array> $rows 引用传递当前页行
  3297. */
  3298. protected function mergePurchaseOrder(array &$rows)
  3299. {
  3300. if ($rows === []) {
  3301. return;
  3302. }
  3303. $ids = [];
  3304. foreach ($rows as $rw) {
  3305. if (!is_array($rw)) {
  3306. continue;
  3307. }
  3308. $id = (int)($rw['ID'] ?? 0);
  3309. if ($id > 0) {
  3310. $ids[$id] = true;
  3311. }
  3312. }
  3313. $idList = array_keys($ids);
  3314. if ($idList === []) {
  3315. return;
  3316. }
  3317. try {
  3318. $list = Db::table('purchase_order')
  3319. ->where('scydgy_id', 'in', $idList)
  3320. ->field('scydgy_id,This_quantity,ceilingPrice')
  3321. ->select();
  3322. } catch (\Throwable $e) {
  3323. return;
  3324. }
  3325. if (!is_array($list)) {
  3326. return;
  3327. }
  3328. $byId = [];
  3329. foreach ($list as $dbRow) {
  3330. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3331. continue;
  3332. }
  3333. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3334. }
  3335. foreach ($rows as &$rw) {
  3336. if (!is_array($rw)) {
  3337. continue;
  3338. }
  3339. $sid = (int)($rw['ID'] ?? 0);
  3340. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3341. continue;
  3342. }
  3343. $db = $byId[$sid];
  3344. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  3345. if (array_key_exists('This_quantity', $db)) {
  3346. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  3347. }
  3348. if (array_key_exists('ceilingPrice', $db)) {
  3349. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  3350. } elseif (array_key_exists('ceiling_price', $db)) {
  3351. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  3352. }
  3353. }
  3354. unset($rw);
  3355. }
  3356. /**
  3357. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3358. */
  3359. public function purchaseConfirmPick()
  3360. {
  3361. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3362. $this->error(__('Invalid parameters'));
  3363. }
  3364. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3365. $this->error(__('You have no permission'));
  3366. }
  3367. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3368. if ($batchRaw !== '') {
  3369. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3370. return;
  3371. }
  3372. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3373. $sid = (int)$scydgyId;
  3374. if (!$this->isValidScydgyRowId($sid)) {
  3375. $this->error('参数无效');
  3376. }
  3377. $parseIdList = function ($raw) {
  3378. if (is_array($raw)) {
  3379. $arr = $raw;
  3380. } else {
  3381. $decoded = json_decode((string)$raw, true);
  3382. $arr = is_array($decoded) ? $decoded : [];
  3383. }
  3384. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3385. };
  3386. $selectedRaw = $this->request->post('selected_ids', null);
  3387. if ($selectedRaw === null || $selectedRaw === '') {
  3388. $legacy = (int)$this->request->post('selected_id', 0);
  3389. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3390. } else {
  3391. $selectedIds = $parseIdList($selectedRaw);
  3392. }
  3393. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3394. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3395. try {
  3396. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3397. } catch (\InvalidArgumentException $e) {
  3398. $this->error($e->getMessage());
  3399. } catch (\Throwable $e) {
  3400. $this->error($e->getMessage());
  3401. }
  3402. $this->pickHiddenScydgySetCache = null;
  3403. $this->success('操作成功', '', $result);
  3404. }
  3405. /**
  3406. * 整单采购确认(多道工序一次提交)
  3407. */
  3408. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3409. {
  3410. $decoded = json_decode($batchRaw, true);
  3411. if (!is_array($decoded) || $decoded === []) {
  3412. $this->error('提交数据无效');
  3413. }
  3414. $picks = [];
  3415. foreach ($decoded as $item) {
  3416. if (!is_array($item)) {
  3417. continue;
  3418. }
  3419. $sid = (int)($item['scydgy_id'] ?? 0);
  3420. if (!$this->isValidScydgyRowId($sid)) {
  3421. continue;
  3422. }
  3423. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3424. if (!is_array($sel)) {
  3425. $sel = [(int)$sel];
  3426. }
  3427. $unsel = $item['unselected_ids'] ?? [];
  3428. if (!is_array($unsel)) {
  3429. $unsel = json_decode((string)$unsel, true);
  3430. $unsel = is_array($unsel) ? $unsel : [];
  3431. }
  3432. $picks[] = [
  3433. 'scydgy_id' => $sid,
  3434. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3435. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3436. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3437. ];
  3438. }
  3439. if ($picks === []) {
  3440. $this->error('提交数据无效');
  3441. }
  3442. Db::startTrans();
  3443. $results = [];
  3444. try {
  3445. foreach ($picks as $pick) {
  3446. $results[] = $this->runPurchaseConfirmPick(
  3447. (int)$pick['scydgy_id'],
  3448. $pick['selected_ids'],
  3449. $pick['unselected_ids'],
  3450. (int)$pick['purchase_order_id'],
  3451. false,
  3452. false
  3453. );
  3454. }
  3455. Db::commit();
  3456. } catch (\Throwable $e) {
  3457. Db::rollback();
  3458. $msg = $e->getMessage();
  3459. $this->error($msg !== '' ? $msg : '提交失败');
  3460. }
  3461. try {
  3462. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3463. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3464. } catch (\Throwable $e) {
  3465. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3466. }
  3467. $this->pickHiddenScydgySetCache = null;
  3468. $this->success('操作成功', '', ['batch' => $results]);
  3469. }
  3470. /**
  3471. * @return array<string, mixed>
  3472. */
  3473. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3474. {
  3475. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3476. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3477. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3478. $scydgyId = (string)$sid;
  3479. if ($selectedIds === []) {
  3480. throw new \InvalidArgumentException('请至少勾选一条明细');
  3481. }
  3482. $inter = array_intersect($selectedIds, $unselectedIds);
  3483. if ($inter !== []) {
  3484. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3485. }
  3486. $allIds = $this->purchaseOrderDetail($sid);
  3487. if ($allIds === []) {
  3488. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3489. }
  3490. foreach ($selectedIds as $id) {
  3491. if (!in_array($id, $allIds, true)) {
  3492. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3493. }
  3494. }
  3495. foreach ($unselectedIds as $id) {
  3496. if (!in_array($id, $allIds, true)) {
  3497. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3498. }
  3499. }
  3500. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3501. sort($union, SORT_NUMERIC);
  3502. $expect = $allIds;
  3503. sort($expect, SORT_NUMERIC);
  3504. if ($union !== $expect) {
  3505. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3506. }
  3507. if ($manageTransaction) {
  3508. Db::startTrans();
  3509. }
  3510. try {
  3511. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3512. $aff = 0;
  3513. try {
  3514. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3515. } catch (\Throwable $e) {
  3516. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3517. }
  3518. if ($aff < 1) {
  3519. throw new \Exception('更新选中状态失败');
  3520. }
  3521. $poPayload = [
  3522. 'status' => ProcuremenStatus::PO_COMPLETED,
  3523. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3524. ];
  3525. if ($purchaseOrderId > 0) {
  3526. $poAff = (int)Db::table('purchase_order')
  3527. ->where('id', $purchaseOrderId)
  3528. ->where('scydgy_id', $sid)
  3529. ->update($poPayload);
  3530. if ($poAff < 1) {
  3531. throw new \Exception('主表订单不存在或与工序行不匹配');
  3532. }
  3533. } else {
  3534. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3535. if ($poAff < 1) {
  3536. throw new \Exception('未找到');
  3537. }
  3538. }
  3539. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3540. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3541. if ($manageTransaction) {
  3542. Db::commit();
  3543. }
  3544. } catch (\Throwable $e) {
  3545. if ($manageTransaction) {
  3546. Db::rollback();
  3547. }
  3548. throw $e;
  3549. }
  3550. $poIdFinal = $purchaseOrderId;
  3551. if ($poIdFinal <= 0) {
  3552. try {
  3553. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3554. if (is_array($rpo)) {
  3555. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3556. }
  3557. } catch (\Throwable $e) {
  3558. $poIdFinal = 0;
  3559. }
  3560. }
  3561. $pickNames = [];
  3562. foreach ($selectedIds as $pid) {
  3563. $dr = $this->purchaseOrderDetai($sid, $pid);
  3564. $nm = trim((string)($dr['company_name'] ?? ''));
  3565. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3566. }
  3567. $this->addOrderLog(
  3568. $sid,
  3569. 'purchase_confirm',
  3570. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3571. $poIdFinal > 0 ? $poIdFinal : null
  3572. );
  3573. if ($sendNotifications) {
  3574. try {
  3575. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3576. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3577. 'scydgy_id' => $sid,
  3578. 'selected_ids' => $selectedIds,
  3579. 'unselected_ids' => $unselectedIds,
  3580. 'purchase_order_id' => $purchaseOrderId,
  3581. ]]);
  3582. } catch (\Throwable $e) {
  3583. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3584. }
  3585. }
  3586. Log::write(sprintf(
  3587. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3588. $scydgyId,
  3589. $purchaseOrderId,
  3590. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3591. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3592. ), 'notice');
  3593. $pdfPublicPath = '';
  3594. try {
  3595. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3596. } catch (\Throwable $e) {
  3597. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3598. }
  3599. return [
  3600. 'scydgy_id' => $scydgyId,
  3601. 'purchase_order_id' => $purchaseOrderId,
  3602. 'selected_ids' => $selectedIds,
  3603. 'unselected_ids' => $unselectedIds,
  3604. 'purchase_confirm_pdf' => $pdfPublicPath,
  3605. ];
  3606. }
  3607. /**
  3608. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3609. *
  3610. * @param int[]|string[] $scydgyIds
  3611. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3612. */
  3613. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3614. {
  3615. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3616. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3617. if ($scydgyIds === []) {
  3618. return $empty;
  3619. }
  3620. $pos = [];
  3621. try {
  3622. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3623. } catch (\Throwable $e) {
  3624. $rows = [];
  3625. }
  3626. if (is_array($rows)) {
  3627. foreach ($rows as $po) {
  3628. if (is_array($po)) {
  3629. $pos[] = $po;
  3630. }
  3631. }
  3632. }
  3633. if ($pos === []) {
  3634. return $empty;
  3635. }
  3636. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3637. return [
  3638. 'ccydh' => $ccydh,
  3639. 'pos' => $pos,
  3640. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3641. ];
  3642. }
  3643. /**
  3644. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3645. *
  3646. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3647. * @param array<int, array<string, mixed>> $picks
  3648. */
  3649. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3650. {
  3651. if ($picks === []) {
  3652. return;
  3653. }
  3654. $fallbackDetailId = 0;
  3655. $winners = [];
  3656. $losers = [];
  3657. foreach ($picks as $pick) {
  3658. if (!is_array($pick)) {
  3659. continue;
  3660. }
  3661. $sid = (int)($pick['scydgy_id'] ?? 0);
  3662. if (!$this->isValidScydgyRowId($sid)) {
  3663. continue;
  3664. }
  3665. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3666. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3667. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3668. $fallbackDetailId = (int)$selectedIds[0];
  3669. }
  3670. foreach ($selectedIds as $pid) {
  3671. $dr = $this->purchaseOrderDetai($sid, $pid);
  3672. if (!is_array($dr)) {
  3673. continue;
  3674. }
  3675. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3676. }
  3677. foreach ($unselectedIds as $pid) {
  3678. $dr = $this->purchaseOrderDetai($sid, $pid);
  3679. if (!is_array($dr)) {
  3680. continue;
  3681. }
  3682. $key = $this->notifySupplierDedupeKey($dr);
  3683. if (!isset($winners[$key])) {
  3684. $losers[$key] = $dr;
  3685. }
  3686. }
  3687. }
  3688. if ($winners === [] && $losers === []) {
  3689. return;
  3690. }
  3691. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3692. $sendSmsSafe = function ($phone, $content) {
  3693. $phone = trim((string)$phone);
  3694. if ($phone === '') {
  3695. return;
  3696. }
  3697. try {
  3698. $this->smsbao($phone, $content);
  3699. } catch (\Throwable $e) {
  3700. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3701. }
  3702. };
  3703. foreach ($winners as $dr) {
  3704. $cname = trim((string)($dr['company_name'] ?? ''));
  3705. $ph = trim((string)($dr['phone'] ?? ''));
  3706. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3707. 'company_name' => $cname,
  3708. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3709. 'phone' => $ph,
  3710. ]));
  3711. $sendSmsSafe($ph, $sms);
  3712. }
  3713. foreach ($losers as $dr) {
  3714. $cname = trim((string)($dr['company_name'] ?? ''));
  3715. $ph = trim((string)($dr['phone'] ?? ''));
  3716. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3717. 'company_name' => $cname,
  3718. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3719. 'phone' => $ph,
  3720. ]));
  3721. $sendSmsSafe($ph, $sms);
  3722. }
  3723. }
  3724. /**
  3725. * 短信去重键:优先手机号,否则公司名
  3726. */
  3727. protected function notifySupplierDedupeKey(array $detailRow): string
  3728. {
  3729. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  3730. if ($ph !== '') {
  3731. return 'p:' . $ph;
  3732. }
  3733. $cn = trim((string)($detailRow['company_name'] ?? ''));
  3734. return 'c:' . $cn;
  3735. }
  3736. /**
  3737. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3738. *
  3739. * @param int[] $detailIds
  3740. */
  3741. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3742. {
  3743. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3744. if ($detailIds === []) {
  3745. return;
  3746. }
  3747. $payload = ['status_name' => $statusName];
  3748. try {
  3749. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3750. } catch (\Throwable $e) {
  3751. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3752. }
  3753. }
  3754. /**
  3755. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3756. */
  3757. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3758. {
  3759. try {
  3760. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3761. } catch (\Throwable $e) {
  3762. return;
  3763. }
  3764. if (!is_array($rows)) {
  3765. return;
  3766. }
  3767. foreach ($rows as $dr) {
  3768. if (!is_array($dr)) {
  3769. continue;
  3770. }
  3771. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3772. if ($id <= 0) {
  3773. continue;
  3774. }
  3775. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3776. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3777. try {
  3778. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3779. } catch (\Throwable $e) {
  3780. }
  3781. }
  3782. }
  3783. /**
  3784. * @param array<string, mixed> $detailRow
  3785. */
  3786. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3787. {
  3788. $am = $detailRow['amount'] ?? null;
  3789. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3790. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3791. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3792. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3793. }
  3794. /**
  3795. * @return int[]
  3796. */
  3797. protected function purchaseOrderDetail(int $scydgyId): array
  3798. {
  3799. if (!$this->isValidScydgyRowId($scydgyId)) {
  3800. return [];
  3801. }
  3802. try {
  3803. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3804. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3805. $list = $listQuery->select();
  3806. } catch (\Throwable $e) {
  3807. return [];
  3808. }
  3809. if (!is_array($list)) {
  3810. return [];
  3811. }
  3812. $ids = [];
  3813. foreach ($list as $r) {
  3814. if (!is_array($r)) {
  3815. continue;
  3816. }
  3817. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3818. if ($pk > 0) {
  3819. $ids[] = $pk;
  3820. }
  3821. }
  3822. return array_values(array_unique($ids));
  3823. }
  3824. /**
  3825. * 获取当前登录用户信息 [id, 展示名]
  3826. */
  3827. protected function GetUseName(): array
  3828. {
  3829. $id = 0;
  3830. $name = '';
  3831. try {
  3832. if ($this->auth && $this->auth->isLogin()) {
  3833. $u = $this->auth->getUserInfo();
  3834. if (is_array($u)) {
  3835. $id = (int)($u['id'] ?? 0);
  3836. $name = trim((string)($u['nickname'] ?? ''));
  3837. if ($name === '') {
  3838. $name = trim((string)($u['username'] ?? ''));
  3839. }
  3840. }
  3841. }
  3842. } catch (\Throwable $e) {
  3843. }
  3844. if ($name === '') {
  3845. $name = '未知用户';
  3846. }
  3847. return [$id, $name];
  3848. }
  3849. /**
  3850. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3851. */
  3852. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3853. {
  3854. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3855. }
  3856. /**
  3857. * 按主键取一条
  3858. */
  3859. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3860. {
  3861. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3862. return [];
  3863. }
  3864. try {
  3865. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3866. if (is_array($one)) {
  3867. return $one;
  3868. }
  3869. } catch (\Throwable $e) {
  3870. }
  3871. try {
  3872. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3873. if (is_array($one)) {
  3874. return $one;
  3875. }
  3876. } catch (\Throwable $e) {
  3877. }
  3878. return [];
  3879. }
  3880. /**
  3881. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3882. */
  3883. protected function formatProcuremenDetailTime($v): string
  3884. {
  3885. if ($v === null || $v === '') {
  3886. return '';
  3887. }
  3888. if (is_numeric($v) && (int)$v > 946684800) {
  3889. return date('Y-m-d H:i:s', (int)$v);
  3890. }
  3891. return ProcuremenTime::formatDisplayDateTime($v);
  3892. }
  3893. /**
  3894. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3895. */
  3896. protected function formatDeliveryYmd($v): string
  3897. {
  3898. if ($v === null || $v === '') {
  3899. return '';
  3900. }
  3901. $s = trim((string)$v);
  3902. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3903. return '';
  3904. }
  3905. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  3906. return $m[1];
  3907. }
  3908. $ts = strtotime($s);
  3909. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  3910. }
  3911. /**
  3912. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  3913. */
  3914. protected function detailRowSupplierOperated(array $r): bool
  3915. {
  3916. $am = $r['amount'] ?? null;
  3917. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3918. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3919. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3920. return $okAmt || $okDel;
  3921. }
  3922. /**
  3923. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  3924. */
  3925. protected function resolveDetailSupplierOperTime(array $r): string
  3926. {
  3927. if (!$this->detailRowSupplierOperated($r)) {
  3928. return '';
  3929. }
  3930. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  3931. if ($t !== '') {
  3932. return $t;
  3933. }
  3934. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  3935. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  3936. continue;
  3937. }
  3938. $t = $this->formatProcuremenDetailTime($r[$col]);
  3939. if ($t !== '') {
  3940. return $t;
  3941. }
  3942. }
  3943. return '';
  3944. }
  3945. /**
  3946. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  3947. */
  3948. protected function detailRowSupplierAccepted(array $r): bool
  3949. {
  3950. $am = $r['amount'] ?? null;
  3951. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3952. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3953. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3954. return $okAmt && $okDel;
  3955. }
  3956. /**
  3957. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  3958. */
  3959. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  3960. {
  3961. if ($detailCount > 0) {
  3962. return true;
  3963. }
  3964. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  3965. return true;
  3966. }
  3967. $pickTime = trim((string)($main['pick_time'] ?? ''));
  3968. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  3969. return true;
  3970. }
  3971. return false;
  3972. }
  3973. /**
  3974. * 下发时间:优先 pick_time,其次首条下发明细时间
  3975. */
  3976. protected function resolveProcuremenIssueTime(array $main, array $details): string
  3977. {
  3978. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  3979. if ($issueTime !== '') {
  3980. return $issueTime;
  3981. }
  3982. foreach ($details as $dr) {
  3983. if (!is_array($dr)) {
  3984. continue;
  3985. }
  3986. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3987. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  3988. $issueTime = $t;
  3989. }
  3990. }
  3991. if ($issueTime !== '') {
  3992. return $issueTime;
  3993. }
  3994. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3995. }
  3996. /**
  3997. * 直接点「完结」时间:优先操作记录 mark_complete
  3998. */
  3999. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  4000. {
  4001. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  4002. }
  4003. /**
  4004. * 操作记录时间(取指定 action 最近一条)
  4005. *
  4006. * @param string|array<int, string> $actions
  4007. */
  4008. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  4009. {
  4010. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  4011. }
  4012. /**
  4013. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  4014. *
  4015. * @param array $main purchase_order 一行
  4016. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  4017. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  4018. */
  4019. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  4020. {
  4021. $issueCnt = count($details);
  4022. $acceptCnt = 0;
  4023. $pickedName = '';
  4024. $pickedTime = '';
  4025. foreach ($details as $dr) {
  4026. if (!is_array($dr)) {
  4027. continue;
  4028. }
  4029. if ($this->detailRowSupplierAccepted($dr)) {
  4030. $acceptCnt++;
  4031. }
  4032. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4033. if ($pickedName === '') {
  4034. $pickedName = trim((string)($dr['company_name'] ?? ''));
  4035. }
  4036. if ($pickedTime === '') {
  4037. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  4038. if ($pickedTime === '') {
  4039. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4040. }
  4041. }
  4042. }
  4043. }
  4044. $hasMain = $main !== [];
  4045. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  4046. if ($poTime === '') {
  4047. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  4048. }
  4049. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  4050. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  4051. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  4052. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  4053. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  4054. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  4055. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  4056. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  4057. $supplierTime = '';
  4058. if ($acceptCnt > 0) {
  4059. foreach ($details as $dr) {
  4060. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  4061. continue;
  4062. }
  4063. $t = $this->resolveDetailSupplierOperTime($dr);
  4064. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  4065. $supplierTime = $t;
  4066. }
  4067. }
  4068. }
  4069. $directComplete = ($mainCompleted && !$issued);
  4070. $doneTime = '';
  4071. if ($mainCompleted) {
  4072. if ($directComplete) {
  4073. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  4074. }
  4075. if ($doneTime === '') {
  4076. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4077. }
  4078. if ($doneTime === '') {
  4079. foreach ($details as $dr) {
  4080. if (!is_array($dr)) {
  4081. continue;
  4082. }
  4083. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  4084. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  4085. $doneTime = $t;
  4086. }
  4087. }
  4088. }
  4089. if ($doneTime === '') {
  4090. $doneTime = $poTime;
  4091. }
  4092. if ($confirmApproveTime !== '') {
  4093. $doneTime = $confirmApproveTime;
  4094. }
  4095. }
  4096. if ($directComplete) {
  4097. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  4098. $step1Done = $hasMain;
  4099. $step2Done = false;
  4100. $step3Done = false;
  4101. $step4Done = false;
  4102. $step5Done = false;
  4103. $step6Done = true;
  4104. } else {
  4105. $step1Done = $issued;
  4106. $step2Done = $issued;
  4107. $step3Done = $acceptCnt > 0;
  4108. $step4Done = $wflowPendingApproval;
  4109. if (!$step4Done) {
  4110. foreach ($details as $dr) {
  4111. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4112. $step4Done = true;
  4113. break;
  4114. }
  4115. }
  4116. }
  4117. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  4118. $step6Done = $mainCompleted;
  4119. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  4120. if ($mainCompleted && $issued) {
  4121. $step3Done = true;
  4122. $step4Done = true;
  4123. $step5Done = true;
  4124. if ($supplierTime === '') {
  4125. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4126. if ($fillT !== '') {
  4127. $supplierTime = $fillT;
  4128. }
  4129. }
  4130. if ($pickedTime === '') {
  4131. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4132. if ($fillT !== '') {
  4133. $pickedTime = $fillT;
  4134. }
  4135. }
  4136. if ($auditSelectTime === '') {
  4137. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4138. if ($fillT !== '') {
  4139. $auditSelectTime = $fillT;
  4140. }
  4141. }
  4142. if ($confirmApproveTime === '') {
  4143. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4144. if ($fillT !== '') {
  4145. $confirmApproveTime = $fillT;
  4146. }
  4147. }
  4148. }
  4149. }
  4150. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4151. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4152. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4153. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4154. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4155. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4156. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4157. $deadlineText = '';
  4158. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  4159. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  4160. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  4161. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  4162. $deadlineText = '截止 ' . $deadlineDisp;
  4163. }
  4164. }
  4165. $steps = [
  4166. [
  4167. 'title' => '未发',
  4168. 'subtitle' => '',
  4169. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  4170. 'done' => $step1Done,
  4171. ],
  4172. [
  4173. 'title' => '下发',
  4174. 'subtitle' => $deadlineText,
  4175. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  4176. 'done' => $step2Done,
  4177. ],
  4178. [
  4179. 'title' => '供应商接单',
  4180. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4181. 'time' => '',
  4182. 'done' => $step3Done,
  4183. ],
  4184. [
  4185. 'title' => '待确认',
  4186. 'subtitle' => $step4Done
  4187. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4188. : ($issued ? '待选供应商' : ''),
  4189. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  4190. 'done' => $step4Done,
  4191. ],
  4192. [
  4193. 'title' => '待审批',
  4194. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4195. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  4196. 'done' => $step5Done,
  4197. ],
  4198. [
  4199. 'title' => '已完结',
  4200. 'subtitle' => '',
  4201. 'time' => $step6Done ? $doneTime : '',
  4202. 'done' => $step6Done,
  4203. ],
  4204. ];
  4205. $currentIdx = count($steps) - 1;
  4206. if (!$directComplete) {
  4207. foreach ($steps as $i => $s) {
  4208. if (!$s['done']) {
  4209. $currentIdx = $i;
  4210. break;
  4211. }
  4212. }
  4213. }
  4214. $nSteps = count($steps);
  4215. foreach ($steps as $idx => &$s) {
  4216. $s['current'] = ($idx === $currentIdx);
  4217. if ($idx === 0) {
  4218. $s['pdf_left_bg'] = '';
  4219. } else {
  4220. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4221. }
  4222. if ($idx >= $nSteps - 1) {
  4223. $s['pdf_right_bg'] = '';
  4224. } else {
  4225. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4226. }
  4227. }
  4228. unset($s);
  4229. $labelMap = [
  4230. 'CCYDH' => '订单号',
  4231. 'CYJMC' => '印件名称',
  4232. 'CCLBMMC' => '承揽部门',
  4233. 'CGYMC' => '工序名称',
  4234. 'CDW' => '单位',
  4235. 'NGZL' => '工作量',
  4236. 'CDF' => '单价',
  4237. 'cGzzxMc' => '工作中心',
  4238. 'MBZ' => '备注',
  4239. 'This_quantity' => '本次数量',
  4240. 'ceilingPrice' => '最高限价',
  4241. ];
  4242. $orderSummary = [];
  4243. foreach ($labelMap as $key => $lab) {
  4244. if (!array_key_exists($key, $main)) {
  4245. continue;
  4246. }
  4247. $val = $main[$key];
  4248. if ($val === null) {
  4249. $val = '';
  4250. } elseif (!is_scalar($val)) {
  4251. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4252. } else {
  4253. $val = (string)$val;
  4254. }
  4255. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4256. }
  4257. $orderSummaryGrid = [];
  4258. $n = count($orderSummary);
  4259. for ($i = 0; $i < $n; $i += 2) {
  4260. $left = $orderSummary[$i];
  4261. $hasRight = ($i + 1) < $n;
  4262. $orderSummaryGrid[] = [
  4263. 'l1' => $left['label'],
  4264. 'v1' => $left['value'],
  4265. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4266. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4267. ];
  4268. }
  4269. return [
  4270. 'steps' => $steps,
  4271. 'orderSummary' => $orderSummary,
  4272. 'orderSummaryGrid' => $orderSummaryGrid,
  4273. 'detailRows' => $details,
  4274. ];
  4275. }
  4276. /**
  4277. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4278. *
  4279. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4280. */
  4281. protected function prepareProcuremenDetailsView(string $ids): array
  4282. {
  4283. $main = [];
  4284. try {
  4285. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4286. $main = is_array($one) ? $one : [];
  4287. } catch (\Throwable $e) {
  4288. $main = [];
  4289. }
  4290. $details = [];
  4291. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4292. if ($mergeRows === []) {
  4293. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4294. if ($mergeRows === [] && $main !== []) {
  4295. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4296. }
  4297. }
  4298. $detailSidList = [];
  4299. $anchorSid = (int)$ids;
  4300. if ($anchorSid !== 0) {
  4301. $detailSidList[$anchorSid] = true;
  4302. }
  4303. foreach ($mergeRows as $mr) {
  4304. if (!is_array($mr)) {
  4305. continue;
  4306. }
  4307. $sid = $this->extractScydgyRowId($mr);
  4308. if ($sid !== 0) {
  4309. $detailSidList[$sid] = true;
  4310. }
  4311. }
  4312. try {
  4313. if ($detailSidList !== []) {
  4314. $details = Db::table('purchase_order_detail')
  4315. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4316. ->order('id', 'asc')
  4317. ->select();
  4318. }
  4319. } catch (\Throwable $e) {
  4320. $details = [];
  4321. }
  4322. if (!is_array($details)) {
  4323. $details = [];
  4324. }
  4325. foreach ($details as &$r) {
  4326. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4327. $r['id'] = $r['ID'];
  4328. }
  4329. if (isset($r['createtime'])) {
  4330. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4331. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4332. } else {
  4333. $r['createtime_text'] = (string)$r['createtime'];
  4334. }
  4335. } else {
  4336. $r['createtime_text'] = '';
  4337. }
  4338. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4339. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4340. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4341. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4342. if (is_array($r)) {
  4343. $r = $this->maskSupplierContactFields($r);
  4344. }
  4345. }
  4346. unset($r);
  4347. $activeDetails = [];
  4348. foreach ($details as $r) {
  4349. if (is_array($r) && empty($r['is_void'])) {
  4350. $activeDetails[] = $r;
  4351. }
  4352. }
  4353. $operLogs = [];
  4354. try {
  4355. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  4356. } catch (\Throwable $e) {
  4357. $operLogs = [];
  4358. }
  4359. if (!is_array($operLogs)) {
  4360. $operLogs = [];
  4361. }
  4362. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4363. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4364. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4365. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4366. if ($ccydh === '') {
  4367. foreach ($details as $r) {
  4368. if (!is_array($r)) {
  4369. continue;
  4370. }
  4371. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4372. if ($ccydh !== '') {
  4373. break;
  4374. }
  4375. }
  4376. }
  4377. $this->view->assign('ccydh', $ccydh);
  4378. $this->view->assign('steps', $bundle['steps']);
  4379. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4380. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4381. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4382. $this->view->assign('processCount', count($mergeRows));
  4383. $this->view->assign('detailRows', $details);
  4384. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4385. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4386. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4387. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4388. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  4389. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  4390. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  4391. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  4392. $this->view->assign('operLogs', $operLogs);
  4393. return [
  4394. 'ok' => $main !== [] || $details !== [],
  4395. 'ccydh' => $ccydh,
  4396. ];
  4397. }
  4398. /**
  4399. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4400. */
  4401. public function details()
  4402. {
  4403. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4404. if (is_array($ids)) {
  4405. $ids = isset($ids[0]) ? $ids[0] : '';
  4406. }
  4407. $ids = trim((string)$ids);
  4408. if ($ids === '') {
  4409. $this->error(__('Invalid parameters'));
  4410. }
  4411. $this->assertManualOrderDetailsViewable((int)$ids);
  4412. $this->prepareProcuremenDetailsView($ids);
  4413. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4414. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4415. $this->view->engine->layout(false);
  4416. try {
  4417. return $this->view->fetch('procuremen/details_dialog_shell');
  4418. } finally {
  4419. if ($restoreLayout) {
  4420. $this->view->engine->layout($restoreLayout);
  4421. }
  4422. }
  4423. }
  4424. /**
  4425. * 解析合并审核工序行(订单号须一致,且均未协助)
  4426. *
  4427. * @return array<int, array<string, mixed>>
  4428. */
  4429. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4430. {
  4431. $primary = json_decode($rowJson, true);
  4432. if (!is_array($primary)) {
  4433. $this->error(__('Invalid parameters'));
  4434. }
  4435. $merge = json_decode($mergeRowsJson, true);
  4436. if (!is_array($merge) || $merge === []) {
  4437. $merge = [$primary];
  4438. }
  4439. $seen = [];
  4440. $out = [];
  4441. foreach ($merge as $r) {
  4442. if (!is_array($r)) {
  4443. continue;
  4444. }
  4445. $id = $this->extractScydgyRowId($r);
  4446. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4447. continue;
  4448. }
  4449. $seen[$id] = true;
  4450. $out[] = $r;
  4451. }
  4452. if ($out === []) {
  4453. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4454. }
  4455. $ccydh = null;
  4456. foreach ($out as $r) {
  4457. $dh = trim((string)($r['CCYDH'] ?? ''));
  4458. if ($ccydh === null) {
  4459. $ccydh = $dh;
  4460. } elseif ($dh !== $ccydh) {
  4461. $this->error('合并审核要求所选行的订单号一致');
  4462. }
  4463. }
  4464. $ids = [];
  4465. foreach ($out as $r) {
  4466. $id = $this->extractScydgyRowId($r);
  4467. if ($this->isValidScydgyRowId($id)) {
  4468. $ids[$id] = true;
  4469. }
  4470. }
  4471. $poBySid = [];
  4472. $detCntBySid = [];
  4473. if ($ids !== []) {
  4474. $idList = array_keys($ids);
  4475. try {
  4476. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4477. if (is_array($poList)) {
  4478. foreach ($poList as $po) {
  4479. if (!is_array($po)) {
  4480. continue;
  4481. }
  4482. $sid = (int)($po['scydgy_id'] ?? 0);
  4483. if ($this->isValidScydgyRowId($sid)) {
  4484. $poBySid[$sid] = $po;
  4485. }
  4486. }
  4487. }
  4488. } catch (\Throwable $e) {
  4489. }
  4490. try {
  4491. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4492. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4493. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4494. if (is_array($detRows)) {
  4495. foreach ($detRows as $dr) {
  4496. if (!is_array($dr)) {
  4497. continue;
  4498. }
  4499. $sid = (int)($dr['scydgy_id'] ?? 0);
  4500. if ($this->isValidScydgyRowId($sid)) {
  4501. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4502. }
  4503. }
  4504. }
  4505. } catch (\Throwable $e) {
  4506. }
  4507. }
  4508. foreach ($out as $r) {
  4509. $id = $this->extractScydgyRowId($r);
  4510. if (!$this->isValidScydgyRowId($id)) {
  4511. continue;
  4512. }
  4513. $po = $poBySid[$id] ?? null;
  4514. if (!is_array($po)) {
  4515. continue;
  4516. }
  4517. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4518. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4519. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4520. }
  4521. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4522. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4523. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4524. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4525. }
  4526. }
  4527. return $out;
  4528. }
  4529. /**
  4530. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4531. */
  4532. protected function maskSupplierContactFields(array $item): array
  4533. {
  4534. if (array_key_exists('email', $item)) {
  4535. $item['email'] = mask_email((string)$item['email']);
  4536. }
  4537. if (array_key_exists('phone', $item)) {
  4538. $item['phone'] = mask_phone((string)$item['phone']);
  4539. }
  4540. return $item;
  4541. }
  4542. /**
  4543. * @param array<int, array<string, mixed>> $list
  4544. * @return array<int, array<string, mixed>>
  4545. */
  4546. protected function maskSupplierContactList(array $list): array
  4547. {
  4548. $out = [];
  4549. foreach ($list as $item) {
  4550. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4551. }
  4552. return $out;
  4553. }
  4554. /**
  4555. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4556. *
  4557. * @return array<string, string>|null
  4558. */
  4559. protected function buildCustomerContactPayloadFromRow($row): ?array
  4560. {
  4561. if (!is_array($row)) {
  4562. return null;
  4563. }
  4564. $norm = [];
  4565. foreach ($row as $k => $v) {
  4566. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4567. }
  4568. $row = $norm;
  4569. $st = $row['status'] ?? '';
  4570. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4571. return null;
  4572. }
  4573. $companyName = '';
  4574. foreach (['company_name', 'name'] as $nk) {
  4575. if (!empty($row[$nk])) {
  4576. $companyName = trim((string)$row[$nk]);
  4577. break;
  4578. }
  4579. }
  4580. if ($companyName === '') {
  4581. return null;
  4582. }
  4583. $username = '';
  4584. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4585. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4586. $username = trim((string)$row[$uk]);
  4587. break;
  4588. }
  4589. }
  4590. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4591. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4592. if ($phone === '' && isset($row['account'])) {
  4593. $phone = trim((string)$row['account']);
  4594. }
  4595. if ($phone === '' && isset($row['mobile'])) {
  4596. $phone = trim((string)$row['mobile']);
  4597. }
  4598. if ($email === '' && $phone === '') {
  4599. return null;
  4600. }
  4601. $category = '';
  4602. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4603. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4604. $category = trim((string)$row[$ck]);
  4605. break;
  4606. }
  4607. }
  4608. return [
  4609. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4610. 'name' => $companyName,
  4611. 'company_name' => $companyName,
  4612. 'username' => $username,
  4613. 'email' => $email,
  4614. 'phone' => $phone,
  4615. 'category' => $category,
  4616. 'company_type' => $category,
  4617. ];
  4618. }
  4619. /**
  4620. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4621. */
  4622. protected function resolveCustomerContactById(string $id): ?array
  4623. {
  4624. $id = trim($id);
  4625. if ($id === '' || !ctype_digit($id)) {
  4626. return null;
  4627. }
  4628. try {
  4629. $row = Db::table('customer')->where('id', (int)$id)->find();
  4630. } catch (\Throwable $e) {
  4631. return null;
  4632. }
  4633. return $this->buildCustomerContactPayloadFromRow($row);
  4634. }
  4635. /**
  4636. * 按供应商名称解析联系信息(兼容旧提交数据)
  4637. */
  4638. protected function resolveCustomerContactByCompanyName(string $name): ?array
  4639. {
  4640. $name = trim($name);
  4641. if ($name === '') {
  4642. return null;
  4643. }
  4644. try {
  4645. $row = Db::table('customer')
  4646. ->where(function ($q) use ($name) {
  4647. $q->where('company_name', $name)->whereOr('name', $name);
  4648. })
  4649. ->order('id', 'desc')
  4650. ->find();
  4651. } catch (\Throwable $e) {
  4652. return null;
  4653. }
  4654. return $this->buildCustomerContactPayloadFromRow($row);
  4655. }
  4656. /**
  4657. * 规范化下发/确认时勾选的供应商
  4658. *
  4659. * @param array<int, mixed> $companies
  4660. * @return array<int, array<string, string>>
  4661. */
  4662. protected function normalizePickCompanies(array $companies): array
  4663. {
  4664. $out = [];
  4665. foreach ($companies as $c) {
  4666. if (!is_array($c)) {
  4667. continue;
  4668. }
  4669. $resolved = null;
  4670. $cid = trim((string)($c['id'] ?? ''));
  4671. if ($cid !== '') {
  4672. $resolved = $this->resolveCustomerContactById($cid);
  4673. }
  4674. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  4675. if ($resolved === null && $name !== '') {
  4676. $resolved = $this->resolveCustomerContactByCompanyName($name);
  4677. }
  4678. if ($resolved === null) {
  4679. continue;
  4680. }
  4681. $out[] = $resolved;
  4682. }
  4683. return $out;
  4684. }
  4685. /**
  4686. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  4687. *
  4688. * @param array<int, array<string, mixed>> $pool
  4689. * @return array<int, array<string, mixed>>
  4690. */
  4691. protected function collapseProcuremenPoolByOrder(array $pool): array
  4692. {
  4693. if ($pool === []) {
  4694. return [];
  4695. }
  4696. $groups = [];
  4697. foreach ($pool as $row) {
  4698. if (!is_array($row)) {
  4699. continue;
  4700. }
  4701. $dh = trim((string)($row['CCYDH'] ?? ''));
  4702. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  4703. if (!isset($groups[$key])) {
  4704. $groups[$key] = [];
  4705. }
  4706. $groups[$key][] = $row;
  4707. }
  4708. $out = [];
  4709. foreach ($groups as $ccydh => $rows) {
  4710. if ($rows === []) {
  4711. continue;
  4712. }
  4713. usort($rows, function ($a, $b) {
  4714. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  4715. });
  4716. $head = $rows[0];
  4717. $gymcList = [];
  4718. foreach ($rows as $r) {
  4719. $g = trim((string)($r['CGYMC'] ?? ''));
  4720. if ($g !== '' && !in_array($g, $gymcList, true)) {
  4721. $gymcList[] = $g;
  4722. }
  4723. }
  4724. $merged = $head;
  4725. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  4726. $merged['process_count'] = count($rows);
  4727. $merged['_order_merge_rows'] = $rows;
  4728. if (count($rows) > 1) {
  4729. $merged['CGYMC'] = implode('、', $gymcList);
  4730. }
  4731. $mergedPickTime = '';
  4732. foreach ($rows as $r) {
  4733. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  4734. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  4735. $mergedPickTime = $t;
  4736. }
  4737. }
  4738. if ($mergedPickTime !== '') {
  4739. $merged['pick_time'] = $mergedPickTime;
  4740. }
  4741. $out[] = $merged;
  4742. }
  4743. usort($out, function ($a, $b) {
  4744. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  4745. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  4746. if ($ta === $tb) {
  4747. $ida = (int)($a['purchase_order_id'] ?? 0);
  4748. $idb = (int)($b['purchase_order_id'] ?? 0);
  4749. if ($ida !== $idb) {
  4750. return $idb <=> $ida;
  4751. }
  4752. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  4753. }
  4754. if ($ta === '') {
  4755. return 1;
  4756. }
  4757. if ($tb === '') {
  4758. return -1;
  4759. }
  4760. return strcmp($tb, $ta);
  4761. });
  4762. return $out;
  4763. }
  4764. /**
  4765. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  4766. *
  4767. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4768. */
  4769. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  4770. {
  4771. $scydgyId = trim($scydgyId);
  4772. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4773. if ($scydgyId === '') {
  4774. return $empty;
  4775. }
  4776. try {
  4777. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4778. } catch (\Throwable $e) {
  4779. $anchor = null;
  4780. }
  4781. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  4782. return $empty;
  4783. }
  4784. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4785. if ($ccydh === '') {
  4786. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4787. }
  4788. try {
  4789. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4790. } catch (\Throwable $e) {
  4791. $pos = [$anchor];
  4792. }
  4793. if (!is_array($pos) || $pos === []) {
  4794. $pos = [$anchor];
  4795. }
  4796. return [
  4797. 'ccydh' => $ccydh,
  4798. 'pos' => $pos,
  4799. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4800. ];
  4801. }
  4802. /**
  4803. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4804. */
  4805. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4806. {
  4807. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4808. return false;
  4809. }
  4810. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4811. return false;
  4812. }
  4813. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4814. return true;
  4815. }
  4816. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4817. $sid = (int)($po['scydgy_id'] ?? 0);
  4818. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4819. }
  4820. return false;
  4821. }
  4822. /**
  4823. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4824. *
  4825. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4826. */
  4827. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4828. {
  4829. $scydgyId = trim($scydgyId);
  4830. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4831. if ($scydgyId === '') {
  4832. return $empty;
  4833. }
  4834. try {
  4835. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4836. } catch (\Throwable $e) {
  4837. $anchor = null;
  4838. }
  4839. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4840. return $empty;
  4841. }
  4842. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4843. if ($ccydh === '') {
  4844. return [
  4845. 'ccydh' => '',
  4846. 'pos' => [$anchor],
  4847. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  4848. ];
  4849. }
  4850. try {
  4851. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  4852. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  4853. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  4854. } catch (\Throwable $e) {
  4855. $pos = [$anchor];
  4856. }
  4857. if (!is_array($pos) || $pos === []) {
  4858. $pos = [$anchor];
  4859. }
  4860. $pos = array_values(array_filter($pos, function ($po) {
  4861. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  4862. }));
  4863. if ($pos === []) {
  4864. $pos = [$anchor];
  4865. }
  4866. return [
  4867. 'ccydh' => $ccydh,
  4868. 'pos' => $pos,
  4869. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4870. ];
  4871. }
  4872. /**
  4873. * @param array<int, array<string, mixed>> $purchaseOrders
  4874. * @return array<int, array<string, mixed>>
  4875. */
  4876. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  4877. {
  4878. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  4879. $byId = [];
  4880. foreach ($pool as $r) {
  4881. if (!is_array($r)) {
  4882. continue;
  4883. }
  4884. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  4885. if ($this->isValidScydgyRowId($sid)) {
  4886. $byId[$sid] = $r;
  4887. }
  4888. }
  4889. $out = [];
  4890. foreach ($purchaseOrders as $po) {
  4891. if (!is_array($po)) {
  4892. continue;
  4893. }
  4894. $sid = (int)($po['scydgy_id'] ?? 0);
  4895. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  4896. $out[] = $byId[$sid];
  4897. }
  4898. }
  4899. return $out;
  4900. }
  4901. /**
  4902. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  4903. *
  4904. * @return array<int, array<string, mixed>>
  4905. */
  4906. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  4907. {
  4908. $scydgyId = trim($scydgyId);
  4909. if ($scydgyId === '') {
  4910. return [];
  4911. }
  4912. try {
  4913. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4914. } catch (\Throwable $e) {
  4915. $anchor = null;
  4916. }
  4917. if (!is_array($anchor)) {
  4918. return [];
  4919. }
  4920. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  4921. return [];
  4922. }
  4923. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4924. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  4925. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  4926. try {
  4927. $q = Db::table('purchase_order');
  4928. if ($ccydh !== '') {
  4929. $q->where('CCYDH', $ccydh);
  4930. } else {
  4931. $q->where('scydgy_id', $scydgyId);
  4932. }
  4933. if ($isValidPick) {
  4934. $q->where('pick_time', $pickTime);
  4935. }
  4936. $pos = $q->order('scydgy_id', 'asc')->select();
  4937. } catch (\Throwable $e) {
  4938. $pos = [$anchor];
  4939. }
  4940. if (!is_array($pos) || $pos === []) {
  4941. $pos = [$anchor];
  4942. }
  4943. $pos = array_values(array_filter($pos, function ($po) {
  4944. if (!is_array($po)) {
  4945. return false;
  4946. }
  4947. $mr = $po['mod_rq'] ?? null;
  4948. if ($mr === null || $mr === '') {
  4949. return true;
  4950. }
  4951. $mrs = trim((string)$mr);
  4952. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  4953. }));
  4954. if ($pos === []) {
  4955. $pos = [$anchor];
  4956. }
  4957. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  4958. if ($rows === []) {
  4959. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  4960. }
  4961. return $rows;
  4962. }
  4963. /**
  4964. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  4965. *
  4966. * @param array<int, array<string, mixed>> $mergeRows
  4967. * @return array<int, array<string, mixed>>
  4968. */
  4969. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  4970. {
  4971. $list = array_values($mergeRows);
  4972. $n = count($list);
  4973. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  4974. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  4975. $mergeSame = $n > 1 && $orderKey0 !== '';
  4976. if ($mergeSame) {
  4977. foreach ($list as $rr) {
  4978. if (!is_array($rr)) {
  4979. $mergeSame = false;
  4980. break;
  4981. }
  4982. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  4983. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  4984. $mergeSame = false;
  4985. break;
  4986. }
  4987. }
  4988. }
  4989. $out = [];
  4990. foreach ($list as $idx => $r) {
  4991. if (!is_array($r)) {
  4992. continue;
  4993. }
  4994. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  4995. if (is_scalar($qty)) {
  4996. $qty = trim((string)$qty);
  4997. } else {
  4998. $qty = '';
  4999. }
  5000. if ($qty === '') {
  5001. $gzl = $r['NGZL'] ?? '';
  5002. if (is_scalar($gzl)) {
  5003. $qty = trim((string)$gzl);
  5004. }
  5005. }
  5006. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  5007. $sid = $this->extractScydgyRowId($r);
  5008. $out[] = [
  5009. 'seq' => $idx + 1,
  5010. 'scydgy_id' => $sid,
  5011. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5012. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5013. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5014. 'CDW' => trim((string)($r['CDW'] ?? '')),
  5015. 'NGZL' => $r['NGZL'] ?? '',
  5016. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  5017. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  5018. 'CDF' => trim((string)($r['CDF'] ?? '')),
  5019. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  5020. 'show_order_cells' => !$mergeSame || $idx === 0,
  5021. 'order_rowspan' => $mergeSame ? $n : 1,
  5022. ];
  5023. }
  5024. return $out;
  5025. }
  5026. /**
  5027. * 解析金额/数量(去千分位等非数字字符)
  5028. */
  5029. protected function parseProcuremenMoneyNumber($value): ?float
  5030. {
  5031. if ($value === null || $value === '') {
  5032. return null;
  5033. }
  5034. if (is_numeric($value)) {
  5035. return (float)$value;
  5036. }
  5037. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  5038. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  5039. }
  5040. protected function formatProcuremenMoneyDisplay(?float $amount): string
  5041. {
  5042. if ($amount === null) {
  5043. return '';
  5044. }
  5045. return (string)(int)round($amount);
  5046. }
  5047. /**
  5048. * 列表/详情展示:工作量为 0 时显示空
  5049. */
  5050. protected function formatProcuremenWorkloadDisplay($value): string
  5051. {
  5052. if ($value === null || $value === '') {
  5053. return '';
  5054. }
  5055. $s = trim((string)$value);
  5056. if ($s === '') {
  5057. return '';
  5058. }
  5059. if (is_numeric($s) && (float)$s == 0) {
  5060. return '';
  5061. }
  5062. return $s;
  5063. }
  5064. /**
  5065. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  5066. */
  5067. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  5068. {
  5069. foreach ($details as $d) {
  5070. if (!is_array($d)) {
  5071. continue;
  5072. }
  5073. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  5074. $cn = trim((string)($d['company_name'] ?? ''));
  5075. if ($cn !== '') {
  5076. return $cn;
  5077. }
  5078. }
  5079. }
  5080. return trim((string)($main['pick_company_name'] ?? ''));
  5081. }
  5082. /**
  5083. * 详情报价小计:单价 × 本工序本次数量
  5084. */
  5085. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  5086. {
  5087. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  5088. if ($unit === null) {
  5089. return null;
  5090. }
  5091. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  5092. if ($qty === null || $qty <= 0) {
  5093. return null;
  5094. }
  5095. return $unit * $qty;
  5096. }
  5097. /**
  5098. * 详情页:工序小计 + 供应商分组报价与总计
  5099. *
  5100. * @param array<int, array<string, mixed>> $mergeRows
  5101. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  5102. * @return array{
  5103. * process_rows: array,
  5104. * supplier_groups: array,
  5105. * order_total_text: string,
  5106. * order_total_has: bool,
  5107. * selected_company: string
  5108. * }
  5109. */
  5110. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  5111. {
  5112. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5113. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  5114. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  5115. $qtyBySid = [];
  5116. $gymcBySid = [];
  5117. $orderedSids = [];
  5118. foreach ($mergeRows as $mr) {
  5119. if (!is_array($mr)) {
  5120. continue;
  5121. }
  5122. $sid = $this->extractScydgyRowId($mr);
  5123. if ($this->isValidScydgyRowId($sid)) {
  5124. $orderedSids[] = $sid;
  5125. }
  5126. $qty = trim((string)($mr['This_quantity'] ?? ''));
  5127. if ($qty === '') {
  5128. $qty = trim((string)($mr['NGZL'] ?? ''));
  5129. }
  5130. $qtyBySid[$sid] = $qty;
  5131. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  5132. }
  5133. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  5134. $detailByCompanySid = [];
  5135. foreach ($details as $d) {
  5136. if (!is_array($d)) {
  5137. continue;
  5138. }
  5139. $cn = trim((string)($d['company_name'] ?? ''));
  5140. $sid = (int)($d['scydgy_id'] ?? 0);
  5141. if ($cn === '' || $sid === 0) {
  5142. continue;
  5143. }
  5144. if (!isset($detailByCompanySid[$cn])) {
  5145. $detailByCompanySid[$cn] = [];
  5146. }
  5147. $detailByCompanySid[$cn][$sid] = $d;
  5148. }
  5149. $supplierGroups = [];
  5150. foreach ($detailByCompanySid as $cn => $bySid) {
  5151. $lines = [];
  5152. $groupTotal = 0.0;
  5153. $groupHas = false;
  5154. $groupVoid = true;
  5155. $usedSids = [];
  5156. $appendLine = function (int $sid, array $d) use (
  5157. &$lines,
  5158. &$groupTotal,
  5159. &$groupHas,
  5160. &$groupVoid,
  5161. $qtyBySid,
  5162. $gymcBySid,
  5163. $quoteVisible
  5164. ) {
  5165. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5166. if (!$isVoid) {
  5167. $groupVoid = false;
  5168. }
  5169. $qtyStr = $qtyBySid[$sid] ?? '';
  5170. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5171. $am = trim((string)($d['amount'] ?? ''));
  5172. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5173. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5174. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5175. $sub = null;
  5176. if (!$isVoid && $amountNum !== null) {
  5177. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5178. }
  5179. $ct = $this->resolveDetailSupplierOperTime($d);
  5180. $line = [
  5181. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5182. 'unit_price_text' => $amountFilled
  5183. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  5184. : '未填写',
  5185. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5186. 'delivery_ymd' => $deliveryYmd,
  5187. 'amount_filled' => $amountFilled,
  5188. 'delivery_filled' => $deliveryFilled,
  5189. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5190. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5191. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5192. 'is_void' => $isVoid,
  5193. 'oper_time_text' => $ct,
  5194. ];
  5195. if (!$quoteVisible && !$isVoid) {
  5196. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5197. } elseif ($sub !== null) {
  5198. $groupTotal += $sub;
  5199. $groupHas = true;
  5200. }
  5201. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5202. };
  5203. foreach ($orderedSids as $sid) {
  5204. if (!isset($bySid[$sid])) {
  5205. continue;
  5206. }
  5207. $usedSids[$sid] = true;
  5208. $appendLine($sid, $bySid[$sid]);
  5209. }
  5210. foreach ($bySid as $sid => $d) {
  5211. if (isset($usedSids[$sid])) {
  5212. continue;
  5213. }
  5214. $appendLine((int)$sid, $d);
  5215. }
  5216. $firstDetail = null;
  5217. foreach ($bySid as $d) {
  5218. if (is_array($d)) {
  5219. $firstDetail = $d;
  5220. break;
  5221. }
  5222. }
  5223. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5224. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5225. if ($username === '' && $ph !== '') {
  5226. $username = $this->resolveCustomerContactName($ph, $cn);
  5227. }
  5228. $remark = '';
  5229. foreach ($bySid as $d) {
  5230. if (!is_array($d)) {
  5231. continue;
  5232. }
  5233. $rm = '';
  5234. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  5235. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  5236. $rm = trim((string)$d[$rk]);
  5237. break;
  5238. }
  5239. }
  5240. if ($rm !== '') {
  5241. $remark = $rm;
  5242. break;
  5243. }
  5244. }
  5245. $lineCount = count($lines);
  5246. $hasRemark = $lineCount > 0;
  5247. $supplierGroup = [
  5248. 'company_name' => $cn,
  5249. 'username' => $username,
  5250. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5251. 'phone' => $ph,
  5252. 'remark' => $remark,
  5253. 'has_remark' => $hasRemark,
  5254. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5255. 'is_void' => $groupVoid,
  5256. 'lines' => $lines,
  5257. 'line_count' => $lineCount,
  5258. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  5259. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5260. 'has_total' => $lineCount > 0,
  5261. ];
  5262. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  5263. $supplierGroups[] = $supplierGroup;
  5264. }
  5265. usort($supplierGroups, function ($a, $b) {
  5266. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5267. return ($a['is_void'] ?? false) ? 1 : -1;
  5268. }
  5269. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5270. return ($a['is_selected'] ?? false) ? -1 : 1;
  5271. }
  5272. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5273. });
  5274. return [
  5275. 'process_rows' => $processRows,
  5276. 'supplier_groups' => $supplierGroups,
  5277. 'order_total_text' => '',
  5278. 'order_total_has' => false,
  5279. 'selected_company' => $selectedCompany,
  5280. ];
  5281. }
  5282. /**
  5283. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5284. */
  5285. protected function buildProcessLinesPlain(array $mergeRows): string
  5286. {
  5287. $lines = [];
  5288. $i = 1;
  5289. foreach ($mergeRows as $r) {
  5290. if (!is_array($r)) {
  5291. continue;
  5292. }
  5293. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5294. $dw = trim((string)($r['CDW'] ?? ''));
  5295. $gzl = trim((string)($r['NGZL'] ?? ''));
  5296. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5297. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5298. if ($dw !== '') {
  5299. $parts[] = '单位:' . $dw;
  5300. }
  5301. if ($gzl !== '') {
  5302. $parts[] = '工作量:' . $gzl;
  5303. }
  5304. if ($qty !== '') {
  5305. $parts[] = '本次数量:' . $qty;
  5306. }
  5307. $lines[] = implode(' ', $parts);
  5308. $i++;
  5309. }
  5310. return implode("\n", $lines);
  5311. }
  5312. /**
  5313. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5314. *
  5315. * @return array<string, string>
  5316. */
  5317. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5318. {
  5319. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5320. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5321. }
  5322. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5323. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5324. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5325. $cyjmc = '';
  5326. foreach ($mergeRows as $mr) {
  5327. if (!is_array($mr)) {
  5328. continue;
  5329. }
  5330. if ($ccydh === '') {
  5331. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5332. }
  5333. if ($cyjmc === '') {
  5334. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5335. }
  5336. }
  5337. if ($pos !== []) {
  5338. $firstPo = $pos[0];
  5339. if (is_array($firstPo)) {
  5340. if ($ccydh === '') {
  5341. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5342. }
  5343. if ($cyjmc === '') {
  5344. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5345. }
  5346. }
  5347. }
  5348. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5349. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5350. if (is_array($any)) {
  5351. if ($ccydh === '') {
  5352. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5353. }
  5354. if ($cyjmc === '') {
  5355. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5356. }
  5357. }
  5358. }
  5359. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5360. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5361. $cgymc = '';
  5362. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5363. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5364. }
  5365. return [
  5366. 'ccydh' => $ccydh,
  5367. 'cyjmc' => $cyjmc,
  5368. 'cgymc' => $cgymc,
  5369. 'process_lines' => $processLines,
  5370. 'process_lines_html' => '',
  5371. ];
  5372. }
  5373. /**
  5374. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5375. */
  5376. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5377. {
  5378. $lines = [];
  5379. if ($ccydh !== '') {
  5380. $lines[] = '订单号:' . $ccydh;
  5381. }
  5382. if ($cyjmc !== '') {
  5383. $lines[] = '印件名称:' . $cyjmc;
  5384. }
  5385. if ($processPlain !== '') {
  5386. $lines[] = $processPlain;
  5387. }
  5388. return implode("\n", $lines);
  5389. }
  5390. /**
  5391. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5392. *
  5393. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5394. */
  5395. protected function buildPlatformLinksPlain(array $detailLinks): string
  5396. {
  5397. $lines = [];
  5398. $i = 1;
  5399. foreach ($detailLinks as $lk) {
  5400. if (!is_array($lk)) {
  5401. continue;
  5402. }
  5403. $url = trim((string)($lk['url'] ?? ''));
  5404. if ($url === '') {
  5405. continue;
  5406. }
  5407. $label = trim((string)($lk['cgymc'] ?? ''));
  5408. if ($label === '') {
  5409. $label = '工序' . $i;
  5410. }
  5411. $lines[] = $label . ':' . $url;
  5412. $i++;
  5413. }
  5414. return implode("\n", $lines);
  5415. }
  5416. /**
  5417. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5418. *
  5419. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5420. */
  5421. protected function buildPlatformLinksHtml(array $detailLinks): string
  5422. {
  5423. $parts = [];
  5424. $i = 1;
  5425. foreach ($detailLinks as $lk) {
  5426. if (!is_array($lk)) {
  5427. continue;
  5428. }
  5429. $url = trim((string)($lk['url'] ?? ''));
  5430. if ($url === '') {
  5431. continue;
  5432. }
  5433. $label = trim((string)($lk['cgymc'] ?? ''));
  5434. if ($label === '') {
  5435. $label = '工序' . $i;
  5436. }
  5437. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5438. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5439. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5440. $i++;
  5441. }
  5442. return implode("<br>\n", $parts);
  5443. }
  5444. /**
  5445. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5446. *
  5447. * @return array<string, mixed>
  5448. */
  5449. protected function loadMailerConfig(): array
  5450. {
  5451. try {
  5452. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5453. } catch (\Throwable $e) {
  5454. $cfg = [];
  5455. }
  5456. return is_array($cfg) ? $cfg : [];
  5457. }
  5458. protected function loadNotifyTemplateRow(string $scene): ?array
  5459. {
  5460. try {
  5461. $row = Db::table('purchase_sms_template')
  5462. ->where('scene', $scene)
  5463. ->where(function ($q) {
  5464. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5465. })
  5466. ->order('id', 'asc')
  5467. ->find();
  5468. } catch (\Throwable $e) {
  5469. return null;
  5470. }
  5471. if (!is_array($row) || $row === []) {
  5472. return null;
  5473. }
  5474. return [
  5475. 'title' => trim((string)($row['title'] ?? '')),
  5476. 'content' => trim((string)($row['content'] ?? '')),
  5477. ];
  5478. }
  5479. /**
  5480. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5481. */
  5482. protected function buildProcessLinesHtml(array $mergeRows): string
  5483. {
  5484. if (count($mergeRows) <= 1) {
  5485. $r = $mergeRows[0] ?? [];
  5486. if (!is_array($r)) {
  5487. return '';
  5488. }
  5489. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5490. $dw = trim((string)($r['CDW'] ?? ''));
  5491. $gzl = trim((string)($r['NGZL'] ?? ''));
  5492. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5493. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5494. if ($dw !== '') {
  5495. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5496. }
  5497. if ($gzl !== '') {
  5498. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5499. }
  5500. if ($qty !== '') {
  5501. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5502. }
  5503. return $html;
  5504. }
  5505. $rows = '';
  5506. $i = 1;
  5507. foreach ($mergeRows as $r) {
  5508. if (!is_array($r)) {
  5509. continue;
  5510. }
  5511. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5512. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5513. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5514. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5515. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5516. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5517. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5518. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5519. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5520. $i++;
  5521. }
  5522. if ($rows === '') {
  5523. return '';
  5524. }
  5525. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5526. . '<thead><tr style="background:#f5f5f5;">'
  5527. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5528. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5529. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5530. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5531. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5532. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5533. }
  5534. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  5535. {
  5536. $sysRq = trim($sysRq);
  5537. if ($sysRq === '') {
  5538. if ($required) {
  5539. $this->error('请选择截止时间');
  5540. }
  5541. return '';
  5542. }
  5543. $ts = strtotime($sysRq);
  5544. if ($ts === false || $ts <= 0) {
  5545. $this->error('截止时间格式无效');
  5546. }
  5547. return date('Y-m-d H:i:s', $ts);
  5548. }
  5549. protected function formatProcuremenSysRqForInput($sysRq): string
  5550. {
  5551. $sr = trim((string)$sysRq);
  5552. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  5553. return '';
  5554. }
  5555. $ts = strtotime($sr);
  5556. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  5557. }
  5558. protected function formatProcuremenSysRqForDisplay($sysRq): string
  5559. {
  5560. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  5561. if ($sr === '') {
  5562. return '—';
  5563. }
  5564. $ts = strtotime($sr);
  5565. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  5566. }
  5567. /**
  5568. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  5569. *
  5570. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  5571. * @return array{ccydh?:string,pos:array,merge_rows:array}
  5572. */
  5573. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  5574. {
  5575. return $bundle;
  5576. }
  5577. /**
  5578. * 写入/更新 purchase_order(单道工序行)
  5579. */
  5580. protected function upsertPurchaseOrderFromRow(
  5581. array $row,
  5582. string $sysRqDb,
  5583. $wflowStatus = null,
  5584. ?string $pickTime = null,
  5585. ?array $exists = null
  5586. ): void {
  5587. $ids = $this->extractScydgyRowId($row);
  5588. if (!$this->isValidScydgyRowId($ids)) {
  5589. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  5590. }
  5591. if ($exists === null) {
  5592. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5593. }
  5594. $data = [
  5595. 'scydgy_id' => $ids,
  5596. 'CCYDH' => $row['CCYDH'] ?? null,
  5597. 'CYJMC' => $row['CYJMC'] ?? null,
  5598. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5599. 'CDXMC' => $row['CDXMC'] ?? null,
  5600. 'CGYBH' => $row['CGYBH'] ?? null,
  5601. 'CGYMC' => $row['CGYMC'] ?? null,
  5602. 'CDW' => $row['CDW'] ?? null,
  5603. 'NGZL' => $row['NGZL'] ?? null,
  5604. 'CDF' => $row['CDF'] ?? null,
  5605. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5606. 'MBZ' => $row['MBZ'] ?? null,
  5607. 'bwjg' => $row['bwjg'] ?? null,
  5608. 'iStatus' => $row['iStatus'] ?? null,
  5609. 'dStamp' => $row['dStamp'] ?? null,
  5610. 'dputrecord' => $row['dputrecord'] ?? null,
  5611. 'cywyxm' => $row['cywyxm'] ?? null,
  5612. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5613. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5614. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5615. 'sys_rq' => $sysRqDb,
  5616. ];
  5617. if ($wflowStatus !== null && $wflowStatus !== '') {
  5618. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  5619. }
  5620. if ($pickTime !== null && $pickTime !== '') {
  5621. $data['pick_time'] = $pickTime;
  5622. $data['pick_company_name'] = '';
  5623. }
  5624. if ($exists) {
  5625. $upd = $data;
  5626. unset($upd['scydgy_id']);
  5627. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5628. } else {
  5629. $data['createtime'] = date('Y-m-d H:i:s');
  5630. Db::table('purchase_order')->insert($data);
  5631. }
  5632. }
  5633. /**
  5634. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  5635. *
  5636. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  5637. */
  5638. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  5639. {
  5640. $toDb = function ($value) {
  5641. if ($value === null) {
  5642. return null;
  5643. }
  5644. if (is_scalar($value)) {
  5645. return $value;
  5646. }
  5647. return json_encode($value, JSON_UNESCAPED_UNICODE);
  5648. };
  5649. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5650. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5651. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5652. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  5653. if ($username === '') {
  5654. $username = $this->resolveCustomerContactName($phone, $companyName);
  5655. }
  5656. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5657. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  5658. }
  5659. if ($phone === '') {
  5660. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  5661. }
  5662. $detailLinks = [];
  5663. foreach ($mergeRows as $row) {
  5664. if (!is_array($row)) {
  5665. continue;
  5666. }
  5667. $sid = $this->extractScydgyRowId($row);
  5668. $detailId = 0;
  5669. if ($skipExisting) {
  5670. try {
  5671. $existsQuery = Db::table('purchase_order_detail')
  5672. ->where('scydgy_id', $sid)
  5673. ->where('company_name', $companyName);
  5674. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  5675. $exists = $existsQuery->find();
  5676. } catch (\Throwable $e) {
  5677. $exists = null;
  5678. }
  5679. if (is_array($exists)) {
  5680. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  5681. }
  5682. }
  5683. if ($detailId <= 0) {
  5684. $one = [
  5685. 'scydgy_id' => $toDb($sid),
  5686. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  5687. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  5688. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  5689. 'username' => $username !== '' ? $username : null,
  5690. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  5691. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  5692. 'createtime' => date('Y-m-d H:i:s'),
  5693. 'status' => ProcuremenStatus::POD_UNPICKED,
  5694. 'status_name' => '未提交',
  5695. ];
  5696. Db::table('purchase_order_detail')->insert($one);
  5697. $detailId = (int)Db::getLastInsID();
  5698. }
  5699. $mprocUrl = '';
  5700. if ($buildMobileLinks && $detailId > 0) {
  5701. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  5702. }
  5703. $detailLinks[] = [
  5704. 'detail_id' => $detailId,
  5705. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  5706. 'url' => $mprocUrl,
  5707. ];
  5708. }
  5709. return $detailLinks;
  5710. }
  5711. /**
  5712. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  5713. * @return array<string, mixed>
  5714. */
  5715. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  5716. {
  5717. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5718. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5719. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5720. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  5721. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  5722. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  5723. $isMerge = !empty($ctx['is_merge']);
  5724. $contactName = trim((string)($c['username'] ?? ''));
  5725. if ($contactName === '') {
  5726. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  5727. }
  5728. $notifyVars = [
  5729. 'company_name' => $companyName,
  5730. 'contact_name' => $contactName,
  5731. 'phone' => $phone,
  5732. 'email' => $toEmail,
  5733. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  5734. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  5735. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  5736. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  5737. 'deadline' => (string)($ctx['deadline'] ?? ''),
  5738. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  5739. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  5740. 'platform_url' => $platformUrl,
  5741. 'platform_links' => $platformLinksPlain,
  5742. 'platform_links_html' => $platformLinksHtml,
  5743. ];
  5744. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  5745. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  5746. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5747. return [
  5748. 'company_name' => $companyName,
  5749. 'phone' => $phone,
  5750. 'email' => $toEmail,
  5751. 'sms_content' => $smsContent,
  5752. 'mail_plain' => $mailPlain,
  5753. 'mail_body' => $mailBody,
  5754. 'notify_vars' => $notifyVars,
  5755. 'detail_links' => $detailLinks,
  5756. ];
  5757. }
  5758. /**
  5759. * @param array<string, mixed> $chosen
  5760. * @param array<int, array<string, mixed>> $mergeRows
  5761. * @param array{ccydh:string, pos:array} $bundle
  5762. */
  5763. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  5764. {
  5765. if (!$sendSms && !$sendEmail) {
  5766. return;
  5767. }
  5768. $companyName = trim((string)($chosen['name'] ?? ''));
  5769. $phone = trim((string)($chosen['phone'] ?? ''));
  5770. $toEmail = trim((string)($chosen['email'] ?? ''));
  5771. if ($companyName === '') {
  5772. throw new \Exception('供应商名称无效');
  5773. }
  5774. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  5775. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  5776. }
  5777. if ($sendSms && $phone === '') {
  5778. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  5779. }
  5780. $sids = [];
  5781. foreach ($mergeRows as $mr) {
  5782. if (!is_array($mr)) {
  5783. continue;
  5784. }
  5785. $sid = $this->extractScydgyRowId($mr);
  5786. if ($this->isValidScydgyRowId($sid)) {
  5787. $sids[$sid] = true;
  5788. }
  5789. }
  5790. if ($sids === []) {
  5791. throw new \Exception('未找到工序行,无法发送通知');
  5792. }
  5793. $sysRqNotify = '';
  5794. $pos = $bundle['pos'] ?? [];
  5795. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5796. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  5797. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  5798. $ts = strtotime($sr);
  5799. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  5800. }
  5801. }
  5802. try {
  5803. $detailsQuery = Db::table('purchase_order_detail')
  5804. ->where('scydgy_id', 'in', array_keys($sids))
  5805. ->where('company_name', $companyName);
  5806. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5807. $details = $detailsQuery->order('id', 'asc')->select();
  5808. } catch (\Throwable $e) {
  5809. $details = [];
  5810. }
  5811. if (!is_array($details) || $details === []) {
  5812. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  5813. try {
  5814. $detailsQuery = Db::table('purchase_order_detail')
  5815. ->where('scydgy_id', 'in', array_keys($sids))
  5816. ->where('company_name', $companyName);
  5817. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5818. $details = $detailsQuery->order('id', 'asc')->select();
  5819. } catch (\Throwable $e) {
  5820. $details = [];
  5821. }
  5822. }
  5823. if (!is_array($details) || $details === []) {
  5824. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  5825. }
  5826. $detailLinks = [];
  5827. foreach ($details as $d) {
  5828. if (!is_array($d)) {
  5829. continue;
  5830. }
  5831. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  5832. if ($detailId <= 0) {
  5833. continue;
  5834. }
  5835. $sid = (int)($d['scydgy_id'] ?? 0);
  5836. $gymc = '';
  5837. foreach ($mergeRows as $mr) {
  5838. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  5839. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5840. break;
  5841. }
  5842. }
  5843. $detailLinks[] = [
  5844. 'detail_id' => $detailId,
  5845. 'cgymc' => $gymc,
  5846. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  5847. ];
  5848. }
  5849. if ($detailLinks === []) {
  5850. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  5851. }
  5852. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  5853. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  5854. $notifyBundle['email_log_scene'] = $emailLogScene;
  5855. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  5856. $poIdLog = 0;
  5857. $pos = $bundle['pos'] ?? [];
  5858. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5859. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5860. }
  5861. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  5862. if ($sendEmail) {
  5863. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  5864. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  5865. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  5866. }
  5867. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  5868. $mailConfig = $this->loadMailerConfig();
  5869. if (!$this->isProcuremenNotifyDryRun()) {
  5870. if (empty($mailConfig['host'])) {
  5871. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  5872. }
  5873. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  5874. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  5875. }
  5876. }
  5877. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  5878. }
  5879. if ($sendSms) {
  5880. $this->issueSendSupplierSms($notifyBundle);
  5881. }
  5882. }
  5883. /**
  5884. * @param array<int, array<string, mixed>> $quoteGroups
  5885. * @return array<int, array<string, mixed>>
  5886. */
  5887. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  5888. {
  5889. $names = [];
  5890. if (is_string($companiesJson) && $companiesJson !== '') {
  5891. $decoded = json_decode($companiesJson, true);
  5892. if (is_array($decoded)) {
  5893. foreach ($decoded as $nm) {
  5894. $nm = trim((string)$nm);
  5895. if ($nm !== '') {
  5896. $names[] = $nm;
  5897. }
  5898. }
  5899. }
  5900. }
  5901. $names = array_values(array_unique($names));
  5902. if ($names === [] && $selectedCompany !== '') {
  5903. $names = [$selectedCompany];
  5904. }
  5905. if ($names === []) {
  5906. return $quoteGroups;
  5907. }
  5908. $targets = [];
  5909. foreach ($quoteGroups as $g) {
  5910. if (!is_array($g)) {
  5911. continue;
  5912. }
  5913. $cn = trim((string)($g['name'] ?? ''));
  5914. if ($cn !== '' && in_array($cn, $names, true)) {
  5915. $targets[] = $g;
  5916. }
  5917. }
  5918. return $targets;
  5919. }
  5920. /**
  5921. * @return array{pos:array, merge_rows:array, bundle:array}
  5922. */
  5923. protected function loadAuditResendBundle(string $scydgyId): array
  5924. {
  5925. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5926. $pos = $bundle['pos'];
  5927. $mergeRows = $bundle['merge_rows'];
  5928. if ($pos === [] || $mergeRows === []) {
  5929. $this->error('该订单不在待确认供应商状态');
  5930. }
  5931. $sysRqDb = '';
  5932. if (isset($pos[0]) && is_array($pos[0])) {
  5933. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  5934. }
  5935. foreach ($pos as $i => $poRow) {
  5936. if (is_array($pos[$i]) && $sysRqDb !== '') {
  5937. $pos[$i]['sys_rq'] = $sysRqDb;
  5938. }
  5939. }
  5940. $bundle['pos'] = $pos;
  5941. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  5942. }
  5943. /**
  5944. * @param array<int, array<string, mixed>> $targets
  5945. */
  5946. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  5947. {
  5948. if ($targets === []) {
  5949. $this->error('未找到可通知的供应商');
  5950. }
  5951. $notifyErrors = [];
  5952. try {
  5953. $this->notifyDryRunPreview = [];
  5954. foreach ($targets as $g) {
  5955. if (!is_array($g)) {
  5956. continue;
  5957. }
  5958. $cname = trim((string)($g['name'] ?? ''));
  5959. if ($cname === '') {
  5960. continue;
  5961. }
  5962. $chosen = [
  5963. 'name' => $cname,
  5964. 'company_name' => $cname,
  5965. 'email' => trim((string)($g['email'] ?? '')),
  5966. 'phone' => trim((string)($g['phone'] ?? '')),
  5967. 'username' => trim((string)($g['username'] ?? '')),
  5968. ];
  5969. try {
  5970. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  5971. } catch (\Throwable $e) {
  5972. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5973. }
  5974. }
  5975. } catch (\Throwable $e) {
  5976. $this->error('通知发送失败:' . $e->getMessage());
  5977. }
  5978. if ($notifyErrors !== []) {
  5979. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5980. }
  5981. if ($this->isProcuremenNotifyDryRun()) {
  5982. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  5983. 'notify_dry_run' => true,
  5984. 'notify_preview' => $this->notifyDryRunPreview,
  5985. ]);
  5986. }
  5987. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  5988. }
  5989. /**
  5990. * 协助下发 — 发送短信(一家供应商)
  5991. *
  5992. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  5993. */
  5994. protected function issueSendSupplierSms(array $bundle): void
  5995. {
  5996. $companyName = (string)($bundle['company_name'] ?? '');
  5997. $phone = (string)($bundle['phone'] ?? '');
  5998. $smsContent = (string)($bundle['sms_content'] ?? '');
  5999. $this->logIssueNotifyDebug('短信', [
  6000. 'company' => $companyName,
  6001. 'phone' => $phone,
  6002. 'sms_content' => $smsContent,
  6003. ]);
  6004. if ($this->isProcuremenNotifyDryRun()) {
  6005. $this->recordNotifyDryRunPreview([
  6006. 'scene' => 'issue_sms',
  6007. 'company_name' => $companyName,
  6008. 'phone' => $phone,
  6009. 'sms_content' => $smsContent,
  6010. ]);
  6011. return;
  6012. }
  6013. $this->smsbao($phone, $smsContent);
  6014. }
  6015. /**
  6016. * 协助下发 — 发送邮件(一家供应商)
  6017. *
  6018. * @param array<string, mixed> $bundle
  6019. * @param array<string, mixed> $mailConfig
  6020. */
  6021. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  6022. {
  6023. $companyName = (string)($bundle['company_name'] ?? '');
  6024. $toEmail = (string)($bundle['email'] ?? '');
  6025. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  6026. $mailBody = (string)($bundle['mail_body'] ?? '');
  6027. $this->logIssueNotifyDebug('邮件', [
  6028. 'company' => $companyName,
  6029. 'email' => $toEmail,
  6030. 'mail_subject' => $mailSubject,
  6031. 'mail_body' => $mailPlain,
  6032. ]);
  6033. if ($this->isProcuremenNotifyDryRun()) {
  6034. $this->recordNotifyDryRunPreview([
  6035. 'scene' => 'issue_email',
  6036. 'company_name' => $companyName,
  6037. 'email' => $toEmail,
  6038. 'mail_subject' => $mailSubject,
  6039. 'mail_body' => $mailPlain,
  6040. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  6041. 'notify_vars' => $bundle['notify_vars'] ?? [],
  6042. 'detail_links' => $bundle['detail_links'] ?? [],
  6043. ]);
  6044. return;
  6045. }
  6046. $mail = new PHPMailer(true);
  6047. $mail->isSMTP();
  6048. $mail->Host = $mailConfig['host'];
  6049. $mail->SMTPAuth = true;
  6050. $mail->Username = $mailConfig['addr'];
  6051. $mail->Password = $mailConfig['pass'];
  6052. $mail->SMTPSecure = $mailConfig['security'];
  6053. $mail->Port = $mailConfig['port'];
  6054. $mail->CharSet = $mailConfig['charset'];
  6055. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  6056. $mail->addAddress($toEmail, $companyName);
  6057. $mail->isHTML(true);
  6058. $mail->Subject = $mailSubject;
  6059. $mail->Body = $mailBody;
  6060. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  6061. $sendOk = true;
  6062. $failReason = '';
  6063. try {
  6064. $mail->send();
  6065. } catch (\Throwable $e) {
  6066. $sendOk = false;
  6067. $failReason = $e->getMessage();
  6068. $this->persistEmailSendLog([
  6069. 'from_email' => $fromEmail,
  6070. 'to_email' => $toEmail,
  6071. 'send_time' => date('Y-m-d H:i:s'),
  6072. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6073. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6074. 'company_name' => $companyName,
  6075. 'mail_subject' => $mailSubject,
  6076. 'status' => 0,
  6077. 'fail_reason' => $failReason,
  6078. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6079. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6080. ]);
  6081. throw $e;
  6082. }
  6083. $this->persistEmailSendLog([
  6084. 'from_email' => $fromEmail,
  6085. 'to_email' => $toEmail,
  6086. 'send_time' => date('Y-m-d H:i:s'),
  6087. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6088. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6089. 'company_name' => $companyName,
  6090. 'mail_subject' => $mailSubject,
  6091. 'status' => 1,
  6092. 'fail_reason' => '',
  6093. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6094. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6095. ]);
  6096. }
  6097. /**
  6098. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  6099. *
  6100. * @param array<int, array<string, mixed>> $mergeRows
  6101. * @return array<string, mixed>
  6102. */
  6103. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  6104. {
  6105. $head = $mergeRows[0] ?? [];
  6106. $isMerge = count($mergeRows) > 1;
  6107. return [
  6108. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  6109. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  6110. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  6111. 'is_merge' => $isMerge,
  6112. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  6113. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  6114. 'deadline' => $sysRqNotify,
  6115. ];
  6116. }
  6117. /**
  6118. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  6119. *
  6120. * @param array<string, mixed> $data
  6121. */
  6122. protected function logIssueNotifyDebug(string $type, array $data): void
  6123. {
  6124. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  6125. return;
  6126. }
  6127. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6128. }
  6129. protected function ensurePurchaseEmailSendLogTableOnce(): void
  6130. {
  6131. try {
  6132. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  6133. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6134. return;
  6135. } catch (\Throwable $e) {
  6136. }
  6137. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  6138. if (is_file($sqlFile)) {
  6139. $sql = file_get_contents($sqlFile);
  6140. if (is_string($sql) && $sql !== '') {
  6141. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  6142. $stmt = trim($stmt);
  6143. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  6144. continue;
  6145. }
  6146. try {
  6147. Db::execute($stmt);
  6148. } catch (\Throwable $ignore) {
  6149. }
  6150. }
  6151. }
  6152. }
  6153. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6154. }
  6155. /**
  6156. * @param array<string, mixed> $row
  6157. */
  6158. protected function persistEmailSendLog(array $row): void
  6159. {
  6160. try {
  6161. $this->ensurePurchaseEmailSendLogTableOnce();
  6162. } catch (\Throwable $e) {
  6163. return;
  6164. }
  6165. list($adminId, $adminName) = $this->GetUseName();
  6166. $cut = function ($s, $max) {
  6167. $s = (string)$s;
  6168. if (function_exists('mb_substr')) {
  6169. return mb_substr($s, 0, $max, 'UTF-8');
  6170. }
  6171. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6172. };
  6173. $data = [
  6174. 'from_email' => $cut($row['from_email'] ?? '', 128),
  6175. 'to_email' => $cut($row['to_email'] ?? '', 128),
  6176. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  6177. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  6178. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  6179. 'company_name' => $cut($row['company_name'] ?? '', 128),
  6180. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6181. 'status' => !empty($row['status']) ? 1 : 0,
  6182. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6183. 'admin_id' => (int)$adminId,
  6184. 'admin_name' => $cut($adminName, 64),
  6185. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6186. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6187. 'createtime' => date('Y-m-d H:i:s'),
  6188. ];
  6189. try {
  6190. Db::table('purchase_email_send_log')->insert($data);
  6191. } catch (\Throwable $e) {
  6192. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6193. }
  6194. }
  6195. protected function formatEmailLogSceneText(string $scene): string
  6196. {
  6197. $map = [
  6198. 'pick_issue' => '初选下发',
  6199. 'audit_resend' => '确认页重发',
  6200. ];
  6201. return $map[$scene] ?? $scene;
  6202. }
  6203. /**
  6204. * 邮件发送日志列表
  6205. */
  6206. public function emailLog()
  6207. {
  6208. $this->relationSearch = false;
  6209. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6210. $this->request->filter(['strip_tags', 'trim']);
  6211. $bakModel = $this->model;
  6212. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6213. if ($this->request->isAjax()) {
  6214. $this->ensurePurchaseEmailSendLogTableOnce();
  6215. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6216. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6217. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6218. $list = $this->model
  6219. ->where($where)
  6220. ->order($sortField, $orderDir)
  6221. ->paginate($limit);
  6222. $rows = [];
  6223. foreach ($list->items() as $item) {
  6224. $row = is_array($item) ? $item : $item->toArray();
  6225. $scene = trim((string)($row['scene'] ?? ''));
  6226. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6227. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6228. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6229. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6230. $rows[] = $row;
  6231. }
  6232. $this->model = $bakModel;
  6233. return json(['total' => $list->total(), 'rows' => $rows]);
  6234. }
  6235. $this->model = $bakModel;
  6236. return $this->view->fetch('procuremen/emaillog');
  6237. }
  6238. /**
  6239. * 协助下发弹窗(选多家供应商并通知)
  6240. */
  6241. public function pickReview()
  6242. {
  6243. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6244. $this->error(__('You have no permission'));
  6245. }
  6246. if ($this->request->isPost()) {
  6247. $this->error('请使用弹窗内「确认下发」提交');
  6248. }
  6249. $this->view->assign('pickMode', 1);
  6250. return $this->view->fetch('procuremen/review');
  6251. }
  6252. /**
  6253. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6254. */
  6255. public function add()
  6256. {
  6257. if ($this->request->isPost()) {
  6258. $params = $this->request->post('row/a');
  6259. if (!is_array($params)) {
  6260. $this->error(__('Parameter %s can not be empty', ''));
  6261. }
  6262. [, $adminName] = $this->GetUseName();
  6263. $params['cywyxm'] = $adminName;
  6264. try {
  6265. $sid = $this->saveManualPickOrder($params);
  6266. } catch (\InvalidArgumentException $e) {
  6267. $this->error($e->getMessage());
  6268. } catch (\Throwable $e) {
  6269. $this->error($e->getMessage());
  6270. }
  6271. $this->success('新增成功', '', [
  6272. 'scydgy_id' => $sid,
  6273. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  6274. ]);
  6275. }
  6276. [, $adminName] = $this->GetUseName();
  6277. $this->view->assign('adminNickname', $adminName);
  6278. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6279. $this->view->assign('defaultCclbmmc', '营销中心');
  6280. return $this->view->fetch();
  6281. }
  6282. /**
  6283. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6284. */
  6285. public function rfqlist()
  6286. {
  6287. $this->relationSearch = false;
  6288. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6289. $this->request->filter(['strip_tags', 'trim']);
  6290. if ($this->request->isAjax()) {
  6291. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6292. $limit = max(10, min(500, (int)$limit));
  6293. $applyFilters = function ($query) use ($where) {
  6294. $query->where('scydgy_id', '<', 0);
  6295. $query->whereRaw(
  6296. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6297. );
  6298. if (!$this->auth->isSuperAdmin()) {
  6299. [, $adminName] = $this->GetUseName();
  6300. $query->where('cywyxm', $adminName);
  6301. }
  6302. if (!empty($where)) {
  6303. $query->where($where);
  6304. }
  6305. };
  6306. $countQuery = Db::table('purchase_order');
  6307. $applyFilters($countQuery);
  6308. $total = (int)$countQuery->count();
  6309. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6310. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6311. $listQuery = Db::table('purchase_order');
  6312. $applyFilters($listQuery);
  6313. $rows = $listQuery
  6314. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6315. ->order($sortField, $orderDir)
  6316. ->limit($offset, $limit)
  6317. ->select();
  6318. if (!is_array($rows)) {
  6319. $rows = [];
  6320. }
  6321. $out = [];
  6322. foreach ($rows as $r) {
  6323. if (!is_array($r)) {
  6324. continue;
  6325. }
  6326. $sid = (int)($r['scydgy_id'] ?? 0);
  6327. if ($sid >= 0) {
  6328. continue;
  6329. }
  6330. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6331. if ($createdText === '') {
  6332. $createdText = trim((string)($r['dStamp'] ?? ''));
  6333. }
  6334. $out[] = [
  6335. 'id' => (int)($r['id'] ?? 0),
  6336. 'scydgy_id' => $sid,
  6337. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6338. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6339. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6340. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6341. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6342. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6343. 'createtime' => $r['createtime'] ?? null,
  6344. 'createtime_text' => $createdText,
  6345. ];
  6346. }
  6347. return json(['total' => $total, 'rows' => $out]);
  6348. }
  6349. [, $adminName] = $this->GetUseName();
  6350. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6351. $this->view->assign('adminNickname', $adminName);
  6352. return $this->view->fetch('procuremen/rfqlist');
  6353. }
  6354. /**
  6355. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6356. */
  6357. public function rfqlistDetails()
  6358. {
  6359. return $this->details();
  6360. }
  6361. /**
  6362. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6363. */
  6364. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6365. {
  6366. if ($scydgyId >= 0) {
  6367. return;
  6368. }
  6369. try {
  6370. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6371. } catch (\Throwable $e) {
  6372. $po = null;
  6373. }
  6374. if (!is_array($po)) {
  6375. $this->error('订单不存在');
  6376. }
  6377. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6378. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6379. $this->error('订单不存在');
  6380. }
  6381. if ($this->auth->isSuperAdmin()) {
  6382. return;
  6383. }
  6384. [, $adminName] = $this->GetUseName();
  6385. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6386. if ($cywy !== '' && $cywy === $adminName) {
  6387. return;
  6388. }
  6389. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6390. try {
  6391. if ($this->auth->check($rule)) {
  6392. return;
  6393. }
  6394. } catch (\Throwable $e) {
  6395. }
  6396. }
  6397. $this->error('无权查看该订单');
  6398. }
  6399. /**
  6400. * 手工新增协助工序进度文案
  6401. */
  6402. protected function formatProcuremenRfqProgressText(array $row): string
  6403. {
  6404. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6405. return ProcuremenStatus::PO_COMPLETED;
  6406. }
  6407. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6408. return '待采购确认';
  6409. }
  6410. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6411. return '待确认供应商';
  6412. }
  6413. $sid = (int)($row['scydgy_id'] ?? 0);
  6414. if ($sid < 0) {
  6415. try {
  6416. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6417. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6418. $detCnt = (int)$detCntQuery->count();
  6419. if ($detCnt > 0) {
  6420. return '已下发待确认';
  6421. }
  6422. } catch (\Throwable $e) {
  6423. }
  6424. }
  6425. return '待协助下发';
  6426. }
  6427. /**
  6428. * 协助初选列表 — 批量软删除
  6429. */
  6430. public function pickDelete()
  6431. {
  6432. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6433. $this->error(__('Invalid parameters'));
  6434. }
  6435. if (!$this->procuremenCanPickDelete()) {
  6436. $this->error(__('You have no permission'));
  6437. }
  6438. $rowsRaw = $this->request->post('rows_json', '[]');
  6439. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6440. if (!is_array($rows) || $rows === []) {
  6441. $this->error('请至少勾选一条工序');
  6442. }
  6443. $done = 0;
  6444. Db::startTrans();
  6445. try {
  6446. foreach ($rows as $row) {
  6447. if (!is_array($row)) {
  6448. continue;
  6449. }
  6450. $this->softDeleteProcuremenPickRow($row);
  6451. $done++;
  6452. }
  6453. if ($done < 1) {
  6454. throw new \Exception('没有可删除的工序');
  6455. }
  6456. Db::commit();
  6457. } catch (\InvalidArgumentException $e) {
  6458. Db::rollback();
  6459. $this->error($e->getMessage());
  6460. } catch (\Throwable $e) {
  6461. Db::rollback();
  6462. $this->error($e->getMessage());
  6463. }
  6464. $this->pickHiddenScydgySetCache = null;
  6465. $this->success('已删除 ' . $done . ' 条工序');
  6466. }
  6467. /**
  6468. * 下发 — 手工新增工序(弹窗)
  6469. */
  6470. public function pickAdd()
  6471. {
  6472. if ($this->request->isPost()) {
  6473. $params = $this->request->post('row/a');
  6474. if (!is_array($params)) {
  6475. $this->error(__('Parameter %s can not be empty', ''));
  6476. }
  6477. try {
  6478. $sid = $this->saveManualPickOrder($params);
  6479. } catch (\InvalidArgumentException $e) {
  6480. $this->error($e->getMessage());
  6481. } catch (\Throwable $e) {
  6482. $this->error($e->getMessage());
  6483. }
  6484. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6485. }
  6486. return $this->view->fetch('procuremen/pick_add');
  6487. }
  6488. /**
  6489. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  6490. */
  6491. public function pickSubmit()
  6492. {
  6493. if (!$this->request->isPost()) {
  6494. $this->error(__('Invalid parameters'));
  6495. }
  6496. // ---------- 接口订单数据 ----------
  6497. $rowJson = $this->request->post('row_json', '');
  6498. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  6499. $companiesJson = $this->request->post('companies_json', '[]');
  6500. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  6501. $companies = json_decode($companiesJson, true);
  6502. if (!is_array($companies)) {
  6503. $this->error('供应商数据无效');
  6504. }
  6505. $issueCompanies = $this->normalizePickCompanies($companies);
  6506. if ($issueCompanies === []) {
  6507. $this->error('请至少选择一家合作供应商');
  6508. }
  6509. $issueNameLabels = [];
  6510. foreach ($issueCompanies as $pc) {
  6511. $issueNameLabels[] = $pc['name'];
  6512. }
  6513. $issueNamesSummary = implode('、', $issueNameLabels);
  6514. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  6515. if ($sysRq === '') {
  6516. $this->error('请选择截止时间');
  6517. }
  6518. $sysRqTs = strtotime($sysRq);
  6519. if ($sysRqTs === false || $sysRqTs <= 0) {
  6520. $this->error('截止时间格式无效');
  6521. }
  6522. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  6523. $isMerge = count($mergeRows) > 1;
  6524. $ccydhLog = '';
  6525. foreach ($mergeRows as $row) {
  6526. if (!is_array($row)) {
  6527. continue;
  6528. }
  6529. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  6530. if ($ccydhLog !== '') {
  6531. break;
  6532. }
  6533. }
  6534. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  6535. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6536. $logMsg = '下发' . $orderPart . $procPart
  6537. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  6538. $issueTime = date('Y-m-d H:i:s');
  6539. $logSidList = [];
  6540. foreach ($mergeRows as $row) {
  6541. if (!is_array($row)) {
  6542. continue;
  6543. }
  6544. $sid = $this->extractScydgyRowId($row);
  6545. if ($this->isValidScydgyRowId($sid)) {
  6546. $logSidList[$sid] = true;
  6547. }
  6548. }
  6549. $existingBySid = [];
  6550. if ($logSidList !== []) {
  6551. try {
  6552. $existingRows = Db::table('purchase_order')
  6553. ->where('scydgy_id', 'in', array_keys($logSidList))
  6554. ->select();
  6555. if (is_array($existingRows)) {
  6556. foreach ($existingRows as $poRow) {
  6557. if (!is_array($poRow)) {
  6558. continue;
  6559. }
  6560. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6561. if ($this->isValidScydgyRowId($sid)) {
  6562. $existingBySid[$sid] = $poRow;
  6563. }
  6564. }
  6565. }
  6566. } catch (\Throwable $e) {
  6567. $existingBySid = [];
  6568. }
  6569. }
  6570. Db::startTrans();
  6571. try {
  6572. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  6573. foreach ($mergeRows as $row) {
  6574. if (!is_array($row)) {
  6575. continue;
  6576. }
  6577. $sid = $this->extractScydgyRowId($row);
  6578. $this->upsertPurchaseOrderFromRow(
  6579. $row,
  6580. $sysRqDb,
  6581. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6582. $issueTime,
  6583. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  6584. );
  6585. }
  6586. foreach ($issueCompanies as $c) {
  6587. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  6588. }
  6589. Db::commit();
  6590. } catch (\Throwable $e) {
  6591. Db::rollback();
  6592. $this->error($e->getMessage());
  6593. }
  6594. $poIdBySid = [];
  6595. if ($logSidList !== []) {
  6596. try {
  6597. $poIdBySid = Db::table('purchase_order')
  6598. ->where('scydgy_id', 'in', array_keys($logSidList))
  6599. ->column('id', 'scydgy_id');
  6600. } catch (\Throwable $e) {
  6601. $poIdBySid = [];
  6602. }
  6603. }
  6604. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  6605. if ($logSidList !== []) {
  6606. list($adminId, $adminName) = $this->GetUseName();
  6607. $cut = function ($s, $max) {
  6608. if (function_exists('mb_substr')) {
  6609. return mb_substr($s, 0, $max, 'UTF-8');
  6610. }
  6611. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6612. };
  6613. $logRows = [];
  6614. $seenLogSid = [];
  6615. foreach ($mergeRows as $row) {
  6616. if (!is_array($row)) {
  6617. continue;
  6618. }
  6619. $ids = $this->extractScydgyRowId($row);
  6620. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  6621. continue;
  6622. }
  6623. $seenLogSid[$ids] = true;
  6624. $poIdLog = null;
  6625. if (isset($poIdBySid[$ids])) {
  6626. $tid = (int)$poIdBySid[$ids];
  6627. $poIdLog = $tid > 0 ? $tid : null;
  6628. }
  6629. $logRows[] = [
  6630. 'scydgy_id' => $ids,
  6631. 'purchase_order_id' => $poIdLog,
  6632. 'admin_id' => $adminId,
  6633. 'admin_name' => $cut($adminName, 64),
  6634. 'action' => $cut('issue_submit', 64),
  6635. 'content' => $cut($logMsg, 1000),
  6636. 'createtime' => ProcuremenTime::nowDateTime(),
  6637. ];
  6638. }
  6639. if ($logRows !== []) {
  6640. try {
  6641. Db::table('purchase_order_oper_log')->insertAll($logRows);
  6642. } catch (\Throwable $e) {
  6643. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  6644. }
  6645. }
  6646. }
  6647. $notifyErrors = [];
  6648. $posNotify = [];
  6649. if ($logSidList !== []) {
  6650. try {
  6651. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  6652. } catch (\Throwable $e) {
  6653. $posNotify = [];
  6654. }
  6655. }
  6656. if (!is_array($posNotify)) {
  6657. $posNotify = [];
  6658. }
  6659. foreach ($posNotify as $i => $prow) {
  6660. if (is_array($posNotify[$i])) {
  6661. $posNotify[$i]['sys_rq'] = $sysRqDb;
  6662. }
  6663. }
  6664. $ccydhPick = '';
  6665. foreach ($mergeRows as $row) {
  6666. if (!is_array($row)) {
  6667. continue;
  6668. }
  6669. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  6670. if ($ccydhPick !== '') {
  6671. break;
  6672. }
  6673. }
  6674. $notifyBundleBase = [
  6675. 'ccydh' => $ccydhPick,
  6676. 'pos' => $posNotify,
  6677. 'merge_rows' => $mergeRows,
  6678. ];
  6679. try {
  6680. $this->notifyDryRunPreview = [];
  6681. foreach ($issueCompanies as $c) {
  6682. if (!is_array($c)) {
  6683. continue;
  6684. }
  6685. $cname = trim((string)($c['name'] ?? ''));
  6686. if ($cname === '') {
  6687. continue;
  6688. }
  6689. try {
  6690. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  6691. } catch (\Throwable $e) {
  6692. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6693. }
  6694. }
  6695. } catch (\Throwable $e) {
  6696. $this->error('通知发送失败:' . $e->getMessage());
  6697. }
  6698. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  6699. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6700. }
  6701. if ($this->isProcuremenNotifyDryRun()) {
  6702. $this->success('【演练模式】已保存并生成通知预览', '', [
  6703. 'notify_dry_run' => true,
  6704. 'notify_preview' => $this->notifyDryRunPreview,
  6705. ]);
  6706. }
  6707. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  6708. }
  6709. /**
  6710. * 确认供应商弹窗
  6711. */
  6712. public function auditIssue()
  6713. {
  6714. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6715. if (is_array($ids)) {
  6716. $ids = isset($ids[0]) ? $ids[0] : '';
  6717. }
  6718. $ids = trim((string)$ids);
  6719. if ($ids === '') {
  6720. $this->error(__('Invalid parameters'));
  6721. }
  6722. if ($this->request->isPost()) {
  6723. $this->error('请使用弹窗内「确认」提交');
  6724. }
  6725. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  6726. $pos = $bundle['pos'];
  6727. if ($pos === []) {
  6728. $this->error('该订单不在待确认供应商状态');
  6729. }
  6730. $po = $pos[0];
  6731. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6732. if ($quoteGroups === []) {
  6733. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  6734. }
  6735. $pickedName = '';
  6736. foreach ($pos as $poRow) {
  6737. if (!is_array($poRow)) {
  6738. continue;
  6739. }
  6740. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6741. if ($pn !== '') {
  6742. $pickedName = $pn;
  6743. break;
  6744. }
  6745. }
  6746. $this->view->assign('po', $po);
  6747. $this->view->assign('scydgyId', $ids);
  6748. $this->view->assign('orderCcydh', $bundle['ccydh']);
  6749. $mergeRows = $bundle['merge_rows'];
  6750. $this->view->assign('processRows', $mergeRows);
  6751. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  6752. $this->view->assign('processCount', count($mergeRows));
  6753. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  6754. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  6755. $this->view->assign('pickedCompanyName', $pickedName);
  6756. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  6757. if ($sysRqForView === '') {
  6758. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6759. }
  6760. $this->view->assign('sysRq', $sysRqForView);
  6761. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  6762. $this->view->assign('quoteDeadlineReached', $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0);
  6763. return $this->view->fetch('procuremen/audit_issue');
  6764. }
  6765. /**
  6766. * 开标双重验证 — 可选验证人列表
  6767. */
  6768. public function bidOpenUsers()
  6769. {
  6770. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6771. $this->error('无权限');
  6772. }
  6773. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  6774. if ($scydgyId !== '') {
  6775. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6776. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6777. $this->success('已完成开标验证', null, [
  6778. 'verified' => 1,
  6779. 'users' => [],
  6780. ]);
  6781. }
  6782. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6783. }
  6784. $this->success('', null, [
  6785. 'verified' => 0,
  6786. 'users' => $this->listBidOpenVerifierCandidates(),
  6787. ]);
  6788. }
  6789. /**
  6790. * 开标双重验证 — 向指定管理员发送短信验证码
  6791. */
  6792. public function bidOpenSendCode()
  6793. {
  6794. if (!$this->request->isPost()) {
  6795. $this->error(__('Invalid parameters'));
  6796. }
  6797. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6798. $this->error('无权限');
  6799. }
  6800. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6801. $adminId = (int)$this->request->post('admin_id', 0);
  6802. if ($scydgyId === '' || $adminId <= 0) {
  6803. $this->error('参数无效');
  6804. }
  6805. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6806. if ($bundle['pos'] === []) {
  6807. $this->error('该订单不在待确认供应商状态');
  6808. }
  6809. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6810. $this->success('已完成开标验证,无需重复发送');
  6811. }
  6812. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6813. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6814. if ($ccydh === '') {
  6815. $this->error('订单号无效');
  6816. }
  6817. $admin = $this->loadBidOpenAdminUser($adminId);
  6818. if ($admin === null) {
  6819. $this->error('验证人无效或未绑定手机号');
  6820. }
  6821. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  6822. $cd = max(30, min(120, $cd));
  6823. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  6824. $this->error('发送过于频繁,请稍后再试');
  6825. }
  6826. $code = (string)random_int(100000, 999999);
  6827. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  6828. $ttl = max(60, min(600, $ttl));
  6829. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  6830. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  6831. try {
  6832. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  6833. } catch (\Throwable $e) {
  6834. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  6835. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  6836. $this->error($e->getMessage());
  6837. }
  6838. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  6839. }
  6840. /**
  6841. * 开标双重验证 — 两人验证码校验并记录
  6842. */
  6843. public function bidOpenVerify()
  6844. {
  6845. if (!$this->request->isPost()) {
  6846. $this->error(__('Invalid parameters'));
  6847. }
  6848. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6849. $this->error('无权限');
  6850. }
  6851. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6852. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  6853. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  6854. $code1 = trim((string)$this->request->post('code1', ''));
  6855. $code2 = trim((string)$this->request->post('code2', ''));
  6856. if ($scydgyId === '') {
  6857. $this->error('参数无效');
  6858. }
  6859. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  6860. $this->error('请选择两位验证人');
  6861. }
  6862. if ($verifier1Id === $verifier2Id) {
  6863. $this->error('两位验证人不能相同');
  6864. }
  6865. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  6866. $this->error('请输入6位短信验证码');
  6867. }
  6868. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6869. if ($bundle['pos'] === []) {
  6870. $this->error('该订单不在待确认供应商状态');
  6871. }
  6872. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6873. if ($ccydh === '') {
  6874. $this->error('订单号无效');
  6875. }
  6876. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6877. $this->success('已完成开标验证');
  6878. }
  6879. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6880. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  6881. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  6882. if ($verifier1 === null || $verifier2 === null) {
  6883. $this->error('验证人无效或未绑定手机号');
  6884. }
  6885. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  6886. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  6887. }
  6888. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  6889. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  6890. }
  6891. try {
  6892. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  6893. } catch (\Throwable $e) {
  6894. $this->error($e->getMessage());
  6895. }
  6896. $this->success('开标验证成功,可查看供应商报价与交货日期');
  6897. }
  6898. /**
  6899. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  6900. */
  6901. public function auditSubmit()
  6902. {
  6903. if (!$this->request->isPost()) {
  6904. $this->error(__('Invalid parameters'));
  6905. }
  6906. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6907. if ($scydgyId === '') {
  6908. $this->error('参数无效');
  6909. }
  6910. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6911. $pos = $bundle['pos'];
  6912. $mergeRows = $bundle['merge_rows'];
  6913. if ($pos === [] || $mergeRows === []) {
  6914. $this->error('该订单不在待确认供应商状态');
  6915. }
  6916. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6917. if ($quoteGroups === []) {
  6918. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  6919. }
  6920. $companyName = trim((string)$this->request->post('selected_company', ''));
  6921. if ($companyName === '') {
  6922. $this->error('请选择一家供应商');
  6923. }
  6924. $matched = null;
  6925. foreach ($quoteGroups as $g) {
  6926. if (!is_array($g)) {
  6927. continue;
  6928. }
  6929. if (trim((string)($g['name'] ?? '')) === $companyName) {
  6930. $matched = $g;
  6931. break;
  6932. }
  6933. }
  6934. if ($matched === null) {
  6935. $this->error('所选供应商不在本单报价列表中');
  6936. }
  6937. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6938. if ($sysRqDb === '') {
  6939. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  6940. } else {
  6941. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true);
  6942. }
  6943. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6944. $this->error('请先完成开标双重验证后再确认供应商');
  6945. }
  6946. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  6947. $procCnt = count($mergeRows);
  6948. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6949. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  6950. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  6951. Db::startTrans();
  6952. try {
  6953. foreach ($pos as $poRow) {
  6954. if (!is_array($poRow)) {
  6955. continue;
  6956. }
  6957. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6958. if (!$this->isValidScydgyRowId($sid)) {
  6959. continue;
  6960. }
  6961. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  6962. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  6963. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6964. 'pick_company_name' => $companyName,
  6965. 'sys_rq' => $sysRqDb,
  6966. ]);
  6967. }
  6968. Db::commit();
  6969. } catch (\Throwable $e) {
  6970. Db::rollback();
  6971. $this->error($e->getMessage());
  6972. }
  6973. foreach ($pos as $poRow) {
  6974. if (!is_array($poRow)) {
  6975. continue;
  6976. }
  6977. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6978. if (!$this->isValidScydgyRowId($sid)) {
  6979. continue;
  6980. }
  6981. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6982. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6983. }
  6984. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  6985. }
  6986. /**
  6987. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  6988. */
  6989. public function auditResendSms()
  6990. {
  6991. if (!$this->request->isPost()) {
  6992. $this->error(__('Invalid parameters'));
  6993. }
  6994. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6995. if ($scydgyId === '') {
  6996. $this->error('参数无效');
  6997. }
  6998. $loaded = $this->loadAuditResendBundle($scydgyId);
  6999. $mergeRows = $loaded['merge_rows'];
  7000. $bundle = $loaded['bundle'];
  7001. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7002. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7003. if ($quoteGroups === []) {
  7004. $this->error('暂无可通知的供应商');
  7005. }
  7006. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7007. $companiesJson = (string)$this->request->post('companies_json', '');
  7008. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7009. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  7010. }
  7011. /**
  7012. * 确认供应商 — 二次发送邮件(可选单家/批量)
  7013. */
  7014. public function auditResendEmail()
  7015. {
  7016. if (!$this->request->isPost()) {
  7017. $this->error(__('Invalid parameters'));
  7018. }
  7019. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7020. if ($scydgyId === '') {
  7021. $this->error('参数无效');
  7022. }
  7023. $loaded = $this->loadAuditResendBundle($scydgyId);
  7024. $mergeRows = $loaded['merge_rows'];
  7025. $bundle = $loaded['bundle'];
  7026. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7027. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7028. if ($quoteGroups === []) {
  7029. $this->error('暂无可通知的供应商');
  7030. }
  7031. $companiesJson = (string)$this->request->post('companies_json', '');
  7032. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7033. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7034. if ($companiesJson === '' && $selectedCompany === '') {
  7035. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  7036. }
  7037. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  7038. }
  7039. /**
  7040. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  7041. *
  7042. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  7043. * @return array<int, true> 已处理的 scydgy_id 集合
  7044. */
  7045. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  7046. {
  7047. $pos = $bundle['pos'] ?? [];
  7048. if (!is_array($pos) || $pos === []) {
  7049. return [];
  7050. }
  7051. $sids = [];
  7052. foreach ($pos as $poRow) {
  7053. if (!is_array($poRow)) {
  7054. continue;
  7055. }
  7056. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7057. if ($this->isValidScydgyRowId($sid)) {
  7058. $sids[$sid] = true;
  7059. }
  7060. }
  7061. if ($sids === []) {
  7062. return [];
  7063. }
  7064. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7065. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  7066. $suffix = trim((string)$logSuffix, ',, ');
  7067. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  7068. $logMsg .= ':从历史存证退回协助初选';
  7069. } else {
  7070. $logMsg .= ':退回协助初选';
  7071. }
  7072. Db::table('purchase_order')
  7073. ->where('scydgy_id', 'in', array_keys($sids))
  7074. ->update([
  7075. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  7076. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7077. 'pick_company_name' => '',
  7078. 'pick_time' => null,
  7079. 'sys_rq' => null,
  7080. 'mod_rq' => null,
  7081. ]);
  7082. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  7083. foreach (array_keys($sids) as $sid) {
  7084. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  7085. }
  7086. return $sids;
  7087. }
  7088. /**
  7089. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  7090. *
  7091. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  7092. */
  7093. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  7094. {
  7095. $scydgyId = trim($scydgyId);
  7096. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7097. if ($scydgyId === '') {
  7098. return $empty;
  7099. }
  7100. try {
  7101. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7102. } catch (\Throwable $e) {
  7103. $anchor = null;
  7104. }
  7105. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  7106. return $empty;
  7107. }
  7108. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7109. if ($ccydh === '') {
  7110. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  7111. }
  7112. try {
  7113. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7114. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7115. $pos = $query->order('scydgy_id', 'asc')->select();
  7116. } catch (\Throwable $e) {
  7117. $pos = [$anchor];
  7118. }
  7119. if (!is_array($pos) || $pos === []) {
  7120. $pos = [$anchor];
  7121. }
  7122. return [
  7123. 'ccydh' => $ccydh,
  7124. 'pos' => $pos,
  7125. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7126. ];
  7127. }
  7128. protected function purchaseOrderRowIsCompleted(array $po): bool
  7129. {
  7130. $st = $po['status'] ?? null;
  7131. if ($st === 1 || $st === '1') {
  7132. return true;
  7133. }
  7134. if (is_string($st) && trim($st) === '1') {
  7135. return true;
  7136. }
  7137. return is_numeric($st) && (int)$st === 1;
  7138. }
  7139. /**
  7140. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  7141. */
  7142. public function auditAbandon()
  7143. {
  7144. if (!$this->request->isPost()) {
  7145. $this->error(__('Invalid parameters'));
  7146. }
  7147. $anchorIds = [];
  7148. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7149. if ($batchRaw !== '') {
  7150. $decoded = json_decode($batchRaw, true);
  7151. if (is_array($decoded)) {
  7152. foreach ($decoded as $id) {
  7153. $s = trim((string)$id);
  7154. if ($s !== '') {
  7155. $anchorIds[] = $s;
  7156. }
  7157. }
  7158. }
  7159. }
  7160. if ($anchorIds === []) {
  7161. $single = trim((string)$this->request->post('scydgy_id', ''));
  7162. if ($single !== '') {
  7163. $anchorIds[] = $single;
  7164. }
  7165. }
  7166. if ($anchorIds === []) {
  7167. $this->error('请至少选择一条订单');
  7168. }
  7169. $processedCcydh = [];
  7170. $doneOrders = 0;
  7171. $allSids = [];
  7172. Db::startTrans();
  7173. try {
  7174. foreach ($anchorIds as $anchorId) {
  7175. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  7176. if (($bundle['pos'] ?? []) === []) {
  7177. continue;
  7178. }
  7179. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7180. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7181. if (isset($processedCcydh[$dedupeKey])) {
  7182. continue;
  7183. }
  7184. $processedCcydh[$dedupeKey] = true;
  7185. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  7186. if ($sids === []) {
  7187. continue;
  7188. }
  7189. $doneOrders++;
  7190. foreach (array_keys($sids) as $sid) {
  7191. $allSids[(int)$sid] = true;
  7192. }
  7193. }
  7194. if ($doneOrders < 1) {
  7195. throw new \Exception('所选订单均不在待确认供应商状态');
  7196. }
  7197. Db::commit();
  7198. } catch (\Throwable $e) {
  7199. Db::rollback();
  7200. $this->error($e->getMessage());
  7201. }
  7202. $this->pickHiddenScydgySetCache = null;
  7203. $msg = $doneOrders > 1
  7204. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7205. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7206. $this->success($msg);
  7207. }
  7208. /**
  7209. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7210. */
  7211. public function archiveAbandon()
  7212. {
  7213. if (!$this->request->isPost()) {
  7214. $this->error(__('Invalid parameters'));
  7215. }
  7216. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7217. $this->error(__('You have no permission'));
  7218. }
  7219. $anchorIds = [];
  7220. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7221. if ($batchRaw !== '') {
  7222. $decoded = json_decode($batchRaw, true);
  7223. if (is_array($decoded)) {
  7224. foreach ($decoded as $id) {
  7225. $s = trim((string)$id);
  7226. if ($s !== '') {
  7227. $anchorIds[] = $s;
  7228. }
  7229. }
  7230. }
  7231. }
  7232. if ($anchorIds === []) {
  7233. $single = trim((string)$this->request->post('scydgy_id', ''));
  7234. if ($single !== '') {
  7235. $anchorIds[] = $single;
  7236. }
  7237. }
  7238. if ($anchorIds === []) {
  7239. $this->error('请至少选择一条订单');
  7240. }
  7241. $processedCcydh = [];
  7242. $doneOrders = 0;
  7243. Db::startTrans();
  7244. try {
  7245. foreach ($anchorIds as $anchorId) {
  7246. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7247. if (($bundle['pos'] ?? []) === []) {
  7248. continue;
  7249. }
  7250. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7251. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7252. if (isset($processedCcydh[$dedupeKey])) {
  7253. continue;
  7254. }
  7255. $processedCcydh[$dedupeKey] = true;
  7256. $sids = $this->abandonOrderBundleToPick(
  7257. $bundle,
  7258. 'archive_abandon',
  7259. ',从历史存证退回协助初选'
  7260. );
  7261. if ($sids === []) {
  7262. continue;
  7263. }
  7264. $doneOrders++;
  7265. }
  7266. if ($doneOrders < 1) {
  7267. throw new \Exception('所选订单均不是已完结状态');
  7268. }
  7269. Db::commit();
  7270. } catch (\Throwable $e) {
  7271. Db::rollback();
  7272. $this->error($e->getMessage());
  7273. }
  7274. $this->pickHiddenScydgySetCache = null;
  7275. $msg = $doneOrders > 1
  7276. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  7277. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7278. $this->success($msg);
  7279. }
  7280. /**
  7281. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  7282. */
  7283. public function purchaseApprovalReject()
  7284. {
  7285. if (!$this->request->isPost() || !$this->request->isAjax()) {
  7286. $this->error(__('Invalid parameters'));
  7287. }
  7288. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  7289. $this->error(__('You have no permission'));
  7290. }
  7291. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  7292. $decoded = json_decode($batchRaw, true);
  7293. if (!is_array($decoded) || $decoded === []) {
  7294. $this->error('提交数据无效');
  7295. }
  7296. $done = 0;
  7297. Db::startTrans();
  7298. try {
  7299. foreach ($decoded as $item) {
  7300. if (!is_array($item)) {
  7301. continue;
  7302. }
  7303. $sid = (int)($item['scydgy_id'] ?? 0);
  7304. if (!$this->isValidScydgyRowId($sid)) {
  7305. continue;
  7306. }
  7307. $this->runPurchaseApprovalRejectForSid($sid);
  7308. $done++;
  7309. }
  7310. if ($done < 1) {
  7311. throw new \Exception('所选订单均不在待审批状态');
  7312. }
  7313. Db::commit();
  7314. } catch (\Throwable $e) {
  7315. Db::rollback();
  7316. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  7317. }
  7318. $this->pickHiddenScydgySetCache = null;
  7319. $this->success('已驳回并退回「协助审批下发」');
  7320. }
  7321. /**
  7322. * @throws \Exception
  7323. */
  7324. protected function runPurchaseApprovalRejectForSid(int $sid): void
  7325. {
  7326. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  7327. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  7328. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  7329. $allIds = $this->purchaseOrderDetail($sid);
  7330. if ($allIds === []) {
  7331. throw new \Exception('未找到下发明细');
  7332. }
  7333. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7334. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7335. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7336. 'pick_company_name' => '',
  7337. ]);
  7338. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  7339. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  7340. $poId = 0;
  7341. try {
  7342. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  7343. if (is_array($po)) {
  7344. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7345. }
  7346. } catch (\Throwable $e) {
  7347. }
  7348. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  7349. }
  7350. /**
  7351. * 审核弹窗(旧入口,POST 已关闭)
  7352. */
  7353. public function review()
  7354. {
  7355. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  7356. $this->error(__('You have no permission'));
  7357. }
  7358. if ($this->request->isPost()) {
  7359. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  7360. }
  7361. $this->view->assign('pickMode', 0);
  7362. return $this->view->fetch('procuremen/review');
  7363. }
  7364. /**
  7365. * 审核弹窗获取公司列表
  7366. */
  7367. public function reviewCompanies()
  7368. {
  7369. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review'])) {
  7370. $this->error(__('You have no permission'));
  7371. }
  7372. if (!$this->request->isAjax()) {
  7373. $this->error(__('Invalid parameters'));
  7374. }
  7375. $list = [];
  7376. try {
  7377. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  7378. $rows = Db::table('customer')
  7379. ->where(function ($q) {
  7380. $q->where('status', 1)
  7381. ->whereOr('status', '1')
  7382. ->whereOr('status', '')
  7383. ->whereNull('status');
  7384. })
  7385. ->order('id', 'desc')
  7386. ->select();
  7387. } catch (\Throwable $e) {
  7388. $this->success('', '', []);
  7389. return;
  7390. }
  7391. if (!is_array($rows)) {
  7392. $this->success('', '', []);
  7393. return;
  7394. }
  7395. $detailColCandidates = [
  7396. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  7397. 'company_detail', 'company_desc', 'address',
  7398. ];
  7399. foreach ($rows as $row) {
  7400. if (!is_array($row)) {
  7401. continue;
  7402. }
  7403. $norm = [];
  7404. foreach ($row as $k => $v) {
  7405. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7406. }
  7407. $row = $norm;
  7408. $st = $row['status'] ?? '';
  7409. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7410. continue;
  7411. }
  7412. $payload = $this->buildCustomerContactPayloadFromRow($row);
  7413. if ($payload === null) {
  7414. continue;
  7415. }
  7416. $detail = '';
  7417. foreach ($detailColCandidates as $dk) {
  7418. if (!isset($row[$dk])) {
  7419. continue;
  7420. }
  7421. $dv = trim((string)$row[$dk]);
  7422. if ($dv !== '') {
  7423. $detail = $dv;
  7424. break;
  7425. }
  7426. }
  7427. $payload['detail'] = $detail;
  7428. $list[] = $this->maskSupplierContactFields($payload);
  7429. }
  7430. $this->success('', '', $list);
  7431. }
  7432. /**
  7433. * 采购确认-下发明细弹窗:
  7434. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  7435. */
  7436. public function outward_detail()
  7437. {
  7438. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7439. if (is_array($ids)) {
  7440. $ids = isset($ids[0]) ? $ids[0] : '';
  7441. }
  7442. $ids = trim((string)$ids);
  7443. if ($ids === '') {
  7444. $this->error(__('Invalid parameters'));
  7445. }
  7446. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  7447. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  7448. $wffTab = 'all';
  7449. }
  7450. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  7451. $purchaseOrderId = 0;
  7452. $po = null;
  7453. try {
  7454. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7455. if (is_array($po)) {
  7456. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7457. }
  7458. } catch (\Throwable $e) {
  7459. $purchaseOrderId = 0;
  7460. $po = null;
  7461. }
  7462. if (!$isPurchaseConfirm && is_array($po)) {
  7463. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  7464. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  7465. $isPurchaseConfirm = true;
  7466. }
  7467. }
  7468. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  7469. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7470. $confirmProcessCount = 1;
  7471. $confirmPickGroups = [];
  7472. $processDisplayRows = [];
  7473. $allDetailsBySid = [];
  7474. $requiredSidList = [];
  7475. $sidList = [$ids];
  7476. if ($isPurchaseConfirm) {
  7477. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  7478. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  7479. if ($mergeRows !== []) {
  7480. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7481. }
  7482. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  7483. if ($confirmBundle['pos'] !== []) {
  7484. $sidList = [];
  7485. foreach ($confirmBundle['pos'] as $poRow) {
  7486. if (!is_array($poRow)) {
  7487. continue;
  7488. }
  7489. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7490. if (!$this->isValidScydgyRowId($sid)) {
  7491. continue;
  7492. }
  7493. $sidList[] = (string)$sid;
  7494. $requiredSidList[] = $sid;
  7495. }
  7496. }
  7497. if ($sidList === []) {
  7498. $sidList = [$ids];
  7499. $requiredSidList = [(int)$ids];
  7500. }
  7501. $confirmProcessCount = max(1, count($requiredSidList));
  7502. if (is_array($po) && $purchaseOrderId <= 0) {
  7503. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7504. }
  7505. }
  7506. $rows = [];
  7507. try {
  7508. if (count($sidList) === 1) {
  7509. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  7510. } else {
  7511. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  7512. }
  7513. } catch (\Throwable $e) {
  7514. $rows = [];
  7515. }
  7516. if ($isPurchaseConfirm) {
  7517. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  7518. }
  7519. foreach ($rows as &$r) {
  7520. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  7521. $r['id'] = $r['ID'];
  7522. }
  7523. if (isset($r['createtime'])) {
  7524. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  7525. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  7526. } else {
  7527. $r['createtime_text'] = (string)$r['createtime'];
  7528. }
  7529. } else {
  7530. $r['createtime_text'] = '';
  7531. }
  7532. if (is_array($r)) {
  7533. $r = $this->maskSupplierContactFields($r);
  7534. }
  7535. }
  7536. unset($r);
  7537. $pickedCompanyName = '';
  7538. if ($isPurchaseConfirm) {
  7539. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  7540. if (!is_array($poRow)) {
  7541. continue;
  7542. }
  7543. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7544. if ($pn !== '') {
  7545. $pickedCompanyName = $pn;
  7546. break;
  7547. }
  7548. }
  7549. }
  7550. $this->view->assign('rows', $rows ?: []);
  7551. $this->view->assign('rowCount', count($rows ?: []));
  7552. $this->view->assign('scydgyId', $ids);
  7553. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  7554. $this->view->assign('headTitle', $headTitle);
  7555. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  7556. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  7557. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  7558. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  7559. $this->view->assign('processDisplayRows', $processDisplayRows);
  7560. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  7561. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  7562. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  7563. $sysRqDisplay = '—';
  7564. if ($isPurchaseConfirm) {
  7565. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  7566. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  7567. );
  7568. }
  7569. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  7570. $this->view->assign('sysRq', $isPurchaseConfirm
  7571. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  7572. : '');
  7573. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  7574. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  7575. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  7576. if ($isPurchaseConfirm) {
  7577. return $this->view->fetch();
  7578. }
  7579. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  7580. $this->view->engine->layout(false);
  7581. try {
  7582. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  7583. $this->view->assign('dialogBody', $bodyHtml);
  7584. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  7585. } finally {
  7586. if ($restoreLayout) {
  7587. $this->view->engine->layout($restoreLayout);
  7588. }
  7589. }
  7590. }
  7591. /**
  7592. * 月度导出记录表(不存在时自动创建)
  7593. */
  7594. protected function ensurePurchaseMonthExportLogTable(): void
  7595. {
  7596. try {
  7597. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  7598. } catch (\Throwable $e) {
  7599. Db::execute(
  7600. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  7601. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  7602. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  7603. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  7604. `admin_name` varchar(64) NOT NULL DEFAULT '',
  7605. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  7606. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  7607. `createtime` int(10) unsigned DEFAULT NULL,
  7608. PRIMARY KEY (`id`),
  7609. KEY `idx_ym` (`ym`),
  7610. KEY `idx_ct` (`createtime`)
  7611. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  7612. );
  7613. }
  7614. }
  7615. /**
  7616. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  7617. *
  7618. * @param array<int, mixed> $dbRows
  7619. * @return array<int, array<string, mixed>>
  7620. */
  7621. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  7622. {
  7623. $keyword = trim((string)$this->request->get('search', ''));
  7624. if ($keyword === '') {
  7625. $keyword = trim((string)$this->request->request('search', ''));
  7626. }
  7627. $filter = $this->request->get('filter', '');
  7628. $op = $this->request->get('op', '');
  7629. if (is_string($filter) && $filter !== '') {
  7630. $filterArr = (array)json_decode($filter, true);
  7631. } else {
  7632. $filterArr = is_array($filter) ? $filter : [];
  7633. }
  7634. if (is_string($op) && $op !== '') {
  7635. $opArr = (array)json_decode($op, true);
  7636. } else {
  7637. $opArr = is_array($op) ? $op : [];
  7638. }
  7639. if ($keyword === '' && $filterArr === []) {
  7640. return array_values(array_filter($dbRows, 'is_array'));
  7641. }
  7642. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  7643. $out = [];
  7644. foreach ($dbRows as $row) {
  7645. if (!is_array($row)) {
  7646. continue;
  7647. }
  7648. if ($keyword !== '') {
  7649. $hit = false;
  7650. foreach ($searchFields as $f) {
  7651. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  7652. $hit = true;
  7653. break;
  7654. }
  7655. }
  7656. if (!$hit) {
  7657. continue;
  7658. }
  7659. }
  7660. $passFilter = true;
  7661. foreach ($filterArr as $field => $val) {
  7662. $field = (string)$field;
  7663. $val = trim((string)$val);
  7664. if ($field === '' || $val === '') {
  7665. continue;
  7666. }
  7667. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  7668. continue;
  7669. }
  7670. $cell = (string)($row[$field] ?? '');
  7671. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  7672. if ($mode === '=' || $mode === 'EQUAL') {
  7673. if (strcasecmp($cell, $val) !== 0) {
  7674. $passFilter = false;
  7675. break;
  7676. }
  7677. } elseif (mb_stripos($cell, $val) === false) {
  7678. $passFilter = false;
  7679. break;
  7680. }
  7681. }
  7682. if (!$passFilter) {
  7683. continue;
  7684. }
  7685. $out[] = $row;
  7686. }
  7687. return $out;
  7688. }
  7689. /**
  7690. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  7691. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  7692. */
  7693. public function export_month_outward()
  7694. {
  7695. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  7696. $this->error(__('You have no permission'));
  7697. }
  7698. $this->request->filter(['strip_tags', 'trim']);
  7699. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  7700. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  7701. $ym = date('Y-m');
  7702. }
  7703. $dbRows = [];
  7704. try {
  7705. $query = Db::table('purchase_order');
  7706. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7707. $dbRows = $query->select();
  7708. } catch (\Throwable $e) {
  7709. $dbRows = [];
  7710. }
  7711. if (!is_array($dbRows)) {
  7712. $dbRows = [];
  7713. }
  7714. $completeTsMap = [];
  7715. $sidList = [];
  7716. foreach ($dbRows as $dbRow) {
  7717. if (!is_array($dbRow)) {
  7718. continue;
  7719. }
  7720. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  7721. if ($sid > 0) {
  7722. $sidList[$sid] = true;
  7723. }
  7724. }
  7725. if ($sidList !== []) {
  7726. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  7727. }
  7728. $searchKw = trim((string)$this->request->get('search', ''));
  7729. if ($searchKw === '') {
  7730. $searchKw = trim((string)$this->request->request('search', ''));
  7731. }
  7732. $filterRaw = $this->request->get('filter', '');
  7733. $filterArrTmp = [];
  7734. if (is_string($filterRaw) && $filterRaw !== '') {
  7735. $filterArrTmp = (array)json_decode($filterRaw, true);
  7736. } elseif (is_array($filterRaw)) {
  7737. $filterArrTmp = $filterRaw;
  7738. }
  7739. $hasSearch = ($searchKw !== '');
  7740. if (!$hasSearch) {
  7741. foreach ($filterArrTmp as $fv) {
  7742. if (trim((string)$fv) !== '') {
  7743. $hasSearch = true;
  7744. break;
  7745. }
  7746. }
  7747. }
  7748. // 有搜索时跨月份导出(与列表一致);无搜索时仍按查看月份
  7749. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  7750. if (!is_array($dbRow)) {
  7751. return false;
  7752. }
  7753. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  7754. if ($done['ts'] <= 0) {
  7755. return false;
  7756. }
  7757. if ($hasSearch) {
  7758. return true;
  7759. }
  7760. return date('Y-m', $done['ts']) === $ym;
  7761. }));
  7762. // 与列表页一致:按搜索关键字 / 通用搜索过滤
  7763. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  7764. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  7765. $filtered = $pool;
  7766. $mainBySid = [];
  7767. foreach ($filtered as $rw) {
  7768. if (!is_array($rw)) {
  7769. continue;
  7770. }
  7771. $rid = (int)($rw['ID'] ?? 0);
  7772. if ($rid > 0) {
  7773. $mainBySid[$rid] = $rw;
  7774. }
  7775. }
  7776. if ($mainBySid === []) {
  7777. $detailRows = [];
  7778. } else {
  7779. try {
  7780. $detailRows = Db::table('purchase_order_detail')
  7781. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7782. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7783. ->order('status', 'desc')
  7784. ->order('CCYDH', 'asc')
  7785. ->order('company_name', 'asc')
  7786. ->order('id', 'asc')
  7787. ->select();
  7788. } catch (\Throwable $e) {
  7789. try {
  7790. $detailRows = Db::table('purchase_order_detail')
  7791. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7792. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7793. ->order('status', 'desc')
  7794. ->order('CCYDH', 'asc')
  7795. ->order('company_name', 'asc')
  7796. ->order('ID', 'asc')
  7797. ->select();
  7798. } catch (\Throwable $e2) {
  7799. $detailRows = [];
  7800. }
  7801. }
  7802. }
  7803. if (!is_array($detailRows)) {
  7804. $detailRows = [];
  7805. }
  7806. $exportLines = [];
  7807. $detailSidSeen = [];
  7808. foreach ($detailRows as $dr) {
  7809. if (!is_array($dr)) {
  7810. continue;
  7811. }
  7812. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7813. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7814. continue;
  7815. }
  7816. if (isset($detailSidSeen[$sid])) {
  7817. continue;
  7818. }
  7819. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  7820. continue;
  7821. }
  7822. $detailSidSeen[$sid] = true;
  7823. $m = $mainBySid[$sid];
  7824. $exportLines[] = [
  7825. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7826. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7827. 'company_name' => (string)($dr['company_name'] ?? ''),
  7828. 'CDF' => (string)($m['CDF'] ?? ''),
  7829. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7830. 'gx' => $this->procuremenExportGxText($m),
  7831. 'detail' => $dr,
  7832. ];
  7833. }
  7834. foreach ($detailRows as $dr) {
  7835. if (!is_array($dr)) {
  7836. continue;
  7837. }
  7838. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7839. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  7840. continue;
  7841. }
  7842. $detailSidSeen[$sid] = true;
  7843. $m = $mainBySid[$sid];
  7844. $exportLines[] = [
  7845. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7846. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7847. 'company_name' => (string)($dr['company_name'] ?? ''),
  7848. 'CDF' => (string)($m['CDF'] ?? ''),
  7849. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7850. 'gx' => $this->procuremenExportGxText($m),
  7851. 'detail' => $dr,
  7852. ];
  7853. }
  7854. foreach ($mainBySid as $sid => $m) {
  7855. if (isset($detailSidSeen[$sid])) {
  7856. continue;
  7857. }
  7858. $company = trim((string)($m['pick_company_name'] ?? ''));
  7859. $exportLines[] = [
  7860. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  7861. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  7862. 'company_name' => $company,
  7863. 'CDF' => (string)($m['CDF'] ?? ''),
  7864. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7865. 'gx' => $this->procuremenExportGxText($m),
  7866. 'detail' => [],
  7867. ];
  7868. }
  7869. $groups = [];
  7870. foreach ($exportLines as $line) {
  7871. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  7872. if (!isset($groups[$k])) {
  7873. $groups[$k] = [];
  7874. }
  7875. $groups[$k][] = $line;
  7876. }
  7877. ksort($groups, SORT_STRING);
  7878. $spreadsheet = new Spreadsheet();
  7879. $sheet = $spreadsheet->getActiveSheet();
  7880. $sheet->setTitle('外协加工明细');
  7881. $mon = (int)substr($ym, 5, 2);
  7882. $sheet->mergeCells('A1:H1');
  7883. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  7884. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  7885. $sheet->getStyle('A1')->getAlignment()
  7886. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7887. ->setVertical(Alignment::VERTICAL_CENTER);
  7888. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  7889. $col = 'A';
  7890. foreach ($headers as $h) {
  7891. $sheet->setCellValue($col . '2', $h);
  7892. $col++;
  7893. }
  7894. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  7895. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7896. $rowNum = 3;
  7897. $sumSubtotalCounts = 0;
  7898. $grandAmount = 0.0;
  7899. $globalSeq = 0;
  7900. if ($groups === []) {
  7901. $sheet->mergeCells('A3:H3');
  7902. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  7903. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7904. $rowNum = 4;
  7905. } else {
  7906. foreach ($groups as $items) {
  7907. if ($items === []) {
  7908. continue;
  7909. }
  7910. $groupLineCount = count($items);
  7911. $subAmount = 0.0;
  7912. foreach ($items as $line) {
  7913. $globalSeq++;
  7914. $dr = $line['detail'];
  7915. $amt = $this->procuremenExportAmount($dr);
  7916. $subAmount += $amt;
  7917. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  7918. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  7919. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  7920. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  7921. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  7922. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  7923. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  7924. $sheet->setCellValue('H' . $rowNum, $amt);
  7925. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  7926. $rowNum++;
  7927. }
  7928. $sumSubtotalCounts += $groupLineCount;
  7929. $grandAmount += $subAmount;
  7930. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7931. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  7932. $sheet->getStyle('G' . $rowNum)->getAlignment()
  7933. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  7934. ->setVertical(Alignment::VERTICAL_CENTER);
  7935. $rowNum++;
  7936. }
  7937. }
  7938. $sheet->setCellValue('A' . $rowNum, '总计');
  7939. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  7940. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7941. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  7942. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  7943. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  7944. $lastRow = $rowNum;
  7945. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  7946. 'borders' => [
  7947. 'allBorders' => [
  7948. 'borderStyle' => Border::BORDER_THIN,
  7949. 'color' => ['rgb' => '000000'],
  7950. ],
  7951. ],
  7952. ]);
  7953. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  7954. if ($lastRow >= 3) {
  7955. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7956. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7957. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7958. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7959. }
  7960. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  7961. $sheet->getColumnDimension('A')->setWidth(7);
  7962. $sheet->getColumnDimension('B')->setWidth(16);
  7963. $sheet->getColumnDimension('C')->setWidth(52);
  7964. $sheet->getColumnDimension('D')->setWidth(32);
  7965. $sheet->getColumnDimension('E')->setWidth(12);
  7966. $sheet->getColumnDimension('F')->setWidth(44);
  7967. $sheet->getColumnDimension('G')->setWidth(26);
  7968. $sheet->getColumnDimension('H')->setWidth(13);
  7969. $sheet->getRowDimension(1)->setRowHeight(28);
  7970. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  7971. $quoteStartRow = $lastRow + 3;
  7972. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
  7973. if ($quoteLastRow >= $quoteStartRow) {
  7974. $sheet->getColumnDimension('E')->setWidth(28);
  7975. }
  7976. $ymCompact = str_replace('-', '', $ym);
  7977. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  7978. $filename = $fileBase . '.xlsx';
  7979. try {
  7980. $this->ensurePurchaseMonthExportLogTable();
  7981. list($adminId, $adminName) = $this->GetUseName();
  7982. Db::table('purchase_month_export_log')->insert([
  7983. 'ym' => $ym,
  7984. 'admin_id' => (int)$adminId,
  7985. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  7986. 'row_count' => count($exportLines),
  7987. 'total_amount' => round($grandAmount, 2),
  7988. 'createtime' => time(),
  7989. ]);
  7990. } catch (\Throwable $e) {
  7991. Log::write('month export log: ' . $e->getMessage(), 'error');
  7992. }
  7993. if (ob_get_length()) {
  7994. ob_end_clean();
  7995. }
  7996. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  7997. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  7998. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  7999. header('Cache-Control: max-age=0');
  8000. $writer = new Xlsx($spreadsheet);
  8001. $writer->save('php://output');
  8002. $spreadsheet->disconnectWorksheets();
  8003. unset($spreadsheet);
  8004. exit;
  8005. }
  8006. /**
  8007. * 导出用:工序列文案
  8008. */
  8009. protected function procuremenExportGxText(array $r)
  8010. {
  8011. $a = trim((string)($r['CDXMC'] ?? ''));
  8012. $b = trim((string)($r['CGYMC'] ?? ''));
  8013. if ($a !== '' && $b !== '') {
  8014. return $a . ':' . $b;
  8015. }
  8016. return $a !== '' ? $a : $b;
  8017. }
  8018. /**
  8019. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  8020. */
  8021. protected function procuremenExportAmount(array $r)
  8022. {
  8023. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  8024. if (!array_key_exists($k, $r)) {
  8025. continue;
  8026. }
  8027. $v = $r[$k];
  8028. if ($v === null || $v === '') {
  8029. continue;
  8030. }
  8031. if (is_numeric($v)) {
  8032. return (float)$v;
  8033. }
  8034. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  8035. if ($v !== '' && is_numeric($v)) {
  8036. return (float)$v;
  8037. }
  8038. }
  8039. return 0.0;
  8040. }
  8041. /**
  8042. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  8043. *
  8044. * @param array<int, array<string, mixed>> $detailRows
  8045. * @param array<int, array<string, mixed>> $mainBySid
  8046. * @return array<int, array<string, mixed>>
  8047. */
  8048. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  8049. {
  8050. $lines = [];
  8051. foreach ($detailRows as $dr) {
  8052. if (!is_array($dr)) {
  8053. continue;
  8054. }
  8055. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8056. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8057. continue;
  8058. }
  8059. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  8060. continue;
  8061. }
  8062. $cn = trim((string)($dr['company_name'] ?? ''));
  8063. if ($cn === '') {
  8064. continue;
  8065. }
  8066. $m = $mainBySid[$sid];
  8067. $am = trim((string)($dr['amount'] ?? ''));
  8068. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  8069. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  8070. $amountText = $amountFilled
  8071. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  8072. : '未填写';
  8073. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  8074. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  8075. if ($deliveryShow === '' && $deliveryRaw !== '') {
  8076. $deliveryShow = $deliveryRaw;
  8077. }
  8078. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  8079. ? $deliveryShow
  8080. : '未填写';
  8081. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  8082. $lines[] = [
  8083. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8084. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8085. 'gx' => $this->procuremenExportGxText($m),
  8086. 'company_name' => $cn,
  8087. 'amount_text' => $amountText,
  8088. 'amount_num' => $amountFilled ? $amountNum : null,
  8089. 'delivery_text' => $deliveryText,
  8090. 'picked_text' => $picked ? '中标' : '未中标',
  8091. 'picked' => $picked,
  8092. ];
  8093. }
  8094. $winnerSupplierByOrder = [];
  8095. foreach ($lines as $line) {
  8096. $dh = trim((string)($line['CCYDH'] ?? ''));
  8097. $cn = trim((string)($line['company_name'] ?? ''));
  8098. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  8099. $winnerSupplierByOrder[$dh][$cn] = true;
  8100. }
  8101. }
  8102. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  8103. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  8104. if ($c !== 0) {
  8105. return $c;
  8106. }
  8107. $dh = trim((string)($a['CCYDH'] ?? ''));
  8108. $aCn = trim((string)($a['company_name'] ?? ''));
  8109. $bCn = trim((string)($b['company_name'] ?? ''));
  8110. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  8111. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  8112. if ($aSupplierWin !== $bSupplierWin) {
  8113. return $aSupplierWin ? -1 : 1;
  8114. }
  8115. $c = strcmp($aCn, $bCn);
  8116. if ($c !== 0) {
  8117. return $c;
  8118. }
  8119. if (!empty($a['picked']) !== !empty($b['picked'])) {
  8120. return !empty($a['picked']) ? -1 : 1;
  8121. }
  8122. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  8123. if ($c !== 0) {
  8124. return $c;
  8125. }
  8126. return 0;
  8127. });
  8128. return $lines;
  8129. }
  8130. /**
  8131. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  8132. *
  8133. * @param array<int, array<string, mixed>> $quoteLines
  8134. */
  8135. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  8136. {
  8137. $mon = (int)substr($ym, 5, 2);
  8138. $titleRow = $startRow;
  8139. $headerRow = $startRow + 1;
  8140. $dataStartRow = $startRow + 2;
  8141. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  8142. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  8143. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  8144. $sheet->getStyle('A' . $titleRow)->getAlignment()
  8145. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8146. ->setVertical(Alignment::VERTICAL_CENTER);
  8147. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  8148. $col = 'A';
  8149. foreach ($headers as $h) {
  8150. $sheet->setCellValue($col . $headerRow, $h);
  8151. $col++;
  8152. }
  8153. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  8154. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8155. $rowNum = $dataStartRow;
  8156. if ($quoteLines === []) {
  8157. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  8158. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  8159. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8160. $rowNum = $dataStartRow + 1;
  8161. } else {
  8162. $i = 0;
  8163. foreach ($quoteLines as $line) {
  8164. $i++;
  8165. $sheet->setCellValue('A' . $rowNum, $i);
  8166. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  8167. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  8168. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  8169. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  8170. if ($line['amount_num'] !== null) {
  8171. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  8172. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  8173. } else {
  8174. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  8175. }
  8176. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  8177. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  8178. if (!empty($line['picked'])) {
  8179. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8180. }
  8181. $rowNum++;
  8182. }
  8183. }
  8184. $lastRow = $rowNum - 1;
  8185. if ($lastRow >= $headerRow) {
  8186. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  8187. 'borders' => [
  8188. 'allBorders' => [
  8189. 'borderStyle' => Border::BORDER_THIN,
  8190. 'color' => ['rgb' => '000000'],
  8191. ],
  8192. ],
  8193. ]);
  8194. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8195. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8196. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8197. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8198. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  8199. if ($lastRow >= $dataStartRow) {
  8200. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  8201. }
  8202. }
  8203. return $lastRow;
  8204. }
  8205. /**
  8206. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  8207. */
  8208. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  8209. {
  8210. if ($lastRow < $dataStartRow || $headerRow < 1) {
  8211. return;
  8212. }
  8213. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  8214. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8215. ->setVertical(Alignment::VERTICAL_CENTER);
  8216. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  8217. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8218. ->setVertical(Alignment::VERTICAL_CENTER);
  8219. if ($lastCol > 'B') {
  8220. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  8221. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8222. ->setVertical(Alignment::VERTICAL_CENTER);
  8223. }
  8224. }
  8225. /**
  8226. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  8227. */
  8228. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  8229. {
  8230. $s = trim($ccydh);
  8231. if ($s === '') {
  8232. return 'ORDER';
  8233. }
  8234. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  8235. $s = trim($s, '._-');
  8236. if ($s === '') {
  8237. return 'ORDER';
  8238. }
  8239. if (function_exists('mb_substr')) {
  8240. return mb_substr($s, 0, 80, 'UTF-8');
  8241. }
  8242. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  8243. }
  8244. /**
  8245. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  8246. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  8247. *
  8248. * @return array{objectKey: string, webPath: string}
  8249. */
  8250. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  8251. {
  8252. $sid = (int)$scydgyId;
  8253. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  8254. $y = date('Y');
  8255. $m = date('m');
  8256. $d = date('d');
  8257. $basename = $safeOrder . '_' . $sid . '.pdf';
  8258. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  8259. return [
  8260. 'objectKey' => $objectKey,
  8261. 'webPath' => '/' . $objectKey,
  8262. ];
  8263. }
  8264. /**
  8265. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  8266. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  8267. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  8268. *
  8269. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  8270. */
  8271. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  8272. {
  8273. if (!$this->isValidScydgyRowId($scydgyId)) {
  8274. return '';
  8275. }
  8276. $ids = trim((string)$scydgyId);
  8277. $prep = $this->prepareProcuremenDetailsView($ids);
  8278. if (!$prep['ok']) {
  8279. return '';
  8280. }
  8281. $ccydh = $prep['ccydh'];
  8282. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  8283. $objectKey = $paths['objectKey'];
  8284. $webPath = $paths['webPath'];
  8285. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  8286. $this->view->assign([
  8287. 'pdf_export' => 1,
  8288. 'pdfMetaLine' => $meta,
  8289. ]);
  8290. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  8291. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8292. $this->view->engine->layout(false);
  8293. try {
  8294. $html = $this->view->fetch('procuremen/details_pdf_shell');
  8295. } catch (\Throwable $e) {
  8296. if ($restoreLayout) {
  8297. $this->view->engine->layout($restoreLayout);
  8298. }
  8299. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  8300. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8301. return '';
  8302. }
  8303. if ($restoreLayout) {
  8304. $this->view->engine->layout($restoreLayout);
  8305. }
  8306. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8307. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  8308. if (!is_dir($tempDir)) {
  8309. @mkdir($tempDir, 0755, true);
  8310. }
  8311. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  8312. try {
  8313. $mpdf = new \Mpdf\Mpdf([
  8314. 'mode' => 'utf-8',
  8315. 'format' => 'A4',
  8316. 'margin_left' => 12,
  8317. 'margin_right' => 12,
  8318. 'margin_top' => 14,
  8319. 'margin_bottom' => 14,
  8320. 'tempDir' => $tempDir,
  8321. 'autoScriptToLang' => true,
  8322. 'autoLangToFont' => true,
  8323. ]);
  8324. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  8325. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  8326. $mpdf->SetBasePath('http://127.0.0.1/');
  8327. $mpdf->WriteHTML($html);
  8328. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  8329. } catch (\Throwable $e) {
  8330. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  8331. if (is_file($tempPdf)) {
  8332. @unlink($tempPdf);
  8333. }
  8334. return '';
  8335. }
  8336. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  8337. if ($ossUrl !== '') {
  8338. @unlink($tempPdf);
  8339. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8340. return $ossUrl;
  8341. }
  8342. $pi = pathinfo($objectKey);
  8343. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  8344. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  8345. if ($baseFile === '') {
  8346. @unlink($tempPdf);
  8347. return '';
  8348. }
  8349. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  8350. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  8351. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  8352. @unlink($tempPdf);
  8353. return '';
  8354. }
  8355. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  8356. if (!@copy($tempPdf, $fullPath)) {
  8357. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  8358. @unlink($tempPdf);
  8359. return '';
  8360. }
  8361. @unlink($tempPdf);
  8362. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8363. return $webPath;
  8364. }
  8365. /**
  8366. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  8367. */
  8368. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  8369. {
  8370. if ($scydgyId <= 0 || $webPath === '') {
  8371. return;
  8372. }
  8373. try {
  8374. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  8375. } catch (\Throwable $e) {
  8376. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  8377. }
  8378. }
  8379. /**
  8380. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  8381. *
  8382. * @param array<string, string> $vars
  8383. * @return array<string, string>
  8384. */
  8385. protected function normalizeSmsTemplateVars(array $vars): array
  8386. {
  8387. $out = [];
  8388. foreach ($vars as $k => $v) {
  8389. $out[(string)$k] = trim((string)$v);
  8390. }
  8391. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  8392. $out['contact_name'] = $out['company_name'];
  8393. }
  8394. return $out;
  8395. }
  8396. /**
  8397. * 按手机号或公司名称查 customer 表联系人姓名
  8398. */
  8399. protected function resolveCustomerContactName(string $phone, string $companyName): string
  8400. {
  8401. $phone = trim($phone);
  8402. $companyName = trim($companyName);
  8403. try {
  8404. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  8405. $row = Db::table('customer')
  8406. ->where(function ($q) use ($phone) {
  8407. $q->where('phone', $phone)->whereOr('account', $phone);
  8408. })
  8409. ->order('id', 'asc')
  8410. ->find();
  8411. if (is_array($row)) {
  8412. $nm = trim((string)($row['username'] ?? ''));
  8413. if ($nm !== '') {
  8414. return $nm;
  8415. }
  8416. }
  8417. }
  8418. if ($companyName !== '') {
  8419. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  8420. if (is_array($row)) {
  8421. return trim((string)($row['username'] ?? ''));
  8422. }
  8423. }
  8424. } catch (\Throwable $e) {
  8425. }
  8426. return '';
  8427. }
  8428. /**
  8429. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  8430. */
  8431. protected function plainTextToHtmlEmailBody(string $text): string
  8432. {
  8433. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  8434. $parts = explode("\n", $text);
  8435. $out = [];
  8436. foreach ($parts as $line) {
  8437. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  8438. $out[] = $line;
  8439. } else {
  8440. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  8441. }
  8442. }
  8443. return implode("<br>\n", $out);
  8444. }
  8445. /**
  8446. * 短信场景:去掉链接类变量,避免误填 URL
  8447. *
  8448. * @param array<string, string> $vars
  8449. * @return array<string, string>
  8450. */
  8451. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  8452. {
  8453. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  8454. return $vars;
  8455. }
  8456. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  8457. $vars[$k] = '';
  8458. }
  8459. return $vars;
  8460. }
  8461. /**
  8462. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  8463. *
  8464. * @param array<string, string> $vars
  8465. */
  8466. protected function renderNotifyTemplate(string $scene, array $vars): string
  8467. {
  8468. $vars = $this->normalizeSmsTemplateVars($vars);
  8469. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  8470. $row = $this->loadNotifyTemplateRow($scene);
  8471. if ($row === null) {
  8472. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8473. }
  8474. $tpl = trim((string)($row['content'] ?? ''));
  8475. if ($tpl === '') {
  8476. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8477. }
  8478. foreach ($vars as $k => $v) {
  8479. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  8480. }
  8481. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  8482. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  8483. return $tpl;
  8484. }
  8485. protected function resolveProcuremenEmailSubject(string $scene): string
  8486. {
  8487. $map = [
  8488. 'review_email' => '您有新的协助加工订单',
  8489. ];
  8490. $subject = trim((string)($map[$scene] ?? ''));
  8491. if ($subject === '') {
  8492. $this->error('未配置邮件主题:' . $scene);
  8493. }
  8494. return $subject;
  8495. }
  8496. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  8497. {
  8498. $map = [
  8499. 'review_email' => '协助下发-邮箱',
  8500. 'review_sms' => '协助下发-短信',
  8501. 'confirm_ok' => '采购确认-通过',
  8502. 'confirm_fail' => '采购确认-未通过',
  8503. 'bid_open' => '开标双重验证',
  8504. ];
  8505. $label = $map[$scene] ?? $scene;
  8506. if ($titleRequired) {
  8507. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  8508. }
  8509. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  8510. }
  8511. /**
  8512. * 是否开启协助通知演练(不发真实短信/邮件)
  8513. */
  8514. protected function isProcuremenNotifyDryRun(): bool
  8515. {
  8516. return (bool)Config::get('procuremen_notify_dry_run');
  8517. }
  8518. /**
  8519. * @param array<string, mixed> $payload
  8520. */
  8521. protected function recordNotifyDryRunPreview(array $payload): void
  8522. {
  8523. $this->notifyDryRunPreview[] = $payload;
  8524. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8525. }
  8526. /**
  8527. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  8528. * @throws \Exception
  8529. */
  8530. protected function smsbao($phone, $content)
  8531. {
  8532. if ($this->isProcuremenNotifyDryRun()) {
  8533. $this->recordNotifyDryRunPreview([
  8534. 'scene' => 'sms_only',
  8535. 'phone' => $phone,
  8536. 'sms_content' => $content,
  8537. ]);
  8538. return;
  8539. }
  8540. $statusStr = [
  8541. '0' => '短信发送成功',
  8542. '-1' => '参数不全',
  8543. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  8544. '30' => '密码错误',
  8545. '40' => '账号不存在',
  8546. '41' => '余额不足',
  8547. '42' => '帐户已过期',
  8548. '43' => 'IP地址限制',
  8549. '50' => '内容含有敏感词',
  8550. ];
  8551. $smsapi = 'http://api.smsbao.com/';
  8552. $user = 'zhuwei123';
  8553. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  8554. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  8555. $result = @file_get_contents($sendurl);
  8556. if ($result === false) {
  8557. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  8558. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  8559. }
  8560. $result = trim((string)$result);
  8561. if ($result !== '0') {
  8562. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  8563. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  8564. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  8565. }
  8566. }
  8567. }