Procuremen.php 339 KB

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