Procuremen.php 376 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenStatus;
  8. use app\common\library\ProcuremenSupplierScore;
  9. use app\common\library\ProcuremenTime;
  10. use PHPMailer\PHPMailer\PHPMailer;
  11. use think\Config;
  12. use think\Cache;
  13. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  14. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  15. use PhpOffice\PhpSpreadsheet\Style\Border;
  16. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  17. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  18. use think\Db;
  19. use think\Log;
  20. class Procuremen extends Backend
  21. {
  22. /**
  23. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  24. */
  25. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  26. /**
  27. * Procuremen模型对象
  28. * @var \app\admin\model\Procuremen
  29. */
  30. protected $model = null;
  31. /**
  32. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  33. */
  34. protected $notifyDryRunPreview = [];
  35. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  36. protected $procuremenRedisCache = null;
  37. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  38. protected $pickHiddenScydgySetCache = null;
  39. /** 邮件发送日志表结构已就绪缓存键 */
  40. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  41. /**
  42. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  43. * @var array
  44. */
  45. protected $noNeedRight = [
  46. 'pickreview', 'review', 'reviewcompanies',
  47. ];
  48. public function _initialize()
  49. {
  50. parent::_initialize();
  51. $this->model = new \app\admin\model\Procuremen;
  52. $this->maybeMigrateLegacyWflowStatusText();
  53. $this->assignProcuremenAuthConfig();
  54. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  55. $this->ensurePurchaseEmailSendLogTableOnce();
  56. }
  57. }
  58. /**
  59. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  60. */
  61. protected function maybeMigrateLegacyWflowStatusText(): void
  62. {
  63. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  64. if (is_file($flagFile)) {
  65. return;
  66. }
  67. $map = [
  68. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  69. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  70. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  71. '3' => ProcuremenStatus::WFLOW_APPROVED,
  72. ];
  73. try {
  74. foreach ($map as $num => $text) {
  75. Db::table('purchase_order')
  76. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  77. ->update(['wflow_status' => $text]);
  78. }
  79. @file_put_contents($flagFile, date('c'));
  80. } catch (\Throwable $e) {
  81. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  82. }
  83. }
  84. /**
  85. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  86. *
  87. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  88. */
  89. protected function hasProcuremenPerm(array $actions): bool
  90. {
  91. foreach ($actions as $action) {
  92. $action = strtolower(trim((string)$action));
  93. if ($action === '') {
  94. continue;
  95. }
  96. if (strpos($action, 'procuremen/') !== 0) {
  97. $action = 'procuremen/' . $action;
  98. }
  99. if ($this->auth->check($action)) {
  100. return true;
  101. }
  102. }
  103. $suffixes = [];
  104. foreach ($actions as $action) {
  105. $action = strtolower(trim((string)$action));
  106. $action = preg_replace('#^procuremen/#', '', $action);
  107. if ($action !== '') {
  108. $suffixes[$action] = true;
  109. }
  110. }
  111. if ($suffixes === []) {
  112. return false;
  113. }
  114. try {
  115. foreach ($this->auth->getRuleList() as $rule) {
  116. $rule = strtolower((string)$rule);
  117. if (strpos($rule, 'procuremen/') !== 0) {
  118. continue;
  119. }
  120. foreach (array_keys($suffixes) as $suffix) {
  121. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  122. return true;
  123. }
  124. }
  125. }
  126. } catch (\Throwable $e) {
  127. }
  128. return false;
  129. }
  130. /**
  131. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  132. *
  133. * @param string[] $actions
  134. */
  135. protected function hasProcuremenPermStrict(array $actions): bool
  136. {
  137. foreach ($actions as $action) {
  138. $action = strtolower(trim((string)$action));
  139. if ($action === '') {
  140. continue;
  141. }
  142. if (strpos($action, 'procuremen/') !== 0) {
  143. $action = 'procuremen/' . $action;
  144. }
  145. if ($this->auth->check($action)) {
  146. return true;
  147. }
  148. }
  149. return false;
  150. }
  151. /**
  152. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  153. *
  154. * @param string[] $titles
  155. */
  156. protected function authHasAssignedRuleTitle(array $titles): bool
  157. {
  158. $titles = array_values(array_filter(array_map('trim', $titles)));
  159. if ($titles === []) {
  160. return false;
  161. }
  162. try {
  163. $ids = $this->auth->getRuleIds();
  164. if (in_array('*', $ids, true)) {
  165. return true;
  166. }
  167. if ($ids === []) {
  168. return false;
  169. }
  170. $rows = Db::name('auth_rule')
  171. ->where('status', 'normal')
  172. ->whereIn('id', $ids)
  173. ->column('title');
  174. foreach ($rows as $title) {
  175. $t = trim((string)$title);
  176. if ($t !== '' && in_array($t, $titles, true)) {
  177. return true;
  178. }
  179. }
  180. } catch (\Throwable $e) {
  181. }
  182. return false;
  183. }
  184. protected function procuremenCanPickDelete(): bool
  185. {
  186. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  187. return true;
  188. }
  189. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  190. }
  191. protected function procuremenCanComplete(): bool
  192. {
  193. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  194. return true;
  195. }
  196. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  197. }
  198. protected function procuremenCanDispatch(): bool
  199. {
  200. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  201. }
  202. /**
  203. * 前端按钮显隐(Config.procuremenAuth)
  204. */
  205. protected function assignProcuremenAuthConfig(): void
  206. {
  207. $authMap = [
  208. 'pickreview' => $this->procuremenCanDispatch(),
  209. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  210. 'pickdelete' => $this->procuremenCanPickDelete(),
  211. 'completedirectly' => $this->procuremenCanComplete(),
  212. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  213. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  214. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  215. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  216. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  217. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  218. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  219. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  220. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  221. 'details' => $this->hasProcuremenPerm(['details']),
  222. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  223. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  224. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  225. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  226. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  227. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  228. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  229. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  230. 'add' => $this->hasProcuremenPerm(['add']),
  231. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  232. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  233. ];
  234. $this->assignconfig('procuremenAuth', $authMap);
  235. }
  236. /**
  237. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  238. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  239. *
  240. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  241. */
  242. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  243. {
  244. static $mprocCfgLoaded = false;
  245. if (!$mprocCfgLoaded) {
  246. $mprocCfgLoaded = true;
  247. if (is_file(APP_PATH . 'extra/mproc.php')) {
  248. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  249. }
  250. }
  251. $eid = (int)$purchaseOrderDetailId;
  252. $base = $this->resolveMprocMobilePublicBaseUrl();
  253. if ($base === '') {
  254. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  255. }
  256. $path = trim((string)Config::get('mproc.mobile_index_path'));
  257. if ($path === '') {
  258. $path = '/index.php/index/index/index';
  259. } else {
  260. $path = '/' . ltrim($path, '/');
  261. }
  262. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  263. if ($eid > 0) {
  264. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  265. }
  266. return $base . $path . '?main_tab=orders';
  267. }
  268. /**
  269. * 邮件/短信外链:须为带点的公网域名
  270. */
  271. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  272. {
  273. $u = trim((string)$baseUrl);
  274. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  275. return false;
  276. }
  277. $host = parse_url($u, PHP_URL_HOST);
  278. if (!is_string($host) || $host === '') {
  279. return false;
  280. }
  281. if (strcasecmp($host, 'localhost') === 0) {
  282. return false;
  283. }
  284. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  285. return false;
  286. }
  287. if (strpos($host, '.') === false) {
  288. return false;
  289. }
  290. return true;
  291. }
  292. /**
  293. * 解析用于协助邮件/短信的手机端站点根
  294. */
  295. protected function resolveMprocMobilePublicBaseUrl()
  296. {
  297. $candidates = [];
  298. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  299. $candidates[] = trim((string)Config::get('site.indexurl'));
  300. $cdn = trim((string)Config::get('site.cdnurl'));
  301. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  302. $candidates[] = rtrim($cdn, '/');
  303. }
  304. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  305. $candidates[] = $reqBase;
  306. foreach ($candidates as $c) {
  307. if ($c === '') {
  308. continue;
  309. }
  310. $c = rtrim($c, '/');
  311. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  312. return $c;
  313. }
  314. }
  315. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  316. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  317. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  318. return $reqBase;
  319. }
  320. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  321. return '';
  322. }
  323. /**
  324. * 获取 Redis 中 procuremen_redis
  325. */
  326. protected function ProcuremenRedis(): array
  327. {
  328. if ($this->procuremenRedisCache !== null) {
  329. return $this->procuremenRedisCache;
  330. }
  331. try {
  332. $redis = redis();
  333. $raw = $redis->get('procuremen_redis');
  334. if ($raw === false || $raw === '') {
  335. $this->procuremenRedisCache = [];
  336. return $this->procuremenRedisCache;
  337. }
  338. $decoded = json_decode($raw, true);
  339. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  340. $this->procuremenRedisCache = [];
  341. return $this->procuremenRedisCache;
  342. }
  343. $this->procuremenRedisCache = $decoded['data'];
  344. return $this->procuremenRedisCache;
  345. } catch (\Throwable $e) {
  346. $this->procuremenRedisCache = [];
  347. return $this->procuremenRedisCache;
  348. }
  349. }
  350. /**
  351. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  352. *
  353. * @return array<int, array<string, mixed>>
  354. */
  355. protected function procuremenFetchErpPoolFromDb(): array
  356. {
  357. try {
  358. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  359. $endTime = date('Y-m-d 23:59:59');
  360. $list = Db::table('scydgy')
  361. ->alias('a')
  362. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  363. ->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, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  364. ->where([
  365. 'a.bwjg' => 1,
  366. 'a.iEndBz' => 0,
  367. 'a.iType' => 0,
  368. 'a.iStatus' => 10,
  369. ])
  370. ->where('a.dStamp', '>=', $startTime)
  371. ->where('a.dStamp', '<=', $endTime)
  372. ->order('a.dStamp', 'desc')
  373. ->select();
  374. if (!is_array($list)) {
  375. return [];
  376. }
  377. try {
  378. $redis = redis();
  379. $payload = [
  380. 'code' => 200,
  381. 'msg' => 'success',
  382. 'data' => $list,
  383. ];
  384. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  385. $this->procuremenRedisCache = $list;
  386. } catch (\Throwable $e) {
  387. }
  388. return $list;
  389. } catch (\Throwable $e) {
  390. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  391. return [];
  392. }
  393. }
  394. /**
  395. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  396. *
  397. * @return array<int, array<string, mixed>>
  398. */
  399. protected function procuremenEnsureRedisPool(): array
  400. {
  401. $pool = $this->ProcuremenRedis();
  402. if (is_array($pool) && $pool !== []) {
  403. return $pool;
  404. }
  405. static $warmed = false;
  406. if ($warmed) {
  407. return is_array($pool) ? $pool : [];
  408. }
  409. $warmed = true;
  410. return $this->procuremenFetchErpPoolFromDb();
  411. }
  412. /**
  413. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  414. *
  415. * @param array<string, mixed> $row
  416. */
  417. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  418. {
  419. $t = $this->procuremenRowListSortTime($row, $primary);
  420. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  421. return null;
  422. }
  423. $mo = (int)$m[2];
  424. if ($mo < 1 || $mo > 12) {
  425. return null;
  426. }
  427. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  428. }
  429. /**
  430. * @param array<int, array{year:string, months:array}> $sidebar
  431. * @return array<int, array{year:string, months:array}>
  432. */
  433. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  434. {
  435. $ym = trim($ym);
  436. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  437. return $sidebar;
  438. }
  439. foreach ($sidebar as $block) {
  440. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  441. continue;
  442. }
  443. foreach ($block['months'] as $item) {
  444. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  445. return $sidebar;
  446. }
  447. }
  448. }
  449. $y = substr($ym, 0, 4);
  450. $mo = (int)substr($ym, 5, 2);
  451. $sidebar[] = [
  452. 'year' => $y,
  453. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  454. ];
  455. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  456. }
  457. /**
  458. * @param array<int, array{year:string, months:array}> $sidebar
  459. * @return string[]
  460. */
  461. protected function flattenProcuremenSidebarYms(array $sidebar): array
  462. {
  463. $yms = [];
  464. foreach ($sidebar as $block) {
  465. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  466. continue;
  467. }
  468. foreach ($block['months'] as $item) {
  469. if (!is_array($item)) {
  470. continue;
  471. }
  472. $ym = trim((string)($item['ym'] ?? ''));
  473. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  474. $yms[$ym] = true;
  475. }
  476. }
  477. }
  478. return array_keys($yms);
  479. }
  480. /**
  481. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  482. */
  483. protected function GetIndexYearMonths()
  484. {
  485. $ymSet = [];
  486. $pool = $this->procuremenEnsureRedisPool();
  487. foreach ($pool as $r) {
  488. if (!is_array($r)) {
  489. continue;
  490. }
  491. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  492. if ($ym !== null) {
  493. $ymSet[$ym] = true;
  494. }
  495. }
  496. foreach ($this->loadPickManualOrderRows() as $r) {
  497. if (!is_array($r)) {
  498. continue;
  499. }
  500. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  501. if ($ym !== null) {
  502. $ymSet[$ym] = true;
  503. }
  504. }
  505. $ymList = array_keys($ymSet);
  506. if ($ymList === []) {
  507. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  508. }
  509. return $this->buildYearMonthSidebar($ymList);
  510. }
  511. /**
  512. * @param string[] $ymList 形如 2026-06
  513. * @return array<int, array{year:string, months:array}>
  514. */
  515. protected function buildYearMonthSidebar(array $ymList): array
  516. {
  517. rsort($ymList, SORT_STRING);
  518. $byYear = [];
  519. foreach ($ymList as $ym) {
  520. $y = substr($ym, 0, 4);
  521. $mo = (int)substr($ym, 5, 2);
  522. if (!isset($byYear[$y])) {
  523. $byYear[$y] = [];
  524. }
  525. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  526. }
  527. krsort($byYear, SORT_NUMERIC);
  528. foreach ($byYear as $y => $items) {
  529. usort($byYear[$y], function ($a, $b) {
  530. return strcmp($b['ym'], $a['ym']);
  531. });
  532. }
  533. $sidebar = [];
  534. foreach ($byYear as $y => $months) {
  535. $sidebar[] = ['year' => $y, 'months' => $months];
  536. }
  537. return $sidebar;
  538. }
  539. /**
  540. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  541. */
  542. protected function GetIssuedOrderYearMonths(string $stage): array
  543. {
  544. $ymSet = [];
  545. try {
  546. $query = Db::table('purchase_order');
  547. $this->applyPurchaseOrderNotDeletedWhere($query);
  548. if ($stage === 'audit') {
  549. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  550. } elseif ($stage === 'confirm') {
  551. $this->applyPurchaseOrderConfirmStageWhere($query);
  552. } else {
  553. return $this->GetIndexYearMonths();
  554. }
  555. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  556. if (is_array($rows)) {
  557. foreach ($rows as $r) {
  558. if (!is_array($r)) {
  559. continue;
  560. }
  561. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  562. if ($ym !== null) {
  563. $ymSet[$ym] = true;
  564. }
  565. }
  566. }
  567. } catch (\Throwable $e) {
  568. $ymSet = [];
  569. }
  570. $ymList = array_keys($ymSet);
  571. if ($ymList === []) {
  572. $def = $this->resolveProcuremenDefaultYm($stage);
  573. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  574. }
  575. return $this->buildYearMonthSidebar($ymList);
  576. }
  577. /**
  578. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  579. */
  580. protected function resolveProcuremenDefaultYm(string $stage): string
  581. {
  582. if ($stage === 'pick') {
  583. return date('Y-m');
  584. }
  585. try {
  586. $query = Db::table('purchase_order');
  587. $this->applyPurchaseOrderNotDeletedWhere($query);
  588. if ($stage === 'audit') {
  589. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  590. } elseif ($stage === 'confirm') {
  591. $this->applyPurchaseOrderConfirmStageWhere($query);
  592. } else {
  593. return date('Y-m');
  594. }
  595. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  596. if ($latest === null || $latest === '') {
  597. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  598. }
  599. $t = $this->formatProcuremenDetailTime($latest);
  600. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  601. return $m[1] . '-' . $m[2];
  602. }
  603. } catch (\Throwable $e) {
  604. }
  605. return date('Y-m');
  606. }
  607. protected function applyPurchaseOrderNotDeletedWhere($query): void
  608. {
  609. $query->whereRaw(
  610. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  611. );
  612. }
  613. /**
  614. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  615. */
  616. protected function applyPurchaseOrderConfirmStageWhere($query): void
  617. {
  618. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  619. $quoted = [];
  620. foreach ($vals as $v) {
  621. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  622. }
  623. if ($quoted === []) {
  624. $query->whereRaw('1 = 0');
  625. return;
  626. }
  627. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  628. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  629. }
  630. /**
  631. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  632. *
  633. * @param array<string, mixed> $row
  634. * @return array<string, mixed>
  635. */
  636. protected function normalizePurchaseOrderListTimeRow(array $row): array
  637. {
  638. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  639. $pick = trim((string)($row['pick_time'] ?? ''));
  640. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  641. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  642. $t = trim((string)($row[$key] ?? ''));
  643. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  644. $row['pick_time'] = $t;
  645. break;
  646. }
  647. }
  648. }
  649. return $row;
  650. }
  651. /**
  652. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  653. */
  654. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  655. {
  656. if (!in_array($stage, ['audit', 'confirm'], true)) {
  657. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  658. }
  659. if ($pool === []) {
  660. $def = $this->resolveProcuremenDefaultYm($stage);
  661. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  662. }
  663. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  664. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  665. return false;
  666. }
  667. $monthStart = $ym . '-01 00:00:00';
  668. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  669. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  670. return $probe !== [];
  671. };
  672. if ($tryYm($requestedYm)) {
  673. return $requestedYm;
  674. }
  675. $fallback = $this->resolveProcuremenDefaultYm($stage);
  676. if ($tryYm($fallback)) {
  677. return $fallback;
  678. }
  679. $bestYm = '';
  680. $bestTime = '';
  681. foreach ($pool as $row) {
  682. if (!is_array($row)) {
  683. continue;
  684. }
  685. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  686. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  687. continue;
  688. }
  689. $ymRow = $m[1];
  690. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  691. $bestTime = $t;
  692. $bestYm = $ymRow;
  693. }
  694. }
  695. if ($bestYm !== '') {
  696. return $bestYm;
  697. }
  698. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  699. }
  700. protected function isPurchaseOrderDetailVoid(array $row): bool
  701. {
  702. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  703. return true;
  704. }
  705. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  706. }
  707. /**
  708. * 仅当前有效下发明细(排除废弃归档)
  709. */
  710. protected function applyActivePurchaseOrderDetailWhere($query): void
  711. {
  712. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  713. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  714. }
  715. /**
  716. * @param array<string, mixed> $detailRow
  717. */
  718. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  719. {
  720. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  721. return false;
  722. }
  723. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  724. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  725. }
  726. /**
  727. * 废弃退回初选:下发明细标记归档,不物理删除
  728. *
  729. * @param array<int, int|string> $scydgyIds
  730. */
  731. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  732. {
  733. $ids = [];
  734. foreach ($scydgyIds as $sid) {
  735. $n = (int)$sid;
  736. if ($this->isValidScydgyRowId($n) || $n < 0) {
  737. $ids[$n] = true;
  738. }
  739. }
  740. if ($ids === []) {
  741. return;
  742. }
  743. $void = ProcuremenStatus::POD_VOID;
  744. Db::table('purchase_order_detail')
  745. ->where('scydgy_id', 'in', array_keys($ids))
  746. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  747. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  748. ->update([
  749. 'status' => $void,
  750. 'status_name' => $void,
  751. ]);
  752. }
  753. /**
  754. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  755. */
  756. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  757. {
  758. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  759. $norm = function (string $col) use ($p): string {
  760. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  761. };
  762. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  763. $parts = [];
  764. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  765. if ($key === 'createtime') {
  766. $parts[] = $createtime;
  767. } else {
  768. $parts[] = $norm($key);
  769. }
  770. }
  771. return 'COALESCE(' . implode(', ', $parts) . ')';
  772. }
  773. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  774. {
  775. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  776. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  777. }
  778. /**
  779. * @return array<int, array<string, mixed>>
  780. */
  781. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  782. {
  783. $this->ensurePurchaseOrderCzlyqColumn();
  784. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  785. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  786. try {
  787. $query = Db::table('purchase_order')->field($fields);
  788. $this->applyPurchaseOrderNotDeletedWhere($query);
  789. if ($stage === 'audit') {
  790. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  791. } elseif ($stage === 'confirm') {
  792. $this->applyPurchaseOrderConfirmStageWhere($query);
  793. } else {
  794. return [];
  795. }
  796. $query->order('pick_time', 'desc')->order('id', 'desc');
  797. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  798. $monthStart = $ym . '-01 00:00:00';
  799. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  800. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  801. }
  802. $rows = $query->select();
  803. } catch (\Throwable $e) {
  804. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  805. $rows = [];
  806. }
  807. return is_array($rows) ? $rows : [];
  808. }
  809. /**
  810. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  811. */
  812. protected function resolveProcuremenListStage(): string
  813. {
  814. $tab = trim((string)$this->request->request('wff_tab', ''));
  815. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  816. return $tab;
  817. }
  818. $action = strtolower((string)$this->request->action());
  819. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  820. return $action;
  821. }
  822. return 'pick';
  823. }
  824. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  825. {
  826. $rootTrue = rtrim((string)$this->request->root(true), '/');
  827. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  828. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  829. $indexPhpRoot = $rootTrue . '/index.php';
  830. }
  831. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  832. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  833. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  834. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  835. $this->view->assign('defaultYm', $defaultYm);
  836. $this->view->assign('sidebarYearMonths', $sidebar);
  837. $this->view->assign('procuremenStage', $stage);
  838. $this->view->assign('procuremenPageTitle', $pageTitle);
  839. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  840. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  841. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  842. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  843. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  844. }
  845. /**
  846. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  847. *
  848. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  849. */
  850. protected function buildProcuremenFilterOptions(string $stage): array
  851. {
  852. $buckets = [
  853. 'czlyq' => [],
  854. 'CCLBMMC' => [],
  855. 'cywyxm' => [],
  856. 'CGYMC' => [],
  857. ];
  858. $maxPerField = 300;
  859. try {
  860. if ($stage === 'pick') {
  861. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  862. return $buckets;
  863. }
  864. if (in_array($stage, ['audit', 'confirm'], true)) {
  865. $this->ensurePurchaseOrderCzlyqColumn();
  866. foreach (array_keys($buckets) as $field) {
  867. try {
  868. $query = Db::table('purchase_order')->field($field);
  869. $this->applyPurchaseOrderNotDeletedWhere($query);
  870. if ($stage === 'audit') {
  871. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  872. } else {
  873. $this->applyPurchaseOrderConfirmStageWhere($query);
  874. }
  875. $query->where($field, '<>', '')->whereNotNull($field);
  876. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  877. if (!is_array($vals)) {
  878. continue;
  879. }
  880. foreach ($vals as $v) {
  881. $v = trim((string)$v);
  882. if ($v !== '') {
  883. $buckets[$field][$v] = $v;
  884. }
  885. }
  886. } catch (\Throwable $e) {
  887. // 单字段失败不影响其它
  888. }
  889. }
  890. }
  891. } catch (\Throwable $e) {
  892. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  893. }
  894. foreach ($buckets as &$set) {
  895. if ($set !== []) {
  896. ksort($set, SORT_STRING);
  897. }
  898. }
  899. unset($set);
  900. return $buckets;
  901. }
  902. /**
  903. * filter JSON 是否含有效条件
  904. *
  905. * @param array<string, mixed> $filterArr
  906. */
  907. protected function procuremenFilterArrHasValue(array $filterArr): bool
  908. {
  909. foreach ($filterArr as $v) {
  910. if (is_array($v)) {
  911. if (array_filter($v, function ($x) {
  912. return $x !== '' && $x !== null;
  913. })) {
  914. return true;
  915. }
  916. } elseif ($v !== '' && $v !== null) {
  917. return true;
  918. }
  919. }
  920. return false;
  921. }
  922. /**
  923. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  924. *
  925. * @param array<string, mixed> $filterArr
  926. * @param array<string, mixed> $opArr
  927. */
  928. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  929. {
  930. if ($search !== '') {
  931. return false;
  932. }
  933. foreach ($filterArr as $fk => $fv) {
  934. if (is_array($fv)) {
  935. continue;
  936. }
  937. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  938. continue;
  939. }
  940. if ($fv === null) {
  941. continue;
  942. }
  943. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  944. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  945. if ($sym === '' || $sym === '=') {
  946. continue;
  947. }
  948. return false;
  949. }
  950. return true;
  951. }
  952. /**
  953. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  954. *
  955. * @param array<int, mixed> $rows
  956. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  957. */
  958. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  959. {
  960. $buckets = [
  961. 'czlyq' => [],
  962. 'CCLBMMC' => [],
  963. 'cywyxm' => [],
  964. 'CGYMC' => [],
  965. ];
  966. foreach ($rows as $r) {
  967. if (!is_array($r)) {
  968. continue;
  969. }
  970. foreach ($buckets as $field => &$set) {
  971. if (count($set) >= $maxPerField) {
  972. continue;
  973. }
  974. $v = trim((string)($r[$field] ?? ''));
  975. if ($v !== '') {
  976. $set[$v] = $v;
  977. }
  978. }
  979. unset($set);
  980. $full = true;
  981. foreach ($buckets as $set) {
  982. if (count($set) < $maxPerField) {
  983. $full = false;
  984. break;
  985. }
  986. }
  987. if ($full) {
  988. break;
  989. }
  990. }
  991. foreach ($buckets as &$set) {
  992. if ($set !== []) {
  993. ksort($set, SORT_STRING);
  994. }
  995. }
  996. unset($set);
  997. return $buckets;
  998. }
  999. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1000. public function pick()
  1001. {
  1002. $this->request->filter(['strip_tags', 'trim']);
  1003. if (!$this->request->isAjax()) {
  1004. $this->assignProcuremenListPage('pick', '协助下发');
  1005. return $this->view->fetch('procuremen/index');
  1006. }
  1007. return $this->index();
  1008. }
  1009. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1010. public function audit()
  1011. {
  1012. $this->request->filter(['strip_tags', 'trim']);
  1013. if (!$this->request->isAjax()) {
  1014. $this->assignProcuremenListPage('audit', '确认供应商');
  1015. return $this->view->fetch('procuremen/index');
  1016. }
  1017. return $this->index();
  1018. }
  1019. /** 采购确认(定标) */
  1020. public function confirm()
  1021. {
  1022. $this->request->filter(['strip_tags', 'trim']);
  1023. if (!$this->request->isAjax()) {
  1024. $this->assignProcuremenListPage('confirm', '采购确认');
  1025. return $this->view->fetch('procuremen/index');
  1026. }
  1027. return $this->index();
  1028. }
  1029. /**
  1030. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1031. */
  1032. public function index()
  1033. {
  1034. $this->request->filter(['strip_tags', 'trim']);
  1035. if (!$this->request->isAjax()) {
  1036. $this->assignProcuremenListPage('pick', '协助下发');
  1037. return $this->view->fetch('procuremen/index');
  1038. }
  1039. if ($this->request->request('keyField')) {
  1040. return $this->selectpage();
  1041. }
  1042. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1043. $limit = max(10, min(500, (int)$limit));
  1044. $ym = $this->request->request('ym', '');
  1045. $ym = is_string($ym) ? trim($ym) : '';
  1046. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1047. $wffTab = $this->resolveProcuremenListStage();
  1048. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1049. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1050. ? $this->resolveProcuremenDefaultYm($wffTab)
  1051. : date('Y-m');
  1052. }
  1053. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1054. $ym = date('Y-m');
  1055. }
  1056. $monthStart = $ym . '-01 00:00:00';
  1057. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1058. $search = trim((string)$this->request->get('search', ''));
  1059. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1060. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1061. if (!is_array($filterArr)) {
  1062. $filterArr = [];
  1063. }
  1064. if (!is_array($opArr)) {
  1065. $opArr = [];
  1066. }
  1067. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1068. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1069. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1070. try {
  1071. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1072. if ($wffTab === 'audit') {
  1073. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1074. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1075. );
  1076. } elseif ($wffTab === 'confirm') {
  1077. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1078. if ($dbRows === []) {
  1079. try {
  1080. $dbRows = Db::table('purchase_order')
  1081. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1082. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1083. ->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%\')')
  1084. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1085. ->order('pick_time', 'desc')->order('id', 'desc')
  1086. ->select();
  1087. } catch (\Throwable $e) {
  1088. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1089. $dbRows = [];
  1090. }
  1091. }
  1092. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1093. if ($pool === []) {
  1094. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1095. }
  1096. } else {
  1097. $pool = $this->procuremenEnsureRedisPool();
  1098. if (!is_array($pool)) {
  1099. $pool = [];
  1100. }
  1101. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  1102. $hideSet = $this->loadPickHiddenScydgySet();
  1103. if ($pool !== [] && $hideSet !== []) {
  1104. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1105. if (!is_array($r)) {
  1106. return false;
  1107. }
  1108. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1109. return $id <= 0 || !isset($hideSet[$id]);
  1110. }));
  1111. }
  1112. $manualPool = $this->loadPickManualOrderRows();
  1113. if ($manualPool !== []) {
  1114. $pool = array_merge($pool, $manualPool);
  1115. }
  1116. if ($pool === []) {
  1117. return json([
  1118. 'total' => 0,
  1119. 'rows' => [],
  1120. ]);
  1121. }
  1122. }
  1123. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1124. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1125. $monthStart = $ym . '-01 00:00:00';
  1126. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1127. }
  1128. $filtered = $this->filterProcuremenIndexPool(
  1129. $pool,
  1130. $monthStart,
  1131. $monthEnd,
  1132. $applyMonthRange,
  1133. $search,
  1134. $filterArr,
  1135. $opArr,
  1136. $listTimePrimary
  1137. );
  1138. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1139. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1140. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1141. }
  1142. $sortField = 'ID';
  1143. if (is_string($sort) && $sort !== '') {
  1144. $parts = explode(',', $sort);
  1145. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1146. if ($sortField === '') {
  1147. $sortField = 'ID';
  1148. }
  1149. }
  1150. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1151. $nFiltered = count($filtered);
  1152. if ($nFiltered > 1) {
  1153. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1154. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1155. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1156. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1157. if ($ta === $tb) {
  1158. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1159. }
  1160. if ($ta === '') {
  1161. return 1;
  1162. }
  1163. if ($tb === '') {
  1164. return -1;
  1165. }
  1166. return strcmp($ta, $tb) * $ord;
  1167. });
  1168. } elseif ($sortField === 'ID') {
  1169. $sortKeys = [];
  1170. foreach ($filtered as $i => $row) {
  1171. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1172. }
  1173. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1174. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1175. } elseif ($sortField === 'CCYDH') {
  1176. usort($filtered, function ($a, $b) use ($ord) {
  1177. $sa = trim((string)($a['CCYDH'] ?? ''));
  1178. $sb = trim((string)($b['CCYDH'] ?? ''));
  1179. if ($sa === $sb) {
  1180. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1181. }
  1182. if ($sa === '') {
  1183. return 1;
  1184. }
  1185. if ($sb === '') {
  1186. return -1;
  1187. }
  1188. return strcmp($sa, $sb) * $ord;
  1189. });
  1190. } else {
  1191. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1192. $va = $a[$sortField] ?? null;
  1193. $vb = $b[$sortField] ?? null;
  1194. $sa = (string)$va;
  1195. $sb = (string)$vb;
  1196. if ($sa === $sb) {
  1197. return 0;
  1198. }
  1199. return strcmp($sa, $sb) * $ord;
  1200. });
  1201. }
  1202. }
  1203. $offset = max(0, (int)$offset);
  1204. $limit = max(1, (int)$limit);
  1205. $rows = array_slice($filtered, $offset, $limit);
  1206. foreach ($rows as &$rw) {
  1207. if (!is_array($rw)) {
  1208. continue;
  1209. }
  1210. $rid = (int)($rw['ID'] ?? 0);
  1211. $rw['_iss_out'] = ($wffTab !== 'pick');
  1212. }
  1213. unset($rw);
  1214. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1215. $idList = [];
  1216. foreach ($rows as $rw) {
  1217. if (!is_array($rw)) {
  1218. continue;
  1219. }
  1220. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1221. foreach ($rw['_order_merge_rows'] as $mr) {
  1222. $mid = (int)($mr['ID'] ?? 0);
  1223. if ($this->isValidScydgyRowId($mid)) {
  1224. $idList[$mid] = true;
  1225. }
  1226. }
  1227. }
  1228. $id = (int)($rw['ID'] ?? 0);
  1229. if ($this->isValidScydgyRowId($id)) {
  1230. $idList[$id] = true;
  1231. }
  1232. }
  1233. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1234. foreach ($rows as &$rw) {
  1235. if (!is_array($rw)) {
  1236. continue;
  1237. }
  1238. $mergeIds = [];
  1239. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1240. foreach ($rw['_order_merge_rows'] as $mr) {
  1241. $mid = (int)($mr['ID'] ?? 0);
  1242. if ($this->isValidScydgyRowId($mid)) {
  1243. $mergeIds[$mid] = true;
  1244. }
  1245. }
  1246. }
  1247. $rid = (int)($rw['ID'] ?? 0);
  1248. if ($this->isValidScydgyRowId($rid)) {
  1249. $mergeIds[$rid] = true;
  1250. }
  1251. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1252. $rw['po_detail_count'] = $s['cnt'];
  1253. $rw['po_amount_fill_cnt'] = $s['amt'];
  1254. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1255. }
  1256. unset($rw);
  1257. }
  1258. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1259. $idList = [];
  1260. foreach ($rows as $rw) {
  1261. if (!is_array($rw)) {
  1262. continue;
  1263. }
  1264. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1265. foreach ($rw['_order_merge_rows'] as $mr) {
  1266. $mid = (int)($mr['ID'] ?? 0);
  1267. if ($this->isValidScydgyRowId($mid)) {
  1268. $idList[$mid] = true;
  1269. }
  1270. }
  1271. }
  1272. $id = (int)($rw['ID'] ?? 0);
  1273. if ($this->isValidScydgyRowId($id)) {
  1274. $idList[$id] = true;
  1275. }
  1276. }
  1277. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1278. $bidOpenSet = [];
  1279. if ($wffTab === 'audit') {
  1280. $ccydhList = [];
  1281. foreach ($rows as $rw0) {
  1282. if (!is_array($rw0)) {
  1283. continue;
  1284. }
  1285. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1286. if ($c0 !== '') {
  1287. $ccydhList[] = $c0;
  1288. }
  1289. }
  1290. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1291. }
  1292. foreach ($rows as &$rw) {
  1293. if (!is_array($rw)) {
  1294. continue;
  1295. }
  1296. $mergeIds = [];
  1297. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1298. foreach ($rw['_order_merge_rows'] as $mr) {
  1299. $mid = (int)($mr['ID'] ?? 0);
  1300. if ($this->isValidScydgyRowId($mid)) {
  1301. $mergeIds[$mid] = true;
  1302. }
  1303. }
  1304. }
  1305. $rid = (int)($rw['ID'] ?? 0);
  1306. if ($this->isValidScydgyRowId($rid)) {
  1307. $mergeIds[$rid] = true;
  1308. }
  1309. $buckets = [];
  1310. foreach (array_keys($mergeIds) as $mid) {
  1311. if (isset($quoteBucket[$mid])) {
  1312. $buckets[] = $quoteBucket[$mid];
  1313. }
  1314. }
  1315. $supplierText = $buckets !== []
  1316. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1317. : '';
  1318. if ($wffTab === 'confirm') {
  1319. $rw['picked_supplier_name'] = $supplierText;
  1320. } else {
  1321. $rw['notify_supplier_text'] = $supplierText;
  1322. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1323. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1324. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1325. $rw['bid_open_status_text'] = $verified ? '已开标' : '待开标';
  1326. }
  1327. }
  1328. unset($rw);
  1329. }
  1330. if ($wffTab === 'all' && count($rows) > 0) {
  1331. $this->mergePurchaseOrder($rows);
  1332. }
  1333. if ($wffTab === 'pick' && count($rows) > 0) {
  1334. $this->mergePurchaseOrder($rows);
  1335. }
  1336. foreach ($rows as &$rwClean) {
  1337. if (is_array($rwClean)) {
  1338. unset($rwClean['_order_merge_rows']);
  1339. if (array_key_exists('NGZL', $rwClean)) {
  1340. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1341. }
  1342. }
  1343. }
  1344. unset($rwClean);
  1345. return json([
  1346. 'total' => count($filtered),
  1347. 'rows' => $rows,
  1348. 'activeYm' => $ym,
  1349. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1350. 'filterOptions' => (
  1351. (int)$offset === 0
  1352. && !$hasActiveSearch
  1353. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1354. )
  1355. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1356. : new \stdClass(),
  1357. ]);
  1358. } catch (\Throwable $e) {
  1359. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1360. return json([
  1361. 'total' => 0,
  1362. 'rows' => [],
  1363. ]);
  1364. }
  1365. }
  1366. /**
  1367. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1368. *
  1369. * @return array<int, true>
  1370. */
  1371. protected function loadPickHiddenScydgySet(): array
  1372. {
  1373. if ($this->pickHiddenScydgySetCache !== null) {
  1374. return $this->pickHiddenScydgySetCache;
  1375. }
  1376. $hideSet = [];
  1377. try {
  1378. $poIds = Db::table('purchase_order')
  1379. ->where(function ($q) {
  1380. $q->whereIn('wflow_status', array_merge(
  1381. ProcuremenStatus::wflowPendingConfirmValues(),
  1382. ProcuremenStatus::wflowPendingApprovalValues()
  1383. ))
  1384. ->whereOr(function ($q1) {
  1385. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1386. })
  1387. ->whereOr(function ($q2) {
  1388. $q2->whereNotNull('pick_time')
  1389. ->where('pick_time', '<>', '')
  1390. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1391. })
  1392. ->whereOr(function ($q3) {
  1393. $q3->whereNotNull('mod_rq')
  1394. ->where('mod_rq', '<>', '')
  1395. ->where('mod_rq', 'not like', '0000-00-00%');
  1396. });
  1397. })
  1398. ->column('scydgy_id');
  1399. if (is_array($poIds)) {
  1400. foreach ($poIds as $pid) {
  1401. $k = (int)$pid;
  1402. if ($k !== 0) {
  1403. $hideSet[$k] = true;
  1404. }
  1405. }
  1406. }
  1407. } catch (\Throwable $e) {
  1408. }
  1409. try {
  1410. $detIdsQuery = Db::table('purchase_order_detail');
  1411. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1412. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1413. if (is_array($detIds)) {
  1414. foreach ($detIds as $pid) {
  1415. $k = (int)$pid;
  1416. if ($this->isValidScydgyRowId($k)) {
  1417. $hideSet[$k] = true;
  1418. }
  1419. }
  1420. }
  1421. } catch (\Throwable $e) {
  1422. }
  1423. $this->pickHiddenScydgySetCache = $hideSet;
  1424. return $hideSet;
  1425. }
  1426. /**
  1427. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1428. *
  1429. * @return array<int, array<string, mixed>>
  1430. */
  1431. protected function loadPickManualOrderRows(): array
  1432. {
  1433. try {
  1434. $dbRows = Db::table('purchase_order')
  1435. ->where('scydgy_id', '<', 0)
  1436. ->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%\')')
  1437. ->order('scydgy_id', 'asc')
  1438. ->select();
  1439. } catch (\Throwable $e) {
  1440. try {
  1441. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1442. } catch (\Throwable $e2) {
  1443. return [];
  1444. }
  1445. }
  1446. if (!is_array($dbRows) || $dbRows === []) {
  1447. return [];
  1448. }
  1449. $detailSidSet = [];
  1450. try {
  1451. $negIds = [];
  1452. foreach ($dbRows as $dbRow) {
  1453. if (!is_array($dbRow)) {
  1454. continue;
  1455. }
  1456. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1457. if ($sid < 0) {
  1458. $negIds[$sid] = true;
  1459. }
  1460. }
  1461. if ($negIds !== []) {
  1462. $detQuery = Db::table('purchase_order_detail')
  1463. ->where('scydgy_id', 'in', array_keys($negIds));
  1464. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1465. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1466. if (is_array($detRows)) {
  1467. foreach ($detRows as $did) {
  1468. $detailSidSet[(int)$did] = true;
  1469. }
  1470. }
  1471. }
  1472. } catch (\Throwable $e) {
  1473. }
  1474. $pool = [];
  1475. foreach ($dbRows as $dbRow) {
  1476. if (!is_array($dbRow)) {
  1477. continue;
  1478. }
  1479. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1480. if ($sid >= 0) {
  1481. continue;
  1482. }
  1483. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1484. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1485. continue;
  1486. }
  1487. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1488. // 仅排除已完结;「进行中」含待下发的新建手工单,必须出现在初选
  1489. if ($st === ProcuremenStatus::PO_COMPLETED) {
  1490. continue;
  1491. }
  1492. if (isset($detailSidSet[$sid])) {
  1493. continue;
  1494. }
  1495. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1496. $r['_is_manual'] = 1;
  1497. $pool[] = $r;
  1498. }
  1499. return $pool;
  1500. }
  1501. /**
  1502. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1503. */
  1504. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1505. {
  1506. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1507. foreach ($keys as $k) {
  1508. $t = trim((string)($row[$k] ?? ''));
  1509. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1510. return $t;
  1511. }
  1512. }
  1513. return '';
  1514. }
  1515. /**
  1516. * 分配手工新增工序行 ID(负数递减)
  1517. */
  1518. protected function allocateManualScydgyId(): int
  1519. {
  1520. try {
  1521. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1522. $min = (int)$min;
  1523. return $min < 0 ? $min - 1 : -1;
  1524. } catch (\Throwable $e) {
  1525. return -1;
  1526. }
  1527. }
  1528. /**
  1529. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1530. */
  1531. protected function allocateManualOrderCcydh(): string
  1532. {
  1533. $prefix = 'YW' . date('Ymd');
  1534. $maxSeq = 0;
  1535. try {
  1536. $rows = Db::table('purchase_order')
  1537. ->where('CCYDH', 'like', $prefix . '%')
  1538. ->column('CCYDH');
  1539. if (is_array($rows)) {
  1540. foreach ($rows as $ccydh) {
  1541. $ccydh = trim((string)$ccydh);
  1542. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1543. $maxSeq = max($maxSeq, (int)$m[1]);
  1544. }
  1545. }
  1546. }
  1547. } catch (\Throwable $e) {
  1548. }
  1549. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1550. }
  1551. /**
  1552. * purchase_order.mod_rq 是否有有效软删除时间
  1553. */
  1554. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1555. {
  1556. $t = trim((string)$modRq);
  1557. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1558. }
  1559. /**
  1560. * 列表行 → purchase_order 写入字段
  1561. *
  1562. * @return array<string, mixed>
  1563. */
  1564. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1565. {
  1566. return [
  1567. 'scydgy_id' => $scydgyId,
  1568. 'CCYDH' => $row['CCYDH'] ?? null,
  1569. 'CYJMC' => $row['CYJMC'] ?? null,
  1570. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1571. 'CDXMC' => $row['CDXMC'] ?? null,
  1572. 'CGYBH' => $row['CGYBH'] ?? null,
  1573. 'CGYMC' => $row['CGYMC'] ?? null,
  1574. 'CDW' => $row['CDW'] ?? null,
  1575. 'czlyq' => $row['czlyq'] ?? null,
  1576. 'NGZL' => $row['NGZL'] ?? null,
  1577. 'CDF' => $row['CDF'] ?? null,
  1578. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1579. 'MBZ' => $row['MBZ'] ?? null,
  1580. 'bwjg' => $row['bwjg'] ?? null,
  1581. 'iStatus' => $row['iStatus'] ?? null,
  1582. 'dStamp' => $row['dStamp'] ?? null,
  1583. 'dputrecord' => $row['dputrecord'] ?? null,
  1584. 'cywyxm' => $row['cywyxm'] ?? null,
  1585. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1586. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1587. ];
  1588. }
  1589. /**
  1590. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1591. *
  1592. * @return array{po:?array<string,mixed>, hidden:bool}
  1593. */
  1594. protected function resolvePickRowPoContext(int $sid): array
  1595. {
  1596. $po = null;
  1597. try {
  1598. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1599. if (is_array($found)) {
  1600. $po = $found;
  1601. }
  1602. } catch (\Throwable $e) {
  1603. }
  1604. $hideSet = $this->loadPickHiddenScydgySet();
  1605. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1606. }
  1607. /**
  1608. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1609. */
  1610. protected function assertPickRowCanDelete(int $sid, array $row): void
  1611. {
  1612. $ctx = $this->resolvePickRowPoContext($sid);
  1613. $po = $ctx['po'];
  1614. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1615. return;
  1616. }
  1617. if (is_array($po)) {
  1618. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1619. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1620. }
  1621. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1622. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1623. }
  1624. }
  1625. if ($ctx['hidden']) {
  1626. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1627. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1628. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1629. }
  1630. }
  1631. /**
  1632. * 初选直接完结前校验
  1633. */
  1634. protected function assertPickRowCanComplete(int $sid, array $row): void
  1635. {
  1636. $ctx = $this->resolvePickRowPoContext($sid);
  1637. $po = $ctx['po'];
  1638. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1639. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1640. }
  1641. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1642. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1643. }
  1644. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1645. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1646. }
  1647. }
  1648. /**
  1649. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1650. */
  1651. protected function softDeleteProcuremenPickRow(array $row): void
  1652. {
  1653. $sid = $this->extractScydgyRowId($row);
  1654. if (!$this->isValidScydgyRowId($sid)) {
  1655. throw new \InvalidArgumentException('无效的行主键');
  1656. }
  1657. $this->assertPickRowCanDelete($sid, $row);
  1658. $po = $this->resolvePickRowPoContext($sid)['po'];
  1659. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1660. return;
  1661. }
  1662. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1663. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1664. }
  1665. $now = date('Y-m-d H:i:s');
  1666. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1667. if (is_array($exists)) {
  1668. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1669. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1670. } else {
  1671. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1672. $data['mod_rq'] = $now;
  1673. $data['createtime'] = $now;
  1674. Db::table('purchase_order')->insert($data);
  1675. $poIdLog = (int)Db::getLastInsID();
  1676. }
  1677. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1678. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1679. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1680. if ($gymcLog !== '') {
  1681. $logTail .= ' / ' . $gymcLog;
  1682. }
  1683. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1684. }
  1685. /**
  1686. * 手工新增协助工序(写入 purchase_order)
  1687. *
  1688. * @param array<string, mixed> $params
  1689. * @return int scydgy_id
  1690. */
  1691. protected function saveManualPickOrder(array $params): int
  1692. {
  1693. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1694. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1695. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1696. if ($ccydh === '') {
  1697. $ccydh = $this->allocateManualOrderCcydh();
  1698. }
  1699. $now = date('Y-m-d H:i:s');
  1700. $sid = $this->allocateManualScydgyId();
  1701. $data = [
  1702. 'scydgy_id' => $sid,
  1703. 'CCYDH' => $ccydh,
  1704. 'CYJMC' => $cyjmc,
  1705. 'CGYMC' => $cgymc,
  1706. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1707. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1708. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1709. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1710. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1711. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1712. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1713. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1714. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1715. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1716. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  1717. 'createtime' => $now,
  1718. 'dStamp' => $now,
  1719. 'dputrecord' => $now,
  1720. ];
  1721. Db::table('purchase_order')->insert($data);
  1722. $poId = (int)Db::getLastInsID();
  1723. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1724. return $sid;
  1725. }
  1726. protected function formatProcuremenRowLabel(array $row): string
  1727. {
  1728. $dh = trim((string)($row['CCYDH'] ?? ''));
  1729. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1730. if ($dh !== '' && $gymc !== '') {
  1731. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1732. }
  1733. if ($dh !== '') {
  1734. return '订单「' . $dh . '」';
  1735. }
  1736. if ($gymc !== '') {
  1737. return '工序「' . $gymc . '」';
  1738. }
  1739. $id = $this->extractScydgyRowId($row);
  1740. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1741. }
  1742. /**
  1743. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1744. */
  1745. protected function extractScydgyRowId(array $row): int
  1746. {
  1747. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  1748. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  1749. return (int)$row['scydgy_id'];
  1750. }
  1751. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  1752. return (int)$row['SCYDGY_ID'];
  1753. }
  1754. return (int)($row['ID'] ?? $row['id'] ?? 0);
  1755. }
  1756. protected function isValidScydgyRowId(int $id): bool
  1757. {
  1758. return ProcuremenGuard::isValidScydgyId($id);
  1759. }
  1760. protected function isManualScydgyRowId(int $id): bool
  1761. {
  1762. return $id < 0;
  1763. }
  1764. /**
  1765. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1766. *
  1767. * @param int[] $scydgyIds
  1768. * @return array<int, string[]>
  1769. */
  1770. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1771. {
  1772. $out = [];
  1773. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1774. if ($scydgyIds === []) {
  1775. return $out;
  1776. }
  1777. try {
  1778. $rows = Db::table('purchase_order_detail')
  1779. ->where('scydgy_id', 'in', $scydgyIds)
  1780. ->field('scydgy_id,company_name')
  1781. ->order('company_name', 'asc')
  1782. ->select();
  1783. } catch (\Throwable $e) {
  1784. $rows = [];
  1785. }
  1786. if (!is_array($rows)) {
  1787. return $out;
  1788. }
  1789. foreach ($rows as $r) {
  1790. if (!is_array($r)) {
  1791. continue;
  1792. }
  1793. $sid = (int)($r['scydgy_id'] ?? 0);
  1794. $cn = trim((string)($r['company_name'] ?? ''));
  1795. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1796. continue;
  1797. }
  1798. if (!isset($out[$sid])) {
  1799. $out[$sid] = [];
  1800. }
  1801. if (!in_array($cn, $out[$sid], true)) {
  1802. $out[$sid][] = $cn;
  1803. }
  1804. }
  1805. return $out;
  1806. }
  1807. /**
  1808. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1809. *
  1810. * @param string[] $names
  1811. */
  1812. protected function formatNotifySupplierDisplay(array $names): string
  1813. {
  1814. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1815. return trim((string)$n);
  1816. }, $names))));
  1817. if ($names === []) {
  1818. return '';
  1819. }
  1820. sort($names, SORT_STRING);
  1821. return implode("\n", $names);
  1822. }
  1823. /**
  1824. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1825. *
  1826. * @param int[] $scydgyIds
  1827. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1828. */
  1829. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1830. {
  1831. $out = [];
  1832. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1833. if ($scydgyIds === []) {
  1834. return $out;
  1835. }
  1836. try {
  1837. $rows = Db::table('purchase_order_detail')
  1838. ->where('scydgy_id', 'in', $scydgyIds)
  1839. ->field('scydgy_id,company_name,amount')
  1840. ->select();
  1841. } catch (\Throwable $e) {
  1842. $rows = [];
  1843. }
  1844. if (!is_array($rows)) {
  1845. return $out;
  1846. }
  1847. foreach ($rows as $r) {
  1848. if (!is_array($r)) {
  1849. continue;
  1850. }
  1851. $sid = (int)($r['scydgy_id'] ?? 0);
  1852. $cn = trim((string)($r['company_name'] ?? ''));
  1853. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1854. continue;
  1855. }
  1856. if (!isset($out[$sid])) {
  1857. $out[$sid] = ['all' => [], 'quoted' => []];
  1858. }
  1859. $out[$sid]['all'][$cn] = true;
  1860. $am = trim((string)($r['amount'] ?? ''));
  1861. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1862. $out[$sid]['quoted'][$cn] = true;
  1863. }
  1864. }
  1865. return $out;
  1866. }
  1867. /**
  1868. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1869. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1870. */
  1871. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1872. {
  1873. $merged = ['all' => [], 'quoted' => []];
  1874. foreach ($buckets as $b) {
  1875. if (!is_array($b)) {
  1876. continue;
  1877. }
  1878. foreach ($b['all'] ?? [] as $cn => $_) {
  1879. $merged['all'][$cn] = true;
  1880. }
  1881. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1882. $merged['quoted'][$cn] = true;
  1883. }
  1884. }
  1885. return $merged;
  1886. }
  1887. /**
  1888. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1889. */
  1890. protected function formatQuotedSupplierLines(array $bucket): string
  1891. {
  1892. $all = array_keys($bucket['all'] ?? []);
  1893. if ($all === []) {
  1894. return '';
  1895. }
  1896. sort($all, SORT_STRING);
  1897. $lines = [];
  1898. foreach ($all as $cn) {
  1899. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1900. $lines[] = $cn . '(' . $status . ')';
  1901. }
  1902. return implode("\n", $lines);
  1903. }
  1904. /**
  1905. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  1906. */
  1907. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  1908. {
  1909. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  1910. $this->view->engine->layout(false);
  1911. try {
  1912. $bodyHtml = $this->view->fetch($view);
  1913. $this->view->assign('dialogBody', $bodyHtml);
  1914. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  1915. return $this->view->fetch('procuremen/dialog_lite_shell');
  1916. } finally {
  1917. if ($restoreLayout) {
  1918. $this->view->engine->layout($restoreLayout);
  1919. }
  1920. }
  1921. }
  1922. /**
  1923. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1924. */
  1925. protected function resolveBundleSysRq(array $bundle): string
  1926. {
  1927. foreach ($bundle['pos'] ?? [] as $po) {
  1928. if (!is_array($po)) {
  1929. continue;
  1930. }
  1931. $sr = trim((string)($po['sys_rq'] ?? ''));
  1932. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1933. return $sr;
  1934. }
  1935. }
  1936. return '';
  1937. }
  1938. /**
  1939. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1940. */
  1941. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1942. {
  1943. $raw = trim((string)$sysRq);
  1944. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1945. return true;
  1946. }
  1947. $ts = strtotime(str_replace('T', ' ', $raw));
  1948. if ($ts === false || $ts <= 0) {
  1949. return true;
  1950. }
  1951. return time() >= $ts;
  1952. }
  1953. /**
  1954. * 开标前校验:必须已过报价截止时间
  1955. *
  1956. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1957. */
  1958. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1959. {
  1960. $sysRq = $this->resolveBundleSysRq($bundle);
  1961. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1962. $this->error('未到招标截止日期');
  1963. }
  1964. }
  1965. /**
  1966. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  1967. *
  1968. * @param array<string, mixed> $d
  1969. * @param string $deliveryYmd
  1970. */
  1971. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  1972. {
  1973. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  1974. return max(0, (int)$d['lead_days']);
  1975. }
  1976. if ($deliveryYmd === '') {
  1977. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  1978. }
  1979. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  1980. return null;
  1981. }
  1982. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  1983. $t2 = strtotime($m[1] . ' 00:00:00');
  1984. if ($t1 === false || $t2 === false) {
  1985. return null;
  1986. }
  1987. return max(0, (int)round(($t2 - $t1) / 86400));
  1988. }
  1989. /**
  1990. * @param int|null $days
  1991. */
  1992. protected function formatProcuremenLeadDaysText($days): string
  1993. {
  1994. if ($days === null || $days === '') {
  1995. return '未填写';
  1996. }
  1997. if (!is_numeric($days)) {
  1998. return '未填写';
  1999. }
  2000. return ((int)$days) . '天';
  2001. }
  2002. /**
  2003. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2004. *
  2005. * @param array<string, mixed> $line
  2006. */
  2007. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2008. {
  2009. $amountFilled = !empty($line['amount_filled']);
  2010. $deliveryFilled = !empty($line['delivery_filled']);
  2011. $leadFilled = !empty($line['lead_days_filled']);
  2012. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2013. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2014. $line['amount_show'] = '';
  2015. if (array_key_exists('amount_text', $line)) {
  2016. $line['amount_text'] = $line['unit_price_text'];
  2017. }
  2018. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2019. $line['delivery_show'] = $deliveryText;
  2020. if (array_key_exists('delivery_text', $line)) {
  2021. $line['delivery_text'] = $deliveryText;
  2022. }
  2023. $line['delivery_ymd'] = '';
  2024. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2025. $line['lead_days_show'] = $leadText;
  2026. $line['lead_days_text'] = $leadText;
  2027. $line['lead_days'] = '';
  2028. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2029. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2030. $line['subtotal_num'] = null;
  2031. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2032. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2033. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2034. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2035. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2036. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2037. $line['amount_filled'] = false;
  2038. $line['delivery_filled'] = false;
  2039. $line['lead_days_filled'] = false;
  2040. $line['is_quoted'] = false;
  2041. if (array_key_exists('quote_label', $line)) {
  2042. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2043. }
  2044. }
  2045. protected function ensurePurchaseOrderBidOpenTable(): void
  2046. {
  2047. try {
  2048. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2049. } catch (\Throwable $e) {
  2050. Db::execute(
  2051. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2052. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2053. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2054. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2055. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2056. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2057. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2058. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2059. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2060. `createtime` datetime DEFAULT NULL,
  2061. PRIMARY KEY (`id`),
  2062. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2063. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2064. );
  2065. }
  2066. }
  2067. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2068. {
  2069. $ccydh = trim($ccydh);
  2070. if ($ccydh === '') {
  2071. return false;
  2072. }
  2073. $this->ensurePurchaseOrderBidOpenTable();
  2074. try {
  2075. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2076. return is_array($row);
  2077. } catch (\Throwable $e) {
  2078. return false;
  2079. }
  2080. }
  2081. /**
  2082. * 批量查询订单是否已开标验证
  2083. *
  2084. * @param array<int, string> $ccydhs
  2085. * @return array<string, bool> ccydh => true
  2086. */
  2087. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2088. {
  2089. $set = [];
  2090. $list = [];
  2091. foreach ($ccydhs as $c) {
  2092. $c = trim((string)$c);
  2093. if ($c !== '') {
  2094. $list[$c] = true;
  2095. }
  2096. }
  2097. if ($list === []) {
  2098. return $set;
  2099. }
  2100. $this->ensurePurchaseOrderBidOpenTable();
  2101. try {
  2102. $rows = Db::table('purchase_order_bid_open')
  2103. ->where('ccydh', 'in', array_keys($list))
  2104. ->field('ccydh')
  2105. ->select();
  2106. foreach ($rows as $row) {
  2107. if (!is_array($row)) {
  2108. continue;
  2109. }
  2110. $c = trim((string)($row['ccydh'] ?? ''));
  2111. if ($c !== '') {
  2112. $set[$c] = true;
  2113. }
  2114. }
  2115. } catch (\Throwable $e) {
  2116. return [];
  2117. }
  2118. return $set;
  2119. }
  2120. /**
  2121. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2122. *
  2123. * @param array<string, mixed> $group
  2124. */
  2125. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2126. {
  2127. if ($quoteVisible) {
  2128. $group['remark_quote_pending'] = 0;
  2129. return;
  2130. }
  2131. $group['remark'] = '';
  2132. $group['remark_quote_pending'] = 0;
  2133. }
  2134. /**
  2135. * @param array{ccydh?:string} $bundle
  2136. */
  2137. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2138. {
  2139. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2140. }
  2141. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2142. {
  2143. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  2144. }
  2145. protected function loadBidOpenAdminUser(int $adminId): ?array
  2146. {
  2147. if ($adminId <= 0) {
  2148. return null;
  2149. }
  2150. try {
  2151. $row = Db::name('admin')->where('id', $adminId)->find();
  2152. } catch (\Throwable $e) {
  2153. return null;
  2154. }
  2155. if (!is_array($row)) {
  2156. return null;
  2157. }
  2158. $status = strtolower(trim((string)($row['status'] ?? '')));
  2159. if ($status !== '' && $status !== 'normal') {
  2160. return null;
  2161. }
  2162. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2163. return null;
  2164. }
  2165. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2166. if (!preg_match('/^1\d{10}$/', $phone)) {
  2167. return null;
  2168. }
  2169. $name = trim((string)($row['nickname'] ?? ''));
  2170. if ($name === '') {
  2171. $name = trim((string)($row['username'] ?? ''));
  2172. }
  2173. return [
  2174. 'id' => (int)$row['id'],
  2175. 'username' => trim((string)($row['username'] ?? '')),
  2176. 'nickname' => $name,
  2177. 'mobile' => $phone,
  2178. ];
  2179. }
  2180. /**
  2181. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2182. */
  2183. protected function bidOpenVerifierAuthGroupRootId(): int
  2184. {
  2185. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2186. return $id > 0 ? $id : 10;
  2187. }
  2188. /**
  2189. * @return int[]
  2190. */
  2191. protected function loadBidOpenVerifierAuthGroupIds(): array
  2192. {
  2193. static $memo = [];
  2194. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2195. if (isset($memo[$rootId])) {
  2196. return $memo[$rootId];
  2197. }
  2198. try {
  2199. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2200. } catch (\Throwable $e) {
  2201. $memo[$rootId] = [$rootId];
  2202. return $memo[$rootId];
  2203. }
  2204. if (!is_array($groups) || $groups === []) {
  2205. $memo[$rootId] = [$rootId];
  2206. return $memo[$rootId];
  2207. }
  2208. $groupList = [];
  2209. foreach ($groups as $g) {
  2210. if (is_array($g)) {
  2211. $groupList[] = $g;
  2212. }
  2213. }
  2214. if ($groupList === []) {
  2215. $memo[$rootId] = [$rootId];
  2216. return $memo[$rootId];
  2217. }
  2218. $tree = \fast\Tree::instance();
  2219. $tree->init($groupList);
  2220. $ids = $tree->getChildrenIds($rootId, true);
  2221. if (!is_array($ids) || $ids === []) {
  2222. $memo[$rootId] = [$rootId];
  2223. return $memo[$rootId];
  2224. }
  2225. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2226. return $memo[$rootId];
  2227. }
  2228. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2229. {
  2230. if ($adminId <= 0) {
  2231. return false;
  2232. }
  2233. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2234. if ($groupIds === []) {
  2235. return false;
  2236. }
  2237. try {
  2238. return (bool)Db::name('auth_group_access')
  2239. ->where('uid', $adminId)
  2240. ->where('group_id', 'in', $groupIds)
  2241. ->count();
  2242. } catch (\Throwable $e) {
  2243. return false;
  2244. }
  2245. }
  2246. /**
  2247. * @return array<int, array<string, mixed>>
  2248. */
  2249. protected function listBidOpenVerifierCandidates(): array
  2250. {
  2251. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2252. if ($groupIds === []) {
  2253. return [];
  2254. }
  2255. try {
  2256. $adminIds = Db::name('auth_group_access')
  2257. ->where('group_id', 'in', $groupIds)
  2258. ->column('uid');
  2259. } catch (\Throwable $e) {
  2260. $adminIds = [];
  2261. }
  2262. $adminIds = is_array($adminIds)
  2263. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  2264. : [];
  2265. if ($adminIds === []) {
  2266. return [];
  2267. }
  2268. try {
  2269. $rows = Db::name('admin')
  2270. ->where('status', 'normal')
  2271. ->where('id', 'in', $adminIds)
  2272. ->where('mobile', '<>', '')
  2273. ->order('id', 'asc')
  2274. ->select();
  2275. } catch (\Throwable $e) {
  2276. return [];
  2277. }
  2278. if (!is_array($rows)) {
  2279. return [];
  2280. }
  2281. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  2282. $out = [];
  2283. foreach ($rows as $row) {
  2284. if (!is_array($row)) {
  2285. continue;
  2286. }
  2287. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  2288. if ($one === null) {
  2289. continue;
  2290. }
  2291. $out[] = [
  2292. 'id' => $one['id'],
  2293. 'username' => $one['username'],
  2294. 'nickname' => $one['nickname'],
  2295. 'group_name' => $groupNameMap[$one['id']] ?? '',
  2296. 'mobile' => mask_phone($one['mobile']),
  2297. ];
  2298. }
  2299. return $out;
  2300. }
  2301. /**
  2302. * @param int[] $adminIds
  2303. * @return array<int, string>
  2304. */
  2305. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2306. {
  2307. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2308. if ($adminIds === []) {
  2309. return [];
  2310. }
  2311. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2312. try {
  2313. $rows = Db::name('auth_group_access')
  2314. ->alias('aga')
  2315. ->join('auth_group ag', 'aga.group_id = ag.id')
  2316. ->where('aga.uid', 'in', $adminIds)
  2317. ->where('aga.group_id', 'in', $groupIds)
  2318. ->field('aga.uid,ag.name')
  2319. ->order('aga.uid', 'asc')
  2320. ->order('aga.group_id', 'asc')
  2321. ->select();
  2322. } catch (\Throwable $e) {
  2323. return [];
  2324. }
  2325. if (!is_array($rows)) {
  2326. return [];
  2327. }
  2328. $out = [];
  2329. foreach ($rows as $row) {
  2330. if (!is_array($row)) {
  2331. continue;
  2332. }
  2333. $uid = (int)($row['uid'] ?? 0);
  2334. $name = trim((string)($row['name'] ?? ''));
  2335. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2336. continue;
  2337. }
  2338. $out[$uid] = $name;
  2339. }
  2340. return $out;
  2341. }
  2342. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2343. {
  2344. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2345. }
  2346. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2347. {
  2348. return 'procuremen_bidopen_wait_' . $adminId;
  2349. }
  2350. protected function renderBidOpenVerifySms(string $code): string
  2351. {
  2352. $tpl = '';
  2353. try {
  2354. $row = $this->loadNotifyTemplateRow('bid_open');
  2355. if (is_array($row)) {
  2356. $tpl = trim((string)($row['content'] ?? ''));
  2357. }
  2358. } catch (\Throwable $e) {
  2359. $tpl = '';
  2360. }
  2361. if ($tpl === '') {
  2362. $tpl = '【可集达】您的短信验证码是{code}';
  2363. }
  2364. return str_replace('{code}', $code, $tpl);
  2365. }
  2366. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2367. {
  2368. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2369. }
  2370. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2371. {
  2372. $code = trim($code);
  2373. if (!preg_match('/^\d{6}$/', $code)) {
  2374. return false;
  2375. }
  2376. $mock = Config::get('mproc.mock_sms_code');
  2377. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2378. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2379. return true;
  2380. }
  2381. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2382. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2383. return false;
  2384. }
  2385. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2386. return true;
  2387. }
  2388. /**
  2389. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2390. */
  2391. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2392. {
  2393. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2394. if ($ccydh === '') {
  2395. throw new \InvalidArgumentException('订单号无效');
  2396. }
  2397. $this->ensurePurchaseOrderBidOpenTable();
  2398. list($operatorId, $operatorName) = $this->GetUseName();
  2399. $now = date('Y-m-d H:i:s');
  2400. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2401. $payload = [
  2402. 'ccydh' => $ccydh,
  2403. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2404. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2405. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2406. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2407. 'operator_id' => (int)$operatorId,
  2408. 'operator_name' => trim((string)$operatorName),
  2409. 'createtime' => $now,
  2410. ];
  2411. if (is_array($exists)) {
  2412. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2413. } else {
  2414. Db::table('purchase_order_bid_open')->insert($payload);
  2415. }
  2416. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2417. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2418. $orderPart = '(订单' . $ccydh . ')';
  2419. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2420. $seenSid = [];
  2421. foreach ($bundle['pos'] ?? [] as $poRow) {
  2422. if (!is_array($poRow)) {
  2423. continue;
  2424. }
  2425. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2426. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2427. continue;
  2428. }
  2429. $seenSid[$sid] = true;
  2430. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2431. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2432. }
  2433. if ($seenSid === []) {
  2434. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2435. if ($this->isValidScydgyRowId($anchor)) {
  2436. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2437. }
  2438. }
  2439. // 开标通过后计算并写入供应商服务评分
  2440. try {
  2441. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  2442. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  2443. } catch (\Throwable $e) {
  2444. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  2445. }
  2446. }
  2447. /**
  2448. * 报价行展示字段默认值(模板安全访问)
  2449. *
  2450. * @param array<string, mixed> $line
  2451. * @return array<string, mixed>
  2452. */
  2453. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2454. {
  2455. if (!array_key_exists('amount_quote_pending', $line)) {
  2456. $line['amount_quote_pending'] = 0;
  2457. }
  2458. if (!array_key_exists('delivery_quote_pending', $line)) {
  2459. $line['delivery_quote_pending'] = 0;
  2460. }
  2461. if (!array_key_exists('quote_before_deadline', $line)) {
  2462. $line['quote_before_deadline'] = 0;
  2463. }
  2464. if (!array_key_exists('amount_filled', $line)) {
  2465. $line['amount_filled'] = 0;
  2466. }
  2467. if (!array_key_exists('delivery_filled', $line)) {
  2468. $line['delivery_filled'] = 0;
  2469. }
  2470. if (!array_key_exists('lead_days_filled', $line)) {
  2471. $line['lead_days_filled'] = 0;
  2472. }
  2473. if (!array_key_exists('lead_days_quote_pending', $line)) {
  2474. $line['lead_days_quote_pending'] = 0;
  2475. }
  2476. if (!array_key_exists('lead_days_show', $line)) {
  2477. $line['lead_days_show'] = '未填写';
  2478. }
  2479. if (!array_key_exists('lead_days_text', $line)) {
  2480. $line['lead_days_text'] = $line['lead_days_show'];
  2481. }
  2482. return $line;
  2483. }
  2484. /**
  2485. * 审核弹窗:按供应商汇总报价明细
  2486. *
  2487. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2488. * @return array<int, array<string, mixed>>
  2489. */
  2490. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2491. {
  2492. $sids = [];
  2493. foreach ($bundle['pos'] ?? [] as $po) {
  2494. if (!is_array($po)) {
  2495. continue;
  2496. }
  2497. $sid = (int)($po['scydgy_id'] ?? 0);
  2498. if ($this->isValidScydgyRowId($sid)) {
  2499. $sids[$sid] = true;
  2500. }
  2501. }
  2502. if ($sids === []) {
  2503. return [];
  2504. }
  2505. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2506. $gymcMap = [];
  2507. $qtyBySid = [];
  2508. $orderedSids = [];
  2509. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2510. if (!is_array($mr)) {
  2511. continue;
  2512. }
  2513. $gid = $this->extractScydgyRowId($mr);
  2514. if ($this->isValidScydgyRowId($gid)) {
  2515. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2516. $orderedSids[] = $gid;
  2517. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2518. if ($qty === '') {
  2519. $qty = trim((string)($mr['NGZL'] ?? ''));
  2520. }
  2521. $qtyBySid[$gid] = $qty;
  2522. }
  2523. }
  2524. foreach ($bundle['pos'] ?? [] as $po) {
  2525. if (!is_array($po)) {
  2526. continue;
  2527. }
  2528. $gid = (int)($po['scydgy_id'] ?? 0);
  2529. if ($this->isValidScydgyRowId($gid)) {
  2530. $nm = trim((string)($po['CGYMC'] ?? ''));
  2531. if ($nm !== '') {
  2532. $gymcMap[$gid] = $nm;
  2533. }
  2534. if (!in_array($gid, $orderedSids, true)) {
  2535. $orderedSids[] = $gid;
  2536. }
  2537. }
  2538. }
  2539. try {
  2540. $detailsQuery = Db::table('purchase_order_detail')
  2541. ->where('scydgy_id', 'in', array_keys($sids));
  2542. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2543. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2544. } catch (\Throwable $e) {
  2545. try {
  2546. $detailsQuery = Db::table('purchase_order_detail')
  2547. ->where('scydgy_id', 'in', array_keys($sids));
  2548. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2549. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2550. } catch (\Throwable $e2) {
  2551. $details = [];
  2552. }
  2553. }
  2554. if (!is_array($details)) {
  2555. $details = [];
  2556. }
  2557. $byCompany = [];
  2558. foreach ($details as $d) {
  2559. if (!is_array($d)) {
  2560. continue;
  2561. }
  2562. $cn = trim((string)($d['company_name'] ?? ''));
  2563. if ($cn === '') {
  2564. continue;
  2565. }
  2566. if (!isset($byCompany[$cn])) {
  2567. $ph = trim((string)($d['phone'] ?? ''));
  2568. $username = trim((string)($d['username'] ?? ''));
  2569. if ($username === '') {
  2570. $username = $this->resolveCustomerContactName($ph, $cn);
  2571. }
  2572. $byCompany[$cn] = [
  2573. 'name' => $cn,
  2574. 'email' => trim((string)($d['email'] ?? '')),
  2575. 'phone' => $ph,
  2576. 'username' => $username,
  2577. 'remark' => '',
  2578. 'has_quote' => false,
  2579. 'lines_map' => [],
  2580. ];
  2581. }
  2582. if ($byCompany[$cn]['remark'] === '') {
  2583. $rm = '';
  2584. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2585. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2586. $rm = trim((string)$d[$rk]);
  2587. break;
  2588. }
  2589. }
  2590. if ($rm !== '') {
  2591. $byCompany[$cn]['remark'] = $rm;
  2592. }
  2593. }
  2594. $sid = (int)($d['scydgy_id'] ?? 0);
  2595. $am = trim((string)($d['amount'] ?? ''));
  2596. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2597. if ($gymc === '') {
  2598. $gymc = '工序';
  2599. }
  2600. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2601. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2602. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2603. $deliveryShow = $deliveryRaw;
  2604. }
  2605. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2606. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2607. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2608. $subtotal = null;
  2609. if ($amountNum !== null) {
  2610. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2611. }
  2612. $unitPriceText = $amountFilled
  2613. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2614. : '未填写';
  2615. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2616. $leadFilled = ($leadDays !== null);
  2617. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2618. $lineRow = [
  2619. 'cgymc' => $gymc,
  2620. 'amount' => $am,
  2621. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2622. 'amount_filled' => $amountFilled,
  2623. 'unit_price_text' => $unitPriceText,
  2624. 'delivery' => $deliveryRaw,
  2625. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2626. 'delivery_filled' => $deliveryFilled,
  2627. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2628. 'lead_days' => $leadFilled ? $leadDays : '',
  2629. 'lead_days_filled'=> $leadFilled,
  2630. 'lead_days_show' => $leadText,
  2631. 'lead_days_text' => $leadText,
  2632. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2633. 'subtotal_num' => $subtotal,
  2634. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2635. 'is_quoted' => $amountFilled,
  2636. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2637. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2638. ];
  2639. if (!$quoteVisible) {
  2640. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2641. }
  2642. // 按工序 id 暂存,下面再按上方工序表顺序输出
  2643. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2644. }
  2645. foreach ($byCompany as $cn => $g) {
  2646. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  2647. $lines = [];
  2648. $usedSids = [];
  2649. foreach ($orderedSids as $sid) {
  2650. if (!isset($linesMap[$sid])) {
  2651. continue;
  2652. }
  2653. $lines[] = $linesMap[$sid];
  2654. $usedSids[$sid] = true;
  2655. }
  2656. foreach ($linesMap as $sid => $ln) {
  2657. if (isset($usedSids[$sid])) {
  2658. continue;
  2659. }
  2660. $lines[] = $ln;
  2661. }
  2662. $total = count($lines);
  2663. $quoted = 0;
  2664. $groupTotal = 0.0;
  2665. $groupHasTotal = false;
  2666. if ($quoteVisible) {
  2667. foreach ($lines as $ln) {
  2668. $am = trim((string)($ln['amount'] ?? ''));
  2669. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2670. $quoted++;
  2671. }
  2672. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2673. $groupTotal += (float)$ln['subtotal_num'];
  2674. $groupHasTotal = true;
  2675. }
  2676. }
  2677. }
  2678. unset($byCompany[$cn]['lines_map']);
  2679. $byCompany[$cn]['lines'] = $lines;
  2680. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2681. $byCompany[$cn]['line_count'] = $total;
  2682. $byCompany[$cn]['has_total'] = $total > 0;
  2683. $byCompany[$cn]['has_remark'] = $total > 0;
  2684. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  2685. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2686. // 工序行 + 备注行 + 总计行
  2687. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  2688. }
  2689. $groups = array_values($byCompany);
  2690. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2691. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  2692. }
  2693. /**
  2694. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2695. *
  2696. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2697. * @return array<int, array<string, mixed>>
  2698. */
  2699. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2700. {
  2701. $sids = [];
  2702. $poIdMap = [];
  2703. foreach ($bundle['pos'] ?? [] as $po) {
  2704. if (!is_array($po)) {
  2705. continue;
  2706. }
  2707. $sid = (int)($po['scydgy_id'] ?? 0);
  2708. if ($this->isValidScydgyRowId($sid)) {
  2709. $sids[$sid] = true;
  2710. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2711. }
  2712. }
  2713. if ($sids === []) {
  2714. return [];
  2715. }
  2716. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2717. $gymcMap = [];
  2718. $qtyBySid = [];
  2719. $orderedSids = [];
  2720. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2721. if (!is_array($mr)) {
  2722. continue;
  2723. }
  2724. $gid = $this->extractScydgyRowId($mr);
  2725. if ($this->isValidScydgyRowId($gid)) {
  2726. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2727. $orderedSids[] = $gid;
  2728. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2729. if ($qty === '') {
  2730. $qty = trim((string)($mr['NGZL'] ?? ''));
  2731. }
  2732. $qtyBySid[$gid] = $qty;
  2733. }
  2734. }
  2735. foreach ($bundle['pos'] ?? [] as $po) {
  2736. if (!is_array($po)) {
  2737. continue;
  2738. }
  2739. $gid = (int)($po['scydgy_id'] ?? 0);
  2740. if ($this->isValidScydgyRowId($gid)) {
  2741. $nm = trim((string)($po['CGYMC'] ?? ''));
  2742. if ($nm !== '') {
  2743. $gymcMap[$gid] = $nm;
  2744. }
  2745. }
  2746. }
  2747. try {
  2748. $details = Db::table('purchase_order_detail')
  2749. ->where('scydgy_id', 'in', array_keys($sids))
  2750. ->order('company_name', 'asc')
  2751. ->order('id', 'asc')
  2752. ->select();
  2753. } catch (\Throwable $e) {
  2754. try {
  2755. $details = Db::table('purchase_order_detail')
  2756. ->where('scydgy_id', 'in', array_keys($sids))
  2757. ->order('company_name', 'asc')
  2758. ->order('ID', 'asc')
  2759. ->select();
  2760. } catch (\Throwable $e2) {
  2761. $details = [];
  2762. }
  2763. }
  2764. if (!is_array($details)) {
  2765. $details = [];
  2766. }
  2767. $byCompany = [];
  2768. foreach ($details as $d) {
  2769. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2770. continue;
  2771. }
  2772. $cn = trim((string)($d['company_name'] ?? ''));
  2773. if ($cn === '') {
  2774. continue;
  2775. }
  2776. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2777. $sid = (int)($d['scydgy_id'] ?? 0);
  2778. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2779. continue;
  2780. }
  2781. if (!isset($byCompany[$cn])) {
  2782. $ph = trim((string)($d['phone'] ?? ''));
  2783. $username = trim((string)($d['username'] ?? ''));
  2784. if ($username === '') {
  2785. $username = $this->resolveCustomerContactName($ph, $cn);
  2786. }
  2787. $byCompany[$cn] = [
  2788. 'name' => $cn,
  2789. 'email' => trim((string)($d['email'] ?? '')),
  2790. 'phone' => $ph,
  2791. 'username' => $username,
  2792. 'remark' => '',
  2793. 'pick_lines' => [],
  2794. 'detail_picks' => [],
  2795. ];
  2796. }
  2797. if ($byCompany[$cn]['remark'] === '') {
  2798. $rm = '';
  2799. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2800. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2801. $rm = trim((string)$d[$rk]);
  2802. break;
  2803. }
  2804. }
  2805. if ($rm !== '') {
  2806. $byCompany[$cn]['remark'] = $rm;
  2807. }
  2808. }
  2809. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2810. if ($gymc === '') {
  2811. $gymc = '工序';
  2812. }
  2813. $am = trim((string)($d['amount'] ?? ''));
  2814. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2815. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2816. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2817. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2818. $deliveryShow = $deliveryRaw;
  2819. }
  2820. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2821. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2822. $subtotal = null;
  2823. if ($amountNum !== null) {
  2824. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2825. }
  2826. $unitPriceText = $amountFilled
  2827. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2828. : '未填写';
  2829. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  2830. $leadFilled = ($leadDays !== null);
  2831. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  2832. $pickLine = [
  2833. 'cgymc' => $gymc,
  2834. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  2835. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2836. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2837. 'amount_filled' => $amountFilled,
  2838. 'delivery_filled' => $deliveryFilled,
  2839. 'unit_price_text' => $unitPriceText,
  2840. 'lead_days' => $leadFilled ? $leadDays : '',
  2841. 'lead_days_filled'=> $leadFilled,
  2842. 'lead_days_show' => $leadText,
  2843. 'lead_days_text' => $leadText,
  2844. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2845. 'subtotal_num' => $subtotal,
  2846. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  2847. 'is_quoted' => $amountFilled,
  2848. ];
  2849. if (!$quoteVisible) {
  2850. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2851. }
  2852. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2853. $byCompany[$cn]['detail_picks'][$sid] = [
  2854. 'scydgy_id' => $sid,
  2855. 'detail_id' => $detailId,
  2856. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2857. 'cgymc' => $gymc,
  2858. ];
  2859. }
  2860. $out = [];
  2861. foreach ($byCompany as $g) {
  2862. $pickLinesMap = $g['pick_lines'] ?? [];
  2863. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2864. continue;
  2865. }
  2866. $pickLines = [];
  2867. $usedLineSids = [];
  2868. foreach ($orderedSids as $sid) {
  2869. if (!isset($pickLinesMap[$sid])) {
  2870. continue;
  2871. }
  2872. $pickLines[] = $pickLinesMap[$sid];
  2873. $usedLineSids[$sid] = true;
  2874. }
  2875. foreach ($pickLinesMap as $sid => $ln) {
  2876. if (isset($usedLineSids[$sid])) {
  2877. continue;
  2878. }
  2879. $pickLines[] = $ln;
  2880. }
  2881. $groupTotal = 0.0;
  2882. $groupHasTotal = false;
  2883. if ($quoteVisible) {
  2884. foreach ($pickLines as $ln) {
  2885. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2886. $groupTotal += (float)$ln['subtotal_num'];
  2887. $groupHasTotal = true;
  2888. }
  2889. }
  2890. }
  2891. $lineCount = count($pickLines);
  2892. $g['pick_lines'] = $pickLines;
  2893. $g['line_count'] = $lineCount;
  2894. $g['has_total'] = $lineCount > 0;
  2895. $g['has_remark'] = $lineCount > 0;
  2896. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  2897. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2898. // 工序行 + 备注行 + 总计行
  2899. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  2900. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  2901. $detailPicks = [];
  2902. $usedPickSids = [];
  2903. foreach ($orderedSids as $sid) {
  2904. if (!isset($detailPicksMap[$sid])) {
  2905. continue;
  2906. }
  2907. $detailPicks[] = $detailPicksMap[$sid];
  2908. $usedPickSids[$sid] = true;
  2909. }
  2910. foreach ($detailPicksMap as $sid => $dp) {
  2911. if (isset($usedPickSids[$sid])) {
  2912. continue;
  2913. }
  2914. $detailPicks[] = $dp;
  2915. }
  2916. $g['detail_picks'] = $detailPicks;
  2917. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2918. unset($g['detail_picks']);
  2919. $out[] = $g;
  2920. }
  2921. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2922. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  2923. }
  2924. /**
  2925. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2926. * @return array<int, int[]> scydgy_id => detail_id[]
  2927. */
  2928. protected function mapDetailIdsByScydgyId(array $details): array
  2929. {
  2930. $out = [];
  2931. foreach ($details as $d) {
  2932. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2933. continue;
  2934. }
  2935. $sid = (int)($d['scydgy_id'] ?? 0);
  2936. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2937. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2938. continue;
  2939. }
  2940. if (!isset($out[$sid])) {
  2941. $out[$sid] = [];
  2942. }
  2943. $out[$sid][] = $pk;
  2944. }
  2945. foreach ($out as $sid => $ids) {
  2946. $out[$sid] = array_values(array_unique($ids));
  2947. }
  2948. return $out;
  2949. }
  2950. /**
  2951. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2952. *
  2953. * @param array<string, mixed> $dbRow
  2954. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2955. */
  2956. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2957. {
  2958. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2959. $r = [
  2960. 'ID' => $sid,
  2961. 'scydgy_id' => $sid,
  2962. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2963. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2964. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2965. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2966. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2967. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2968. 'CDW' => $dbRow['CDW'] ?? '',
  2969. 'czlyq' => $dbRow['czlyq'] ?? '',
  2970. 'NGZL' => $dbRow['NGZL'] ?? '',
  2971. 'CDF' => $dbRow['CDF'] ?? '',
  2972. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2973. 'MBZ' => $dbRow['MBZ'] ?? '',
  2974. 'bwjg' => $dbRow['bwjg'] ?? '',
  2975. 'iStatus' => $dbRow['iStatus'] ?? '',
  2976. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2977. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2978. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2979. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2980. 'dStamp' => $dbRow['dStamp'] ?? '',
  2981. 'pick_time' => $dbRow['pick_time'] ?? '',
  2982. ];
  2983. if ($sid > 0 && isset($dStampMap[$sid])) {
  2984. $t = trim((string)$dStampMap[$sid]);
  2985. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2986. $r['dStamp'] = $dStampMap[$sid];
  2987. }
  2988. }
  2989. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2990. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2991. $ct = $dbRow['createtime'];
  2992. if (is_numeric($ct) && (int)$ct > 946684800) {
  2993. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2994. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2995. $r['dStamp'] = trim($ct);
  2996. }
  2997. }
  2998. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2999. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3000. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3001. $fallback = trim((string)($r['dStamp'] ?? ''));
  3002. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3003. $r['dputrecord'] = $fallback;
  3004. }
  3005. }
  3006. if (array_key_exists('id', $dbRow)) {
  3007. $r['purchase_order_id'] = (int)$dbRow['id'];
  3008. }
  3009. if ($sid < 0) {
  3010. $r['_is_manual'] = 1;
  3011. }
  3012. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3013. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3014. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3015. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3016. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3017. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3018. $r['pick_time'] = $pickFallback;
  3019. break;
  3020. }
  3021. }
  3022. }
  3023. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3024. if ($pickNm !== '') {
  3025. $r['pick_company_name'] = $pickNm;
  3026. $r['picked_supplier_name'] = $pickNm;
  3027. }
  3028. return $r;
  3029. }
  3030. /**
  3031. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3032. *
  3033. * @return array<int, array<string, mixed>>
  3034. */
  3035. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3036. {
  3037. $pool = [];
  3038. if (!is_array($dbRows) || $dbRows === []) {
  3039. return $pool;
  3040. }
  3041. $dStampMap = [];
  3042. $sidList = [];
  3043. foreach ($dbRows as $tmpRow) {
  3044. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3045. $sid = (int)$tmpRow['scydgy_id'];
  3046. if ($sid > 0) {
  3047. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3048. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3049. $sidList[$sid] = true;
  3050. }
  3051. }
  3052. }
  3053. }
  3054. if ($sidList !== []) {
  3055. try {
  3056. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3057. } catch (\Throwable $e) {
  3058. $dStampMap = [];
  3059. }
  3060. }
  3061. foreach ($dbRows as $dbRow) {
  3062. if (!is_array($dbRow)) {
  3063. continue;
  3064. }
  3065. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3066. }
  3067. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3068. $needCcydh = [];
  3069. foreach ($pool as $row) {
  3070. if (!is_array($row)) {
  3071. continue;
  3072. }
  3073. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3074. continue;
  3075. }
  3076. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3077. if ($ccydh !== '') {
  3078. $needCcydh[$ccydh] = true;
  3079. }
  3080. }
  3081. if ($needCcydh !== []) {
  3082. $czMap = [];
  3083. try {
  3084. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3085. } catch (\Throwable $e) {
  3086. $czMap = [];
  3087. }
  3088. if (is_array($czMap) && $czMap !== []) {
  3089. foreach ($pool as &$row) {
  3090. if (!is_array($row)) {
  3091. continue;
  3092. }
  3093. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3094. continue;
  3095. }
  3096. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3097. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3098. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3099. }
  3100. }
  3101. unset($row);
  3102. }
  3103. }
  3104. return $pool;
  3105. }
  3106. /**
  3107. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3108. *
  3109. * @param int[] $scydgyIds
  3110. * @return array<int, array<string, mixed>>
  3111. */
  3112. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3113. {
  3114. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3115. if ($scydgyIds === []) {
  3116. return [];
  3117. }
  3118. try {
  3119. $list = Db::table('purchase_order_detail')
  3120. ->where('scydgy_id', 'in', $scydgyIds)
  3121. ->field('scydgy_id,company_name,amount,delivery')
  3122. ->select();
  3123. } catch (\Throwable $e) {
  3124. $list = [];
  3125. }
  3126. return is_array($list) ? $list : [];
  3127. }
  3128. /**
  3129. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3130. *
  3131. * @param int[] $scydgyIds
  3132. * @param array<int, array<string, mixed>> $allRows
  3133. * @return array{cnt:int, amt:int, deliv:int}
  3134. */
  3135. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3136. {
  3137. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3138. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3139. if ($scydgyIds === [] || $allRows === []) {
  3140. return $out;
  3141. }
  3142. $idSet = array_flip($scydgyIds);
  3143. $all = [];
  3144. $withAmt = [];
  3145. $withDeliv = [];
  3146. foreach ($allRows as $r) {
  3147. if (!is_array($r)) {
  3148. continue;
  3149. }
  3150. $sid = (int)($r['scydgy_id'] ?? 0);
  3151. if (!isset($idSet[$sid])) {
  3152. continue;
  3153. }
  3154. $cn = trim((string)($r['company_name'] ?? ''));
  3155. if ($cn === '') {
  3156. continue;
  3157. }
  3158. $all[$cn] = true;
  3159. $am = $r['amount'] ?? null;
  3160. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3161. $withAmt[$cn] = true;
  3162. }
  3163. $dv = $r['delivery'] ?? null;
  3164. if ($dv !== null && trim((string)$dv) !== '') {
  3165. $withDeliv[$cn] = true;
  3166. }
  3167. }
  3168. return [
  3169. 'cnt' => count($all),
  3170. 'amt' => count($withAmt),
  3171. 'deliv' => count($withDeliv),
  3172. ];
  3173. }
  3174. /**
  3175. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  3176. *
  3177. * @param int[] $scydgyIds
  3178. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  3179. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  3180. */
  3181. protected function OrderDetailSummary(array $scydgyIds)
  3182. {
  3183. $out = [];
  3184. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3185. if ($scydgyIds === []) {
  3186. return $out;
  3187. }
  3188. $list = [];
  3189. try {
  3190. $list = Db::table('purchase_order_detail')
  3191. ->where('scydgy_id', 'in', $scydgyIds)
  3192. ->field('id,scydgy_id,amount,delivery')
  3193. ->select();
  3194. } catch (\Throwable $e) {
  3195. $list = [];
  3196. }
  3197. if (!is_array($list)) {
  3198. return $out;
  3199. }
  3200. foreach ($list as $r) {
  3201. if (!is_array($r)) {
  3202. continue;
  3203. }
  3204. $ids = (int)($r['scydgy_id'] ?? 0);
  3205. if (!$this->isValidScydgyRowId($ids)) {
  3206. continue;
  3207. }
  3208. if (!isset($out[$ids])) {
  3209. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3210. }
  3211. $out[$ids]['cnt']++;
  3212. $am = $r['amount'] ?? null;
  3213. if ($am !== null && $am !== '') {
  3214. if (!(is_string($am) && trim($am) === '')) {
  3215. $out[$ids]['amt']++;
  3216. }
  3217. }
  3218. $dv = $r['delivery'] ?? null;
  3219. if ($dv !== null && trim((string)$dv) !== '') {
  3220. $out[$ids]['deliv']++;
  3221. }
  3222. }
  3223. return $out;
  3224. }
  3225. /**
  3226. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  3227. *
  3228. * @return array
  3229. */
  3230. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  3231. {
  3232. $strContains = function ($haystack, $needle) {
  3233. if ($needle === '') {
  3234. return false;
  3235. }
  3236. $haystack = (string)$haystack;
  3237. if (function_exists('mb_stripos')) {
  3238. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  3239. }
  3240. return stripos($haystack, $needle) !== false;
  3241. };
  3242. $stripAlias = function ($f) {
  3243. return preg_replace('/^[ab]\./i', '', (string)$f);
  3244. };
  3245. $searchColNames = [];
  3246. foreach (explode(',', $this->searchFields) as $colRaw) {
  3247. $c = $stripAlias(trim($colRaw));
  3248. if ($c !== '') {
  3249. $searchColNames[] = $c;
  3250. }
  3251. }
  3252. // 等值条件先行(表头下拉),减少后续日期解析量
  3253. $eqFilters = [];
  3254. $otherFilters = [];
  3255. foreach ($filterArr as $fk => $fv) {
  3256. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  3257. continue;
  3258. }
  3259. if (is_array($fv)) {
  3260. continue;
  3261. }
  3262. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  3263. continue;
  3264. }
  3265. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  3266. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  3267. $field = $stripAlias($fk);
  3268. if ($sym === '=' || $sym === '') {
  3269. $eqFilters[$field] = trim((string)$fv);
  3270. } else {
  3271. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  3272. }
  3273. }
  3274. $ymTarget = '';
  3275. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  3276. $ymTarget = $ymM[1];
  3277. }
  3278. $filtered = [];
  3279. foreach ($pool as $r) {
  3280. if (!is_array($r)) {
  3281. continue;
  3282. }
  3283. foreach ($eqFilters as $field => $fv) {
  3284. if (trim((string)($r[$field] ?? '')) !== $fv) {
  3285. continue 2;
  3286. }
  3287. }
  3288. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  3289. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  3290. if (!$isManual) {
  3291. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  3292. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  3293. continue;
  3294. }
  3295. if ($applyMonthRange) {
  3296. $mo = (int)$m[2];
  3297. if ($mo < 1 || $mo > 12) {
  3298. continue;
  3299. }
  3300. if ($ymTarget !== '') {
  3301. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3302. if ($ymRow !== $ymTarget) {
  3303. continue;
  3304. }
  3305. } else {
  3306. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3307. $rowMonthStart = $ymRow . '-01 00:00:00';
  3308. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3309. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3310. continue;
  3311. }
  3312. }
  3313. }
  3314. } elseif ($applyMonthRange) {
  3315. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  3316. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3317. $ds = $listTime;
  3318. }
  3319. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  3320. continue;
  3321. }
  3322. $mo = (int)$m[2];
  3323. if ($mo < 1 || $mo > 12) {
  3324. continue;
  3325. }
  3326. if ($ymTarget !== '') {
  3327. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3328. if ($ymRow !== $ymTarget) {
  3329. continue;
  3330. }
  3331. } else {
  3332. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  3333. $rowMonthStart = $ymRow . '-01 00:00:00';
  3334. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  3335. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  3336. continue;
  3337. }
  3338. }
  3339. }
  3340. if ($search !== '') {
  3341. $hitSearch = false;
  3342. foreach ($searchColNames as $c) {
  3343. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  3344. if ($cell !== '' && $strContains($cell, $search)) {
  3345. $hitSearch = true;
  3346. break;
  3347. }
  3348. }
  3349. if (!$hitSearch) {
  3350. continue;
  3351. }
  3352. }
  3353. foreach ($otherFilters as $item) {
  3354. $fv = $item['fv'];
  3355. $sym = $item['sym'];
  3356. $field = $item['field'];
  3357. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  3358. $cellStr = trim((string)$cell);
  3359. switch ($sym) {
  3360. case '<>':
  3361. if ((string)$cell === (string)$fv) {
  3362. continue 3;
  3363. }
  3364. break;
  3365. case 'LIKE':
  3366. case 'NOT LIKE':
  3367. $needle = trim((string)$fv);
  3368. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  3369. if ($sym === 'LIKE' && !$hit) {
  3370. continue 3;
  3371. }
  3372. if ($sym === 'NOT LIKE' && $hit) {
  3373. continue 3;
  3374. }
  3375. break;
  3376. case 'BETWEEN':
  3377. case 'RANGE':
  3378. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  3379. if (count($parts) < 2) {
  3380. $parts = is_string($fv) ? explode(',', $fv) : [];
  3381. }
  3382. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  3383. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  3384. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  3385. continue 3;
  3386. }
  3387. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  3388. continue 3;
  3389. }
  3390. break;
  3391. case '>':
  3392. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  3393. continue 3;
  3394. }
  3395. break;
  3396. case '>=':
  3397. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  3398. continue 3;
  3399. }
  3400. break;
  3401. case '<':
  3402. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  3403. continue 3;
  3404. }
  3405. break;
  3406. case '<=':
  3407. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  3408. continue 3;
  3409. }
  3410. break;
  3411. default:
  3412. if ((string)$cell !== (string)$fv) {
  3413. continue 3;
  3414. }
  3415. break;
  3416. }
  3417. }
  3418. $filtered[] = $r;
  3419. }
  3420. return $filtered;
  3421. }
  3422. /**
  3423. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  3424. */
  3425. public function snapshotToProcure()
  3426. {
  3427. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3428. $this->error(__('Invalid parameters'));
  3429. }
  3430. $row = json_decode($this->request->post('row_json', ''), true);
  3431. if (!is_array($row)) {
  3432. $this->error(__('Invalid parameters'));
  3433. }
  3434. try {
  3435. $ids = $this->extractScydgyRowId($row);
  3436. if (!$this->isValidScydgyRowId($ids)) {
  3437. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3438. }
  3439. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3440. $data = [
  3441. 'scydgy_id' => $ids,
  3442. 'CCYDH' => $row['CCYDH'] ?? null,
  3443. 'CYJMC' => $row['CYJMC'] ?? null,
  3444. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3445. 'CDXMC' => $row['CDXMC'] ?? null,
  3446. 'CGYBH' => $row['CGYBH'] ?? null,
  3447. 'CGYMC' => $row['CGYMC'] ?? null,
  3448. 'CDW' => $row['CDW'] ?? null,
  3449. 'czlyq' => $row['czlyq'] ?? null,
  3450. 'NGZL' => $row['NGZL'] ?? null,
  3451. 'CDF' => $row['CDF'] ?? null,
  3452. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3453. 'MBZ' => $row['MBZ'] ?? null,
  3454. 'bwjg' => $row['bwjg'] ?? null,
  3455. 'iStatus' => $row['iStatus'] ?? null,
  3456. 'dStamp' => $row['dStamp'] ?? null,
  3457. 'dputrecord' => $row['dputrecord'] ?? null,
  3458. 'cywyxm' => $row['cywyxm'] ?? null,
  3459. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3460. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3461. ];
  3462. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3463. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3464. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3465. $this->success('操作成功');
  3466. return;
  3467. }
  3468. if ($exists) {
  3469. $upd = $data;
  3470. unset($upd['scydgy_id'], $upd['status']);
  3471. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3472. } else {
  3473. // 新增:不写 status(空/走库默认);仅写创建时间
  3474. $data['createtime'] = date('Y-m-d H:i:s');
  3475. Db::table('purchase_order')->insert($data);
  3476. }
  3477. } catch (\Throwable $e) {
  3478. $this->error($e->getMessage());
  3479. }
  3480. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3481. $this->success('操作成功');
  3482. }
  3483. /**
  3484. * 未发列表
  3485. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3486. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3487. */
  3488. public function completeDirectly()
  3489. {
  3490. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3491. $this->error(__('参数错误'));
  3492. }
  3493. if (!$this->procuremenCanComplete()) {
  3494. $this->error(__('You have no permission'));
  3495. }
  3496. $row = json_decode($this->request->post('row_json', ''), true);
  3497. if (!is_array($row)) {
  3498. $this->error(__('Invalid parameters'));
  3499. }
  3500. $finishRaw = $this->request->post('finish', '1');
  3501. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3502. $poIdLog = null;
  3503. try {
  3504. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3505. $ids = $this->extractScydgyRowId($row);
  3506. if (!$this->isValidScydgyRowId($ids)) {
  3507. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3508. }
  3509. if ($asComplete) {
  3510. $this->assertPickRowCanComplete($ids, $row);
  3511. }
  3512. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3513. $data = [
  3514. 'scydgy_id' => $ids,
  3515. 'CCYDH' => $row['CCYDH'] ?? null,
  3516. 'CYJMC' => $row['CYJMC'] ?? null,
  3517. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3518. 'CDXMC' => $row['CDXMC'] ?? null,
  3519. 'CGYBH' => $row['CGYBH'] ?? null,
  3520. 'CGYMC' => $row['CGYMC'] ?? null,
  3521. 'CDW' => $row['CDW'] ?? null,
  3522. 'czlyq' => $row['czlyq'] ?? null,
  3523. 'NGZL' => $row['NGZL'] ?? null,
  3524. 'CDF' => $row['CDF'] ?? null,
  3525. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3526. 'MBZ' => $row['MBZ'] ?? null,
  3527. 'bwjg' => $row['bwjg'] ?? null,
  3528. 'iStatus' => $row['iStatus'] ?? null,
  3529. 'dStamp' => $row['dStamp'] ?? null,
  3530. 'dputrecord' => $row['dputrecord'] ?? null,
  3531. 'cywyxm' => $row['cywyxm'] ?? null,
  3532. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3533. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3534. ];
  3535. if ($asComplete) {
  3536. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3537. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3538. }
  3539. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3540. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3541. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3542. $this->success('操作成功');
  3543. return;
  3544. }
  3545. if ($exists) {
  3546. $upd = $data;
  3547. unset($upd['scydgy_id']);
  3548. if (!$asComplete) {
  3549. unset($upd['status']);
  3550. }
  3551. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3552. } else {
  3553. // 新增:不写 status;完结时 $data 已含 status=1
  3554. $data['createtime'] = date('Y-m-d H:i:s');
  3555. Db::table('purchase_order')->insert($data);
  3556. }
  3557. } catch (\Throwable $e) {
  3558. $this->error($e->getMessage());
  3559. }
  3560. try {
  3561. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3562. if (is_array($rpo)) {
  3563. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3564. $poIdLog = $tid > 0 ? $tid : null;
  3565. }
  3566. } catch (\Throwable $e) {
  3567. $poIdLog = null;
  3568. }
  3569. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3570. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3571. if ($asComplete) {
  3572. $this->addOrderLog(
  3573. $ids,
  3574. 'mark_complete',
  3575. '点击「完结」,已标记为已完结',
  3576. $poIdLog
  3577. );
  3578. try {
  3579. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3580. if ($pdfPublicPath === '') {
  3581. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3582. }
  3583. } catch (\Throwable $e) {
  3584. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3585. }
  3586. } else {
  3587. $this->addOrderLog(
  3588. $ids,
  3589. 'save_qty_price',
  3590. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3591. $poIdLog
  3592. );
  3593. }
  3594. $this->pickHiddenScydgySetCache = null;
  3595. $this->success("操作成功");
  3596. }
  3597. /**
  3598. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3599. *
  3600. * @param array<int, array> $rows 引用传递当前页行
  3601. */
  3602. protected function mergePurchaseOrder(array &$rows)
  3603. {
  3604. if ($rows === []) {
  3605. return;
  3606. }
  3607. $ids = [];
  3608. foreach ($rows as $rw) {
  3609. if (!is_array($rw)) {
  3610. continue;
  3611. }
  3612. $id = (int)($rw['ID'] ?? 0);
  3613. if ($id > 0) {
  3614. $ids[$id] = true;
  3615. }
  3616. }
  3617. $idList = array_keys($ids);
  3618. if ($idList === []) {
  3619. return;
  3620. }
  3621. try {
  3622. $list = Db::table('purchase_order')
  3623. ->where('scydgy_id', 'in', $idList)
  3624. ->field('scydgy_id,This_quantity,ceilingPrice')
  3625. ->select();
  3626. } catch (\Throwable $e) {
  3627. return;
  3628. }
  3629. if (!is_array($list)) {
  3630. return;
  3631. }
  3632. $byId = [];
  3633. foreach ($list as $dbRow) {
  3634. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3635. continue;
  3636. }
  3637. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3638. }
  3639. foreach ($rows as &$rw) {
  3640. if (!is_array($rw)) {
  3641. continue;
  3642. }
  3643. $sid = (int)($rw['ID'] ?? 0);
  3644. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3645. continue;
  3646. }
  3647. $db = $byId[$sid];
  3648. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  3649. if (array_key_exists('This_quantity', $db)) {
  3650. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  3651. }
  3652. if (array_key_exists('ceilingPrice', $db)) {
  3653. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  3654. } elseif (array_key_exists('ceiling_price', $db)) {
  3655. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  3656. }
  3657. }
  3658. unset($rw);
  3659. }
  3660. /**
  3661. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3662. */
  3663. public function purchaseConfirmPick()
  3664. {
  3665. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3666. $this->error(__('Invalid parameters'));
  3667. }
  3668. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3669. $this->error(__('You have no permission'));
  3670. }
  3671. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3672. if ($batchRaw !== '') {
  3673. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3674. return;
  3675. }
  3676. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3677. $sid = (int)$scydgyId;
  3678. if (!$this->isValidScydgyRowId($sid)) {
  3679. $this->error('参数无效');
  3680. }
  3681. $parseIdList = function ($raw) {
  3682. if (is_array($raw)) {
  3683. $arr = $raw;
  3684. } else {
  3685. $decoded = json_decode((string)$raw, true);
  3686. $arr = is_array($decoded) ? $decoded : [];
  3687. }
  3688. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3689. };
  3690. $selectedRaw = $this->request->post('selected_ids', null);
  3691. if ($selectedRaw === null || $selectedRaw === '') {
  3692. $legacy = (int)$this->request->post('selected_id', 0);
  3693. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3694. } else {
  3695. $selectedIds = $parseIdList($selectedRaw);
  3696. }
  3697. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3698. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3699. try {
  3700. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3701. } catch (\InvalidArgumentException $e) {
  3702. $this->error($e->getMessage());
  3703. } catch (\Throwable $e) {
  3704. $this->error($e->getMessage());
  3705. }
  3706. $this->pickHiddenScydgySetCache = null;
  3707. $this->success('操作成功', '', $result);
  3708. }
  3709. /**
  3710. * 整单采购确认(多道工序一次提交)
  3711. */
  3712. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3713. {
  3714. $decoded = json_decode($batchRaw, true);
  3715. if (!is_array($decoded) || $decoded === []) {
  3716. $this->error('提交数据无效');
  3717. }
  3718. $picks = [];
  3719. foreach ($decoded as $item) {
  3720. if (!is_array($item)) {
  3721. continue;
  3722. }
  3723. $sid = (int)($item['scydgy_id'] ?? 0);
  3724. if (!$this->isValidScydgyRowId($sid)) {
  3725. continue;
  3726. }
  3727. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3728. if (!is_array($sel)) {
  3729. $sel = [(int)$sel];
  3730. }
  3731. $unsel = $item['unselected_ids'] ?? [];
  3732. if (!is_array($unsel)) {
  3733. $unsel = json_decode((string)$unsel, true);
  3734. $unsel = is_array($unsel) ? $unsel : [];
  3735. }
  3736. $picks[] = [
  3737. 'scydgy_id' => $sid,
  3738. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3739. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3740. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3741. ];
  3742. }
  3743. if ($picks === []) {
  3744. $this->error('提交数据无效');
  3745. }
  3746. Db::startTrans();
  3747. $results = [];
  3748. try {
  3749. foreach ($picks as $pick) {
  3750. $results[] = $this->runPurchaseConfirmPick(
  3751. (int)$pick['scydgy_id'],
  3752. $pick['selected_ids'],
  3753. $pick['unselected_ids'],
  3754. (int)$pick['purchase_order_id'],
  3755. false,
  3756. false
  3757. );
  3758. }
  3759. Db::commit();
  3760. } catch (\Throwable $e) {
  3761. Db::rollback();
  3762. $msg = $e->getMessage();
  3763. $this->error($msg !== '' ? $msg : '提交失败');
  3764. }
  3765. try {
  3766. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3767. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3768. } catch (\Throwable $e) {
  3769. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3770. }
  3771. $this->pickHiddenScydgySetCache = null;
  3772. $this->success('操作成功', '', ['batch' => $results]);
  3773. }
  3774. /**
  3775. * @return array<string, mixed>
  3776. */
  3777. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3778. {
  3779. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3780. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3781. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3782. $scydgyId = (string)$sid;
  3783. if ($selectedIds === []) {
  3784. throw new \InvalidArgumentException('请至少勾选一条明细');
  3785. }
  3786. $inter = array_intersect($selectedIds, $unselectedIds);
  3787. if ($inter !== []) {
  3788. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3789. }
  3790. $allIds = $this->purchaseOrderDetail($sid);
  3791. if ($allIds === []) {
  3792. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3793. }
  3794. foreach ($selectedIds as $id) {
  3795. if (!in_array($id, $allIds, true)) {
  3796. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3797. }
  3798. }
  3799. foreach ($unselectedIds as $id) {
  3800. if (!in_array($id, $allIds, true)) {
  3801. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3802. }
  3803. }
  3804. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3805. sort($union, SORT_NUMERIC);
  3806. $expect = $allIds;
  3807. sort($expect, SORT_NUMERIC);
  3808. if ($union !== $expect) {
  3809. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3810. }
  3811. if ($manageTransaction) {
  3812. Db::startTrans();
  3813. }
  3814. try {
  3815. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3816. $aff = 0;
  3817. try {
  3818. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3819. } catch (\Throwable $e) {
  3820. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3821. }
  3822. if ($aff < 1) {
  3823. throw new \Exception('更新选中状态失败');
  3824. }
  3825. $poPayload = [
  3826. 'status' => ProcuremenStatus::PO_COMPLETED,
  3827. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3828. ];
  3829. if ($purchaseOrderId > 0) {
  3830. $poAff = (int)Db::table('purchase_order')
  3831. ->where('id', $purchaseOrderId)
  3832. ->where('scydgy_id', $sid)
  3833. ->update($poPayload);
  3834. if ($poAff < 1) {
  3835. throw new \Exception('主表订单不存在或与工序行不匹配');
  3836. }
  3837. } else {
  3838. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3839. if ($poAff < 1) {
  3840. throw new \Exception('未找到');
  3841. }
  3842. }
  3843. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3844. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3845. if ($manageTransaction) {
  3846. Db::commit();
  3847. }
  3848. } catch (\Throwable $e) {
  3849. if ($manageTransaction) {
  3850. Db::rollback();
  3851. }
  3852. throw $e;
  3853. }
  3854. $poIdFinal = $purchaseOrderId;
  3855. if ($poIdFinal <= 0) {
  3856. try {
  3857. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3858. if (is_array($rpo)) {
  3859. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3860. }
  3861. } catch (\Throwable $e) {
  3862. $poIdFinal = 0;
  3863. }
  3864. }
  3865. $pickNames = [];
  3866. foreach ($selectedIds as $pid) {
  3867. $dr = $this->purchaseOrderDetai($sid, $pid);
  3868. $nm = trim((string)($dr['company_name'] ?? ''));
  3869. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3870. }
  3871. $this->addOrderLog(
  3872. $sid,
  3873. 'purchase_confirm',
  3874. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3875. $poIdFinal > 0 ? $poIdFinal : null
  3876. );
  3877. if ($sendNotifications) {
  3878. try {
  3879. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3880. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3881. 'scydgy_id' => $sid,
  3882. 'selected_ids' => $selectedIds,
  3883. 'unselected_ids' => $unselectedIds,
  3884. 'purchase_order_id' => $purchaseOrderId,
  3885. ]]);
  3886. } catch (\Throwable $e) {
  3887. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3888. }
  3889. }
  3890. Log::write(sprintf(
  3891. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3892. $scydgyId,
  3893. $purchaseOrderId,
  3894. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3895. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3896. ), 'notice');
  3897. $pdfPublicPath = '';
  3898. try {
  3899. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3900. } catch (\Throwable $e) {
  3901. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3902. }
  3903. return [
  3904. 'scydgy_id' => $scydgyId,
  3905. 'purchase_order_id' => $purchaseOrderId,
  3906. 'selected_ids' => $selectedIds,
  3907. 'unselected_ids' => $unselectedIds,
  3908. 'purchase_confirm_pdf' => $pdfPublicPath,
  3909. ];
  3910. }
  3911. /**
  3912. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3913. *
  3914. * @param int[]|string[] $scydgyIds
  3915. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3916. */
  3917. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3918. {
  3919. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3920. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3921. if ($scydgyIds === []) {
  3922. return $empty;
  3923. }
  3924. $pos = [];
  3925. try {
  3926. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3927. } catch (\Throwable $e) {
  3928. $rows = [];
  3929. }
  3930. if (is_array($rows)) {
  3931. foreach ($rows as $po) {
  3932. if (is_array($po)) {
  3933. $pos[] = $po;
  3934. }
  3935. }
  3936. }
  3937. if ($pos === []) {
  3938. return $empty;
  3939. }
  3940. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3941. return [
  3942. 'ccydh' => $ccydh,
  3943. 'pos' => $pos,
  3944. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3945. ];
  3946. }
  3947. /**
  3948. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3949. *
  3950. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3951. * @param array<int, array<string, mixed>> $picks
  3952. */
  3953. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3954. {
  3955. if ($picks === []) {
  3956. return;
  3957. }
  3958. $fallbackDetailId = 0;
  3959. $winners = [];
  3960. $losers = [];
  3961. foreach ($picks as $pick) {
  3962. if (!is_array($pick)) {
  3963. continue;
  3964. }
  3965. $sid = (int)($pick['scydgy_id'] ?? 0);
  3966. if (!$this->isValidScydgyRowId($sid)) {
  3967. continue;
  3968. }
  3969. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3970. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3971. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3972. $fallbackDetailId = (int)$selectedIds[0];
  3973. }
  3974. foreach ($selectedIds as $pid) {
  3975. $dr = $this->purchaseOrderDetai($sid, $pid);
  3976. if (!is_array($dr)) {
  3977. continue;
  3978. }
  3979. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3980. }
  3981. foreach ($unselectedIds as $pid) {
  3982. $dr = $this->purchaseOrderDetai($sid, $pid);
  3983. if (!is_array($dr)) {
  3984. continue;
  3985. }
  3986. $key = $this->notifySupplierDedupeKey($dr);
  3987. if (!isset($winners[$key])) {
  3988. $losers[$key] = $dr;
  3989. }
  3990. }
  3991. }
  3992. if ($winners === [] && $losers === []) {
  3993. return;
  3994. }
  3995. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3996. $sendSmsSafe = function ($phone, $content) {
  3997. $phone = trim((string)$phone);
  3998. if ($phone === '') {
  3999. return;
  4000. }
  4001. try {
  4002. $this->smsbao($phone, $content);
  4003. } catch (\Throwable $e) {
  4004. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4005. }
  4006. };
  4007. foreach ($winners as $dr) {
  4008. $cname = trim((string)($dr['company_name'] ?? ''));
  4009. $ph = trim((string)($dr['phone'] ?? ''));
  4010. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  4011. 'company_name' => $cname,
  4012. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4013. 'phone' => $ph,
  4014. ]));
  4015. $sendSmsSafe($ph, $sms);
  4016. }
  4017. foreach ($losers as $dr) {
  4018. $cname = trim((string)($dr['company_name'] ?? ''));
  4019. $ph = trim((string)($dr['phone'] ?? ''));
  4020. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  4021. 'company_name' => $cname,
  4022. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4023. 'phone' => $ph,
  4024. ]));
  4025. $sendSmsSafe($ph, $sms);
  4026. }
  4027. }
  4028. /**
  4029. * 短信去重键:优先手机号,否则公司名
  4030. */
  4031. protected function notifySupplierDedupeKey(array $detailRow): string
  4032. {
  4033. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  4034. if ($ph !== '') {
  4035. return 'p:' . $ph;
  4036. }
  4037. $cn = trim((string)($detailRow['company_name'] ?? ''));
  4038. return 'c:' . $cn;
  4039. }
  4040. /**
  4041. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  4042. *
  4043. * @param int[] $detailIds
  4044. */
  4045. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  4046. {
  4047. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  4048. if ($detailIds === []) {
  4049. return;
  4050. }
  4051. $payload = ['status_name' => $statusName];
  4052. try {
  4053. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  4054. } catch (\Throwable $e) {
  4055. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  4056. }
  4057. }
  4058. /**
  4059. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  4060. */
  4061. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  4062. {
  4063. try {
  4064. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  4065. } catch (\Throwable $e) {
  4066. return;
  4067. }
  4068. if (!is_array($rows)) {
  4069. return;
  4070. }
  4071. foreach ($rows as $dr) {
  4072. if (!is_array($dr)) {
  4073. continue;
  4074. }
  4075. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4076. if ($id <= 0) {
  4077. continue;
  4078. }
  4079. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  4080. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  4081. try {
  4082. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  4083. } catch (\Throwable $e) {
  4084. }
  4085. }
  4086. }
  4087. /**
  4088. * @param array<string, mixed> $detailRow
  4089. */
  4090. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  4091. {
  4092. $am = $detailRow['amount'] ?? null;
  4093. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  4094. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  4095. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  4096. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  4097. }
  4098. /**
  4099. * @return int[]
  4100. */
  4101. protected function purchaseOrderDetail(int $scydgyId): array
  4102. {
  4103. if (!$this->isValidScydgyRowId($scydgyId)) {
  4104. return [];
  4105. }
  4106. try {
  4107. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  4108. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  4109. $list = $listQuery->select();
  4110. } catch (\Throwable $e) {
  4111. return [];
  4112. }
  4113. if (!is_array($list)) {
  4114. return [];
  4115. }
  4116. $ids = [];
  4117. foreach ($list as $r) {
  4118. if (!is_array($r)) {
  4119. continue;
  4120. }
  4121. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  4122. if ($pk > 0) {
  4123. $ids[] = $pk;
  4124. }
  4125. }
  4126. return array_values(array_unique($ids));
  4127. }
  4128. /**
  4129. * 获取当前登录用户信息 [id, 展示名]
  4130. */
  4131. protected function GetUseName(): array
  4132. {
  4133. $id = 0;
  4134. $name = '';
  4135. try {
  4136. if ($this->auth && $this->auth->isLogin()) {
  4137. $u = $this->auth->getUserInfo();
  4138. if (is_array($u)) {
  4139. $id = (int)($u['id'] ?? 0);
  4140. $name = trim((string)($u['nickname'] ?? ''));
  4141. if ($name === '') {
  4142. $name = trim((string)($u['username'] ?? ''));
  4143. }
  4144. }
  4145. }
  4146. } catch (\Throwable $e) {
  4147. }
  4148. if ($name === '') {
  4149. $name = '未知用户';
  4150. }
  4151. return [$id, $name];
  4152. }
  4153. /**
  4154. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  4155. */
  4156. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  4157. {
  4158. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  4159. }
  4160. /**
  4161. * 按主键取一条
  4162. */
  4163. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  4164. {
  4165. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  4166. return [];
  4167. }
  4168. try {
  4169. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  4170. if (is_array($one)) {
  4171. return $one;
  4172. }
  4173. } catch (\Throwable $e) {
  4174. }
  4175. try {
  4176. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  4177. if (is_array($one)) {
  4178. return $one;
  4179. }
  4180. } catch (\Throwable $e) {
  4181. }
  4182. return [];
  4183. }
  4184. /**
  4185. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  4186. */
  4187. protected function formatProcuremenDetailTime($v): string
  4188. {
  4189. if ($v === null || $v === '') {
  4190. return '';
  4191. }
  4192. if (is_numeric($v) && (int)$v > 946684800) {
  4193. return date('Y-m-d H:i:s', (int)$v);
  4194. }
  4195. return ProcuremenTime::formatDisplayDateTime($v);
  4196. }
  4197. /**
  4198. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  4199. */
  4200. protected function formatDeliveryYmd($v): string
  4201. {
  4202. if ($v === null || $v === '') {
  4203. return '';
  4204. }
  4205. $s = trim((string)$v);
  4206. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  4207. return '';
  4208. }
  4209. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  4210. return $m[1];
  4211. }
  4212. $ts = strtotime($s);
  4213. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  4214. }
  4215. /**
  4216. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  4217. */
  4218. protected function detailRowSupplierOperated(array $r): bool
  4219. {
  4220. $am = $r['amount'] ?? null;
  4221. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4222. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4223. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4224. return $okAmt || $okDel;
  4225. }
  4226. /**
  4227. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  4228. */
  4229. protected function resolveDetailSupplierOperTime(array $r): string
  4230. {
  4231. if (!$this->detailRowSupplierOperated($r)) {
  4232. return '';
  4233. }
  4234. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  4235. if ($t !== '') {
  4236. return $t;
  4237. }
  4238. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  4239. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  4240. continue;
  4241. }
  4242. $t = $this->formatProcuremenDetailTime($r[$col]);
  4243. if ($t !== '') {
  4244. return $t;
  4245. }
  4246. }
  4247. return '';
  4248. }
  4249. /**
  4250. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  4251. */
  4252. protected function detailRowSupplierAccepted(array $r): bool
  4253. {
  4254. $am = $r['amount'] ?? null;
  4255. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  4256. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  4257. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  4258. return $okAmt && $okDel;
  4259. }
  4260. /**
  4261. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  4262. */
  4263. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  4264. {
  4265. if ($detailCount > 0) {
  4266. return true;
  4267. }
  4268. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  4269. return true;
  4270. }
  4271. $pickTime = trim((string)($main['pick_time'] ?? ''));
  4272. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  4273. return true;
  4274. }
  4275. return false;
  4276. }
  4277. /**
  4278. * 下发时间:优先 pick_time,其次首条下发明细时间
  4279. */
  4280. protected function resolveProcuremenIssueTime(array $main, array $details): string
  4281. {
  4282. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  4283. if ($issueTime !== '') {
  4284. return $issueTime;
  4285. }
  4286. foreach ($details as $dr) {
  4287. if (!is_array($dr)) {
  4288. continue;
  4289. }
  4290. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4291. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  4292. $issueTime = $t;
  4293. }
  4294. }
  4295. if ($issueTime !== '') {
  4296. return $issueTime;
  4297. }
  4298. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4299. }
  4300. /**
  4301. * 直接点「完结」时间:优先操作记录 mark_complete
  4302. */
  4303. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  4304. {
  4305. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  4306. }
  4307. /**
  4308. * 操作记录时间(取指定 action 最近一条)
  4309. *
  4310. * @param string|array<int, string> $actions
  4311. */
  4312. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  4313. {
  4314. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  4315. }
  4316. /**
  4317. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  4318. *
  4319. * @param array $main purchase_order 一行
  4320. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  4321. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  4322. */
  4323. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  4324. {
  4325. $issueCnt = count($details);
  4326. $acceptCnt = 0;
  4327. $pickedName = '';
  4328. $pickedTime = '';
  4329. foreach ($details as $dr) {
  4330. if (!is_array($dr)) {
  4331. continue;
  4332. }
  4333. if ($this->detailRowSupplierAccepted($dr)) {
  4334. $acceptCnt++;
  4335. }
  4336. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4337. if ($pickedName === '') {
  4338. $pickedName = trim((string)($dr['company_name'] ?? ''));
  4339. }
  4340. if ($pickedTime === '') {
  4341. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  4342. if ($pickedTime === '') {
  4343. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4344. }
  4345. }
  4346. }
  4347. }
  4348. $hasMain = $main !== [];
  4349. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  4350. if ($poTime === '') {
  4351. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  4352. }
  4353. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  4354. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  4355. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  4356. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  4357. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  4358. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  4359. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  4360. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  4361. $supplierTime = '';
  4362. if ($acceptCnt > 0) {
  4363. foreach ($details as $dr) {
  4364. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  4365. continue;
  4366. }
  4367. $t = $this->resolveDetailSupplierOperTime($dr);
  4368. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  4369. $supplierTime = $t;
  4370. }
  4371. }
  4372. }
  4373. $directComplete = ($mainCompleted && !$issued);
  4374. $doneTime = '';
  4375. if ($mainCompleted) {
  4376. if ($directComplete) {
  4377. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  4378. }
  4379. if ($doneTime === '') {
  4380. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4381. }
  4382. if ($doneTime === '') {
  4383. foreach ($details as $dr) {
  4384. if (!is_array($dr)) {
  4385. continue;
  4386. }
  4387. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  4388. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  4389. $doneTime = $t;
  4390. }
  4391. }
  4392. }
  4393. if ($doneTime === '') {
  4394. $doneTime = $poTime;
  4395. }
  4396. if ($confirmApproveTime !== '') {
  4397. $doneTime = $confirmApproveTime;
  4398. }
  4399. }
  4400. if ($directComplete) {
  4401. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  4402. $step1Done = $hasMain;
  4403. $step2Done = false;
  4404. $step3Done = false;
  4405. $step4Done = false;
  4406. $step5Done = false;
  4407. $step6Done = true;
  4408. } else {
  4409. $step1Done = $issued;
  4410. $step2Done = $issued;
  4411. $step3Done = $acceptCnt > 0;
  4412. $step4Done = $wflowPendingApproval;
  4413. if (!$step4Done) {
  4414. foreach ($details as $dr) {
  4415. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4416. $step4Done = true;
  4417. break;
  4418. }
  4419. }
  4420. }
  4421. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  4422. $step6Done = $mainCompleted;
  4423. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  4424. if ($mainCompleted && $issued) {
  4425. $step3Done = true;
  4426. $step4Done = true;
  4427. $step5Done = true;
  4428. if ($supplierTime === '') {
  4429. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4430. if ($fillT !== '') {
  4431. $supplierTime = $fillT;
  4432. }
  4433. }
  4434. if ($pickedTime === '') {
  4435. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4436. if ($fillT !== '') {
  4437. $pickedTime = $fillT;
  4438. }
  4439. }
  4440. if ($auditSelectTime === '') {
  4441. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4442. if ($fillT !== '') {
  4443. $auditSelectTime = $fillT;
  4444. }
  4445. }
  4446. if ($confirmApproveTime === '') {
  4447. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4448. if ($fillT !== '') {
  4449. $confirmApproveTime = $fillT;
  4450. }
  4451. }
  4452. }
  4453. }
  4454. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4455. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4456. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4457. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4458. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4459. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4460. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4461. $deadlineLines = [];
  4462. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  4463. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  4464. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  4465. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  4466. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  4467. }
  4468. }
  4469. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  4470. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  4471. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  4472. if ($deliveryDisp === '') {
  4473. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  4474. }
  4475. if ($deliveryDisp !== '') {
  4476. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  4477. }
  4478. }
  4479. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  4480. $deadlineText = implode("\n", $deadlineLines);
  4481. $prefixOperTime = static function (string $t): string {
  4482. $t = trim($t);
  4483. if ($t === '' || $t === '—') {
  4484. return $t;
  4485. }
  4486. if (strpos($t, '操作时间') === 0) {
  4487. return $t;
  4488. }
  4489. return '操作时间:' . $t;
  4490. };
  4491. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  4492. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  4493. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '';
  4494. $step6Time = $step6Done ? $doneTime : '';
  4495. $steps = [
  4496. [
  4497. 'title' => '未发',
  4498. 'subtitle' => '',
  4499. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  4500. 'done' => $step1Done,
  4501. ],
  4502. [
  4503. 'title' => '下发',
  4504. 'subtitle' => $deadlineText,
  4505. 'time' => $prefixOperTime($step2Time),
  4506. 'done' => $step2Done,
  4507. ],
  4508. [
  4509. 'title' => '供应商接单',
  4510. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4511. 'time' => '',
  4512. 'done' => $step3Done,
  4513. ],
  4514. [
  4515. 'title' => '待确认',
  4516. 'subtitle' => $step4Done
  4517. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4518. : ($issued ? '待选供应商' : ''),
  4519. 'time' => $prefixOperTime($step4Time),
  4520. 'done' => $step4Done,
  4521. ],
  4522. [
  4523. 'title' => '待审批',
  4524. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4525. 'time' => $prefixOperTime($step5Time),
  4526. 'done' => $step5Done,
  4527. ],
  4528. [
  4529. 'title' => '已完结',
  4530. 'subtitle' => '',
  4531. 'time' => $prefixOperTime($step6Time),
  4532. 'done' => $step6Done,
  4533. ],
  4534. ];
  4535. $currentIdx = count($steps) - 1;
  4536. if (!$directComplete) {
  4537. foreach ($steps as $i => $s) {
  4538. if (!$s['done']) {
  4539. $currentIdx = $i;
  4540. break;
  4541. }
  4542. }
  4543. }
  4544. $nSteps = count($steps);
  4545. foreach ($steps as $idx => &$s) {
  4546. $s['current'] = ($idx === $currentIdx);
  4547. if ($idx === 0) {
  4548. $s['pdf_left_bg'] = '';
  4549. } else {
  4550. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4551. }
  4552. if ($idx >= $nSteps - 1) {
  4553. $s['pdf_right_bg'] = '';
  4554. } else {
  4555. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4556. }
  4557. }
  4558. unset($s);
  4559. $labelMap = [
  4560. 'CCYDH' => '订单号',
  4561. 'CYJMC' => '印件名称',
  4562. 'CCLBMMC' => '承揽部门',
  4563. 'CGYMC' => '工序名称',
  4564. 'CDW' => '单位',
  4565. 'czlyq' => '类型',
  4566. 'NGZL' => '工作量',
  4567. 'CDF' => '单价',
  4568. 'cGzzxMc' => '工作中心',
  4569. 'MBZ' => '备注',
  4570. 'This_quantity' => '本次数量',
  4571. 'ceilingPrice' => '最高限价',
  4572. ];
  4573. $orderSummary = [];
  4574. foreach ($labelMap as $key => $lab) {
  4575. if (!array_key_exists($key, $main)) {
  4576. continue;
  4577. }
  4578. $val = $main[$key];
  4579. if ($val === null) {
  4580. $val = '';
  4581. } elseif (!is_scalar($val)) {
  4582. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4583. } else {
  4584. $val = (string)$val;
  4585. }
  4586. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4587. }
  4588. $orderSummaryGrid = [];
  4589. $n = count($orderSummary);
  4590. for ($i = 0; $i < $n; $i += 2) {
  4591. $left = $orderSummary[$i];
  4592. $hasRight = ($i + 1) < $n;
  4593. $orderSummaryGrid[] = [
  4594. 'l1' => $left['label'],
  4595. 'v1' => $left['value'],
  4596. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4597. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4598. ];
  4599. }
  4600. return [
  4601. 'steps' => $steps,
  4602. 'orderSummary' => $orderSummary,
  4603. 'orderSummaryGrid' => $orderSummaryGrid,
  4604. 'detailRows' => $details,
  4605. ];
  4606. }
  4607. /**
  4608. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4609. *
  4610. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4611. */
  4612. protected function prepareProcuremenDetailsView(string $ids): array
  4613. {
  4614. $main = [];
  4615. try {
  4616. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4617. $main = is_array($one) ? $one : [];
  4618. } catch (\Throwable $e) {
  4619. $main = [];
  4620. }
  4621. $details = [];
  4622. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4623. if ($mergeRows === []) {
  4624. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4625. if ($mergeRows === [] && $main !== []) {
  4626. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4627. }
  4628. }
  4629. $detailSidList = [];
  4630. $anchorSid = (int)$ids;
  4631. if ($anchorSid !== 0) {
  4632. $detailSidList[$anchorSid] = true;
  4633. }
  4634. foreach ($mergeRows as $mr) {
  4635. if (!is_array($mr)) {
  4636. continue;
  4637. }
  4638. $sid = $this->extractScydgyRowId($mr);
  4639. if ($sid !== 0) {
  4640. $detailSidList[$sid] = true;
  4641. }
  4642. }
  4643. try {
  4644. if ($detailSidList !== []) {
  4645. $details = Db::table('purchase_order_detail')
  4646. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4647. ->order('id', 'asc')
  4648. ->select();
  4649. }
  4650. } catch (\Throwable $e) {
  4651. $details = [];
  4652. }
  4653. if (!is_array($details)) {
  4654. $details = [];
  4655. }
  4656. foreach ($details as &$r) {
  4657. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4658. $r['id'] = $r['ID'];
  4659. }
  4660. if (isset($r['createtime'])) {
  4661. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4662. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4663. } else {
  4664. $r['createtime_text'] = (string)$r['createtime'];
  4665. }
  4666. } else {
  4667. $r['createtime_text'] = '';
  4668. }
  4669. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4670. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4671. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4672. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4673. if (is_array($r)) {
  4674. $r = $this->maskSupplierContactFields($r);
  4675. }
  4676. }
  4677. unset($r);
  4678. $activeDetails = [];
  4679. foreach ($details as $r) {
  4680. if (is_array($r) && empty($r['is_void'])) {
  4681. $activeDetails[] = $r;
  4682. }
  4683. }
  4684. $operLogs = [];
  4685. try {
  4686. $operSidList = array_keys($detailSidList);
  4687. if ($operSidList === [] && (int)$ids !== 0) {
  4688. $operSidList = [(int)$ids];
  4689. }
  4690. if ($operSidList !== []) {
  4691. $operLogs = Db::table('purchase_order_oper_log')
  4692. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  4693. ->order('id', 'asc')
  4694. ->select();
  4695. }
  4696. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  4697. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  4698. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  4699. if ($poId > 0) {
  4700. $operLogs = Db::table('purchase_order_oper_log')
  4701. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  4702. ->order('id', 'asc')
  4703. ->select();
  4704. }
  4705. }
  4706. } catch (\Throwable $e) {
  4707. $operLogs = [];
  4708. }
  4709. if (!is_array($operLogs)) {
  4710. $operLogs = [];
  4711. }
  4712. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4713. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4714. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4715. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4716. if ($ccydh === '') {
  4717. foreach ($details as $r) {
  4718. if (!is_array($r)) {
  4719. continue;
  4720. }
  4721. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4722. if ($ccydh !== '') {
  4723. break;
  4724. }
  4725. }
  4726. }
  4727. $this->view->assign('ccydh', $ccydh);
  4728. $this->view->assign('steps', $bundle['steps']);
  4729. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4730. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4731. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4732. $this->view->assign('processCount', count($mergeRows));
  4733. $this->view->assign('detailRows', $details);
  4734. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4735. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4736. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4737. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4738. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  4739. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  4740. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  4741. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  4742. $this->view->assign('operLogs', $operLogs);
  4743. $sg = $quoteView['supplier_groups'] ?? [];
  4744. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : []));
  4745. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : []) ? 1 : 0);
  4746. return [
  4747. 'ok' => $main !== [] || $details !== [],
  4748. 'ccydh' => $ccydh,
  4749. ];
  4750. }
  4751. /**
  4752. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4753. */
  4754. public function details()
  4755. {
  4756. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4757. if (is_array($ids)) {
  4758. $ids = isset($ids[0]) ? $ids[0] : '';
  4759. }
  4760. $ids = trim((string)$ids);
  4761. if ($ids === '') {
  4762. $this->error(__('Invalid parameters'));
  4763. }
  4764. $this->assertManualOrderDetailsViewable((int)$ids);
  4765. $this->prepareProcuremenDetailsView($ids);
  4766. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4767. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4768. $this->view->engine->layout(false);
  4769. try {
  4770. return $this->view->fetch('procuremen/details_dialog_shell');
  4771. } finally {
  4772. if ($restoreLayout) {
  4773. $this->view->engine->layout($restoreLayout);
  4774. }
  4775. }
  4776. }
  4777. /**
  4778. * 解析合并审核工序行(订单号须一致,且均未协助)
  4779. *
  4780. * @return array<int, array<string, mixed>>
  4781. */
  4782. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4783. {
  4784. $primary = json_decode($rowJson, true);
  4785. if (!is_array($primary)) {
  4786. $this->error(__('Invalid parameters'));
  4787. }
  4788. $merge = json_decode($mergeRowsJson, true);
  4789. if (!is_array($merge) || $merge === []) {
  4790. $merge = [$primary];
  4791. }
  4792. $seen = [];
  4793. $out = [];
  4794. foreach ($merge as $r) {
  4795. if (!is_array($r)) {
  4796. continue;
  4797. }
  4798. $id = $this->extractScydgyRowId($r);
  4799. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4800. continue;
  4801. }
  4802. $seen[$id] = true;
  4803. $out[] = $r;
  4804. }
  4805. if ($out === []) {
  4806. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4807. }
  4808. $ccydh = null;
  4809. foreach ($out as $r) {
  4810. $dh = trim((string)($r['CCYDH'] ?? ''));
  4811. if ($ccydh === null) {
  4812. $ccydh = $dh;
  4813. } elseif ($dh !== $ccydh) {
  4814. $this->error('合并审核要求所选行的订单号一致');
  4815. }
  4816. }
  4817. $ids = [];
  4818. foreach ($out as $r) {
  4819. $id = $this->extractScydgyRowId($r);
  4820. if ($this->isValidScydgyRowId($id)) {
  4821. $ids[$id] = true;
  4822. }
  4823. }
  4824. $poBySid = [];
  4825. $detCntBySid = [];
  4826. if ($ids !== []) {
  4827. $idList = array_keys($ids);
  4828. try {
  4829. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4830. if (is_array($poList)) {
  4831. foreach ($poList as $po) {
  4832. if (!is_array($po)) {
  4833. continue;
  4834. }
  4835. $sid = (int)($po['scydgy_id'] ?? 0);
  4836. if ($this->isValidScydgyRowId($sid)) {
  4837. $poBySid[$sid] = $po;
  4838. }
  4839. }
  4840. }
  4841. } catch (\Throwable $e) {
  4842. }
  4843. try {
  4844. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4845. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4846. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4847. if (is_array($detRows)) {
  4848. foreach ($detRows as $dr) {
  4849. if (!is_array($dr)) {
  4850. continue;
  4851. }
  4852. $sid = (int)($dr['scydgy_id'] ?? 0);
  4853. if ($this->isValidScydgyRowId($sid)) {
  4854. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4855. }
  4856. }
  4857. }
  4858. } catch (\Throwable $e) {
  4859. }
  4860. }
  4861. foreach ($out as $r) {
  4862. $id = $this->extractScydgyRowId($r);
  4863. if (!$this->isValidScydgyRowId($id)) {
  4864. continue;
  4865. }
  4866. $po = $poBySid[$id] ?? null;
  4867. if (!is_array($po)) {
  4868. continue;
  4869. }
  4870. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4871. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4872. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4873. }
  4874. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4875. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4876. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4877. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4878. }
  4879. }
  4880. return $out;
  4881. }
  4882. /**
  4883. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4884. */
  4885. protected function maskSupplierContactFields(array $item): array
  4886. {
  4887. if (array_key_exists('email', $item)) {
  4888. $item['email'] = mask_email((string)$item['email']);
  4889. }
  4890. if (array_key_exists('phone', $item)) {
  4891. $item['phone'] = mask_phone((string)$item['phone']);
  4892. }
  4893. return $item;
  4894. }
  4895. /**
  4896. * @param array<int, array<string, mixed>> $list
  4897. * @return array<int, array<string, mixed>>
  4898. */
  4899. protected function maskSupplierContactList(array $list): array
  4900. {
  4901. $out = [];
  4902. foreach ($list as $item) {
  4903. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4904. }
  4905. return $out;
  4906. }
  4907. /**
  4908. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4909. *
  4910. * @return array<string, string>|null
  4911. */
  4912. protected function buildCustomerContactPayloadFromRow($row): ?array
  4913. {
  4914. if (!is_array($row)) {
  4915. return null;
  4916. }
  4917. $norm = [];
  4918. foreach ($row as $k => $v) {
  4919. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4920. }
  4921. $row = $norm;
  4922. $st = $row['status'] ?? '';
  4923. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4924. return null;
  4925. }
  4926. $companyName = '';
  4927. foreach (['company_name', 'name'] as $nk) {
  4928. if (!empty($row[$nk])) {
  4929. $companyName = trim((string)$row[$nk]);
  4930. break;
  4931. }
  4932. }
  4933. if ($companyName === '') {
  4934. return null;
  4935. }
  4936. $username = '';
  4937. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4938. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4939. $username = trim((string)$row[$uk]);
  4940. break;
  4941. }
  4942. }
  4943. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4944. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4945. if ($phone === '' && isset($row['account'])) {
  4946. $phone = trim((string)$row['account']);
  4947. }
  4948. if ($phone === '' && isset($row['mobile'])) {
  4949. $phone = trim((string)$row['mobile']);
  4950. }
  4951. if ($email === '' && $phone === '') {
  4952. return null;
  4953. }
  4954. $category = '';
  4955. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4956. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4957. $category = trim((string)$row[$ck]);
  4958. break;
  4959. }
  4960. }
  4961. return [
  4962. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4963. 'name' => $companyName,
  4964. 'company_name' => $companyName,
  4965. 'username' => $username,
  4966. 'email' => $email,
  4967. 'phone' => $phone,
  4968. 'category' => $category,
  4969. 'company_type' => $category,
  4970. ];
  4971. }
  4972. /**
  4973. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4974. */
  4975. protected function resolveCustomerContactById(string $id): ?array
  4976. {
  4977. $id = trim($id);
  4978. if ($id === '' || !ctype_digit($id)) {
  4979. return null;
  4980. }
  4981. try {
  4982. $row = Db::table('customer')->where('id', (int)$id)->find();
  4983. } catch (\Throwable $e) {
  4984. return null;
  4985. }
  4986. return $this->buildCustomerContactPayloadFromRow($row);
  4987. }
  4988. /**
  4989. * 按供应商名称解析联系信息(兼容旧提交数据)
  4990. */
  4991. protected function resolveCustomerContactByCompanyName(string $name): ?array
  4992. {
  4993. $name = trim($name);
  4994. if ($name === '') {
  4995. return null;
  4996. }
  4997. try {
  4998. $row = Db::table('customer')
  4999. ->where(function ($q) use ($name) {
  5000. $q->where('company_name', $name)->whereOr('name', $name);
  5001. })
  5002. ->order('id', 'desc')
  5003. ->find();
  5004. } catch (\Throwable $e) {
  5005. return null;
  5006. }
  5007. return $this->buildCustomerContactPayloadFromRow($row);
  5008. }
  5009. /**
  5010. * 规范化下发/确认时勾选的供应商
  5011. *
  5012. * @param array<int, mixed> $companies
  5013. * @return array<int, array<string, string>>
  5014. */
  5015. protected function normalizePickCompanies(array $companies): array
  5016. {
  5017. $out = [];
  5018. foreach ($companies as $c) {
  5019. if (!is_array($c)) {
  5020. continue;
  5021. }
  5022. $resolved = null;
  5023. $cid = trim((string)($c['id'] ?? ''));
  5024. if ($cid !== '') {
  5025. $resolved = $this->resolveCustomerContactById($cid);
  5026. }
  5027. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  5028. if ($resolved === null && $name !== '') {
  5029. $resolved = $this->resolveCustomerContactByCompanyName($name);
  5030. }
  5031. if ($resolved === null) {
  5032. continue;
  5033. }
  5034. $out[] = $resolved;
  5035. }
  5036. return $out;
  5037. }
  5038. /**
  5039. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  5040. *
  5041. * @param array<int, array<string, mixed>> $pool
  5042. * @return array<int, array<string, mixed>>
  5043. */
  5044. protected function collapseProcuremenPoolByOrder(array $pool): array
  5045. {
  5046. if ($pool === []) {
  5047. return [];
  5048. }
  5049. $groups = [];
  5050. foreach ($pool as $row) {
  5051. if (!is_array($row)) {
  5052. continue;
  5053. }
  5054. $dh = trim((string)($row['CCYDH'] ?? ''));
  5055. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  5056. if (!isset($groups[$key])) {
  5057. $groups[$key] = [];
  5058. }
  5059. $groups[$key][] = $row;
  5060. }
  5061. $out = [];
  5062. foreach ($groups as $ccydh => $rows) {
  5063. if ($rows === []) {
  5064. continue;
  5065. }
  5066. usort($rows, function ($a, $b) {
  5067. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  5068. });
  5069. $head = $rows[0];
  5070. $gymcList = [];
  5071. foreach ($rows as $r) {
  5072. $g = trim((string)($r['CGYMC'] ?? ''));
  5073. if ($g !== '' && !in_array($g, $gymcList, true)) {
  5074. $gymcList[] = $g;
  5075. }
  5076. }
  5077. $merged = $head;
  5078. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  5079. $merged['process_count'] = count($rows);
  5080. $merged['_order_merge_rows'] = $rows;
  5081. if (count($rows) > 1) {
  5082. $merged['CGYMC'] = implode('、', $gymcList);
  5083. }
  5084. $mergedPickTime = '';
  5085. foreach ($rows as $r) {
  5086. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  5087. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  5088. $mergedPickTime = $t;
  5089. }
  5090. }
  5091. if ($mergedPickTime !== '') {
  5092. $merged['pick_time'] = $mergedPickTime;
  5093. }
  5094. $out[] = $merged;
  5095. }
  5096. usort($out, function ($a, $b) {
  5097. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  5098. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  5099. if ($ta === $tb) {
  5100. $ida = (int)($a['purchase_order_id'] ?? 0);
  5101. $idb = (int)($b['purchase_order_id'] ?? 0);
  5102. if ($ida !== $idb) {
  5103. return $idb <=> $ida;
  5104. }
  5105. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  5106. }
  5107. if ($ta === '') {
  5108. return 1;
  5109. }
  5110. if ($tb === '') {
  5111. return -1;
  5112. }
  5113. return strcmp($tb, $ta);
  5114. });
  5115. return $out;
  5116. }
  5117. /**
  5118. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  5119. *
  5120. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5121. */
  5122. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  5123. {
  5124. $scydgyId = trim($scydgyId);
  5125. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5126. if ($scydgyId === '') {
  5127. return $empty;
  5128. }
  5129. try {
  5130. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5131. } catch (\Throwable $e) {
  5132. $anchor = null;
  5133. }
  5134. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  5135. return $empty;
  5136. }
  5137. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5138. if ($ccydh === '') {
  5139. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  5140. }
  5141. try {
  5142. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  5143. } catch (\Throwable $e) {
  5144. $pos = [$anchor];
  5145. }
  5146. if (!is_array($pos) || $pos === []) {
  5147. $pos = [$anchor];
  5148. }
  5149. return [
  5150. 'ccydh' => $ccydh,
  5151. 'pos' => $pos,
  5152. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5153. ];
  5154. }
  5155. /**
  5156. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  5157. */
  5158. protected function purchaseOrderRowInConfirmStage(array $po): bool
  5159. {
  5160. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  5161. return false;
  5162. }
  5163. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  5164. return false;
  5165. }
  5166. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  5167. return true;
  5168. }
  5169. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  5170. $sid = (int)($po['scydgy_id'] ?? 0);
  5171. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  5172. }
  5173. return false;
  5174. }
  5175. /**
  5176. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  5177. *
  5178. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5179. */
  5180. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  5181. {
  5182. $scydgyId = trim($scydgyId);
  5183. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5184. if ($scydgyId === '') {
  5185. return $empty;
  5186. }
  5187. try {
  5188. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5189. } catch (\Throwable $e) {
  5190. $anchor = null;
  5191. }
  5192. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  5193. return $empty;
  5194. }
  5195. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5196. if ($ccydh === '') {
  5197. return [
  5198. 'ccydh' => '',
  5199. 'pos' => [$anchor],
  5200. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  5201. ];
  5202. }
  5203. try {
  5204. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  5205. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  5206. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  5207. } catch (\Throwable $e) {
  5208. $pos = [$anchor];
  5209. }
  5210. if (!is_array($pos) || $pos === []) {
  5211. $pos = [$anchor];
  5212. }
  5213. $pos = array_values(array_filter($pos, function ($po) {
  5214. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  5215. }));
  5216. if ($pos === []) {
  5217. $pos = [$anchor];
  5218. }
  5219. return [
  5220. 'ccydh' => $ccydh,
  5221. 'pos' => $pos,
  5222. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5223. ];
  5224. }
  5225. /**
  5226. * @param array<int, array<string, mixed>> $purchaseOrders
  5227. * @return array<int, array<string, mixed>>
  5228. */
  5229. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  5230. {
  5231. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  5232. $byId = [];
  5233. foreach ($pool as $r) {
  5234. if (!is_array($r)) {
  5235. continue;
  5236. }
  5237. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  5238. if ($this->isValidScydgyRowId($sid)) {
  5239. $byId[$sid] = $r;
  5240. }
  5241. }
  5242. $out = [];
  5243. foreach ($purchaseOrders as $po) {
  5244. if (!is_array($po)) {
  5245. continue;
  5246. }
  5247. $sid = (int)($po['scydgy_id'] ?? 0);
  5248. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  5249. $out[] = $byId[$sid];
  5250. }
  5251. }
  5252. return $out;
  5253. }
  5254. /**
  5255. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  5256. *
  5257. * @return array<int, array<string, mixed>>
  5258. */
  5259. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  5260. {
  5261. $scydgyId = trim($scydgyId);
  5262. if ($scydgyId === '') {
  5263. return [];
  5264. }
  5265. try {
  5266. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5267. } catch (\Throwable $e) {
  5268. $anchor = null;
  5269. }
  5270. if (!is_array($anchor)) {
  5271. return [];
  5272. }
  5273. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  5274. return [];
  5275. }
  5276. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5277. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  5278. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  5279. try {
  5280. $q = Db::table('purchase_order');
  5281. if ($ccydh !== '') {
  5282. $q->where('CCYDH', $ccydh);
  5283. } else {
  5284. $q->where('scydgy_id', $scydgyId);
  5285. }
  5286. if ($isValidPick) {
  5287. $q->where('pick_time', $pickTime);
  5288. }
  5289. $pos = $q->order('scydgy_id', 'asc')->select();
  5290. } catch (\Throwable $e) {
  5291. $pos = [$anchor];
  5292. }
  5293. if (!is_array($pos) || $pos === []) {
  5294. $pos = [$anchor];
  5295. }
  5296. $pos = array_values(array_filter($pos, function ($po) {
  5297. if (!is_array($po)) {
  5298. return false;
  5299. }
  5300. $mr = $po['mod_rq'] ?? null;
  5301. if ($mr === null || $mr === '') {
  5302. return true;
  5303. }
  5304. $mrs = trim((string)$mr);
  5305. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  5306. }));
  5307. if ($pos === []) {
  5308. $pos = [$anchor];
  5309. }
  5310. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  5311. if ($rows === []) {
  5312. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  5313. }
  5314. return $rows;
  5315. }
  5316. /**
  5317. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  5318. *
  5319. * @param array<int, array<string, mixed>> $mergeRows
  5320. * @return array<int, array<string, mixed>>
  5321. */
  5322. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  5323. {
  5324. $list = array_values($mergeRows);
  5325. $n = count($list);
  5326. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  5327. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  5328. $mergeSame = $n > 1 && $orderKey0 !== '';
  5329. if ($mergeSame) {
  5330. foreach ($list as $rr) {
  5331. if (!is_array($rr)) {
  5332. $mergeSame = false;
  5333. break;
  5334. }
  5335. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  5336. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  5337. $mergeSame = false;
  5338. break;
  5339. }
  5340. }
  5341. }
  5342. $out = [];
  5343. foreach ($list as $idx => $r) {
  5344. if (!is_array($r)) {
  5345. continue;
  5346. }
  5347. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  5348. if (is_scalar($qty)) {
  5349. $qty = trim((string)$qty);
  5350. } else {
  5351. $qty = '';
  5352. }
  5353. if ($qty === '') {
  5354. $gzl = $r['NGZL'] ?? '';
  5355. if (is_scalar($gzl)) {
  5356. $qty = trim((string)$gzl);
  5357. }
  5358. }
  5359. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  5360. $sid = $this->extractScydgyRowId($r);
  5361. $out[] = [
  5362. 'seq' => $idx + 1,
  5363. 'scydgy_id' => $sid,
  5364. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5365. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5366. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5367. 'CDW' => trim((string)($r['CDW'] ?? '')),
  5368. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  5369. 'NGZL' => $r['NGZL'] ?? '',
  5370. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  5371. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  5372. 'CDF' => trim((string)($r['CDF'] ?? '')),
  5373. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  5374. 'show_order_cells' => !$mergeSame || $idx === 0,
  5375. 'order_rowspan' => $mergeSame ? $n : 1,
  5376. ];
  5377. }
  5378. return $out;
  5379. }
  5380. /**
  5381. * 解析金额/数量(去千分位等非数字字符)
  5382. */
  5383. protected function parseProcuremenMoneyNumber($value): ?float
  5384. {
  5385. if ($value === null || $value === '') {
  5386. return null;
  5387. }
  5388. if (is_numeric($value)) {
  5389. return (float)$value;
  5390. }
  5391. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  5392. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  5393. }
  5394. protected function formatProcuremenMoneyDisplay(?float $amount): string
  5395. {
  5396. if ($amount === null) {
  5397. return '';
  5398. }
  5399. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  5400. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  5401. return $s === '' ? '0' : $s;
  5402. }
  5403. /**
  5404. * 列表/详情展示:工作量为 0 时显示空
  5405. */
  5406. protected function formatProcuremenWorkloadDisplay($value): string
  5407. {
  5408. if ($value === null || $value === '') {
  5409. return '';
  5410. }
  5411. $s = trim((string)$value);
  5412. if ($s === '') {
  5413. return '';
  5414. }
  5415. if (is_numeric($s) && (float)$s == 0) {
  5416. return '';
  5417. }
  5418. return $s;
  5419. }
  5420. /**
  5421. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  5422. */
  5423. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  5424. {
  5425. foreach ($details as $d) {
  5426. if (!is_array($d)) {
  5427. continue;
  5428. }
  5429. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  5430. $cn = trim((string)($d['company_name'] ?? ''));
  5431. if ($cn !== '') {
  5432. return $cn;
  5433. }
  5434. }
  5435. }
  5436. return trim((string)($main['pick_company_name'] ?? ''));
  5437. }
  5438. /**
  5439. * 详情报价小计:单价 × 本工序本次数量
  5440. */
  5441. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  5442. {
  5443. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  5444. if ($unit === null) {
  5445. return null;
  5446. }
  5447. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  5448. if ($qty === null || $qty <= 0) {
  5449. return null;
  5450. }
  5451. return $unit * $qty;
  5452. }
  5453. /**
  5454. * 详情页:工序小计 + 供应商分组报价与总计
  5455. *
  5456. * @param array<int, array<string, mixed>> $mergeRows
  5457. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  5458. * @return array{
  5459. * process_rows: array,
  5460. * supplier_groups: array,
  5461. * order_total_text: string,
  5462. * order_total_has: bool,
  5463. * selected_company: string
  5464. * }
  5465. */
  5466. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  5467. {
  5468. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5469. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  5470. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  5471. $qtyBySid = [];
  5472. $gymcBySid = [];
  5473. $orderedSids = [];
  5474. foreach ($mergeRows as $mr) {
  5475. if (!is_array($mr)) {
  5476. continue;
  5477. }
  5478. $sid = $this->extractScydgyRowId($mr);
  5479. if ($this->isValidScydgyRowId($sid)) {
  5480. $orderedSids[] = $sid;
  5481. }
  5482. $qty = trim((string)($mr['This_quantity'] ?? ''));
  5483. if ($qty === '') {
  5484. $qty = trim((string)($mr['NGZL'] ?? ''));
  5485. }
  5486. $qtyBySid[$sid] = $qty;
  5487. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  5488. }
  5489. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  5490. $detailByCompanySid = [];
  5491. foreach ($details as $d) {
  5492. if (!is_array($d)) {
  5493. continue;
  5494. }
  5495. $cn = trim((string)($d['company_name'] ?? ''));
  5496. $sid = (int)($d['scydgy_id'] ?? 0);
  5497. if ($cn === '' || $sid === 0) {
  5498. continue;
  5499. }
  5500. if (!isset($detailByCompanySid[$cn])) {
  5501. $detailByCompanySid[$cn] = [];
  5502. }
  5503. $detailByCompanySid[$cn][$sid] = $d;
  5504. }
  5505. $supplierGroups = [];
  5506. foreach ($detailByCompanySid as $cn => $bySid) {
  5507. $lines = [];
  5508. $groupTotal = 0.0;
  5509. $groupHas = false;
  5510. $groupVoid = true;
  5511. $usedSids = [];
  5512. $appendLine = function (int $sid, array $d) use (
  5513. &$lines,
  5514. &$groupTotal,
  5515. &$groupHas,
  5516. &$groupVoid,
  5517. $qtyBySid,
  5518. $gymcBySid,
  5519. $quoteVisible
  5520. ) {
  5521. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5522. if (!$isVoid) {
  5523. $groupVoid = false;
  5524. }
  5525. $qtyStr = $qtyBySid[$sid] ?? '';
  5526. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5527. $am = trim((string)($d['amount'] ?? ''));
  5528. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5529. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5530. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5531. $sub = null;
  5532. if (!$isVoid && $amountNum !== null) {
  5533. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5534. }
  5535. $ct = $this->resolveDetailSupplierOperTime($d);
  5536. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  5537. $leadFilled = ($leadDays !== null);
  5538. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  5539. $line = [
  5540. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5541. 'amount' => $am,
  5542. 'unit_price_text' => $amountFilled
  5543. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  5544. : '未填写',
  5545. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5546. 'delivery_ymd' => $deliveryYmd,
  5547. 'amount_filled' => $amountFilled,
  5548. 'delivery_filled' => $deliveryFilled,
  5549. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5550. 'lead_days' => $leadFilled ? $leadDays : '',
  5551. 'lead_days_filled'=> $leadFilled,
  5552. 'lead_days_show' => $leadText,
  5553. 'lead_days_text' => $leadText,
  5554. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5555. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5556. 'is_void' => $isVoid,
  5557. 'oper_time_text' => $ct,
  5558. ];
  5559. if (!$quoteVisible && !$isVoid) {
  5560. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5561. } elseif ($sub !== null) {
  5562. $groupTotal += $sub;
  5563. $groupHas = true;
  5564. }
  5565. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5566. };
  5567. foreach ($orderedSids as $sid) {
  5568. if (!isset($bySid[$sid])) {
  5569. continue;
  5570. }
  5571. $usedSids[$sid] = true;
  5572. $appendLine($sid, $bySid[$sid]);
  5573. }
  5574. foreach ($bySid as $sid => $d) {
  5575. if (isset($usedSids[$sid])) {
  5576. continue;
  5577. }
  5578. $appendLine((int)$sid, $d);
  5579. }
  5580. $firstDetail = null;
  5581. foreach ($bySid as $d) {
  5582. if (is_array($d)) {
  5583. $firstDetail = $d;
  5584. break;
  5585. }
  5586. }
  5587. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5588. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5589. if ($username === '' && $ph !== '') {
  5590. $username = $this->resolveCustomerContactName($ph, $cn);
  5591. }
  5592. $remark = '';
  5593. foreach ($bySid as $d) {
  5594. if (!is_array($d)) {
  5595. continue;
  5596. }
  5597. $rm = '';
  5598. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  5599. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  5600. $rm = trim((string)$d[$rk]);
  5601. break;
  5602. }
  5603. }
  5604. if ($rm !== '') {
  5605. $remark = $rm;
  5606. break;
  5607. }
  5608. }
  5609. $lineCount = count($lines);
  5610. $hasRemark = $lineCount > 0;
  5611. $supplierGroup = [
  5612. 'company_name' => $cn,
  5613. 'username' => $username,
  5614. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5615. 'phone' => $ph,
  5616. 'remark' => $remark,
  5617. 'has_remark' => $hasRemark,
  5618. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5619. 'is_void' => $groupVoid,
  5620. 'lines' => $lines,
  5621. 'line_count' => $lineCount,
  5622. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  5623. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5624. 'has_total' => $lineCount > 0,
  5625. ];
  5626. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  5627. $supplierGroups[] = $supplierGroup;
  5628. }
  5629. usort($supplierGroups, function ($a, $b) {
  5630. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5631. return ($a['is_void'] ?? false) ? 1 : -1;
  5632. }
  5633. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5634. return ($a['is_selected'] ?? false) ? -1 : 1;
  5635. }
  5636. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5637. });
  5638. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  5639. return [
  5640. 'process_rows' => $processRows,
  5641. 'supplier_groups' => $supplierGroups,
  5642. 'order_total_text' => '',
  5643. 'order_total_has' => false,
  5644. 'selected_company' => $selectedCompany,
  5645. ];
  5646. }
  5647. /**
  5648. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5649. */
  5650. protected function buildProcessLinesPlain(array $mergeRows): string
  5651. {
  5652. $lines = [];
  5653. $i = 1;
  5654. foreach ($mergeRows as $r) {
  5655. if (!is_array($r)) {
  5656. continue;
  5657. }
  5658. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5659. $dw = trim((string)($r['CDW'] ?? ''));
  5660. $gzl = trim((string)($r['NGZL'] ?? ''));
  5661. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5662. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5663. if ($dw !== '') {
  5664. $parts[] = '单位:' . $dw;
  5665. }
  5666. if ($gzl !== '') {
  5667. $parts[] = '工作量:' . $gzl;
  5668. }
  5669. if ($qty !== '') {
  5670. $parts[] = '本次数量:' . $qty;
  5671. }
  5672. $lines[] = implode(' ', $parts);
  5673. $i++;
  5674. }
  5675. return implode("\n", $lines);
  5676. }
  5677. /**
  5678. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5679. *
  5680. * @return array<string, string>
  5681. */
  5682. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5683. {
  5684. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5685. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5686. }
  5687. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5688. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5689. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5690. $cyjmc = '';
  5691. foreach ($mergeRows as $mr) {
  5692. if (!is_array($mr)) {
  5693. continue;
  5694. }
  5695. if ($ccydh === '') {
  5696. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5697. }
  5698. if ($cyjmc === '') {
  5699. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5700. }
  5701. }
  5702. if ($pos !== []) {
  5703. $firstPo = $pos[0];
  5704. if (is_array($firstPo)) {
  5705. if ($ccydh === '') {
  5706. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5707. }
  5708. if ($cyjmc === '') {
  5709. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5710. }
  5711. }
  5712. }
  5713. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5714. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5715. if (is_array($any)) {
  5716. if ($ccydh === '') {
  5717. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5718. }
  5719. if ($cyjmc === '') {
  5720. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5721. }
  5722. }
  5723. }
  5724. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5725. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5726. $cgymc = '';
  5727. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5728. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5729. }
  5730. return [
  5731. 'ccydh' => $ccydh,
  5732. 'cyjmc' => $cyjmc,
  5733. 'cgymc' => $cgymc,
  5734. 'process_lines' => $processLines,
  5735. 'process_lines_html' => '',
  5736. ];
  5737. }
  5738. /**
  5739. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5740. */
  5741. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5742. {
  5743. $lines = [];
  5744. if ($ccydh !== '') {
  5745. $lines[] = '订单号:' . $ccydh;
  5746. }
  5747. if ($cyjmc !== '') {
  5748. $lines[] = '印件名称:' . $cyjmc;
  5749. }
  5750. if ($processPlain !== '') {
  5751. $lines[] = $processPlain;
  5752. }
  5753. return implode("\n", $lines);
  5754. }
  5755. /**
  5756. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5757. *
  5758. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5759. */
  5760. protected function buildPlatformLinksPlain(array $detailLinks): string
  5761. {
  5762. $lines = [];
  5763. $i = 1;
  5764. foreach ($detailLinks as $lk) {
  5765. if (!is_array($lk)) {
  5766. continue;
  5767. }
  5768. $url = trim((string)($lk['url'] ?? ''));
  5769. if ($url === '') {
  5770. continue;
  5771. }
  5772. $label = trim((string)($lk['cgymc'] ?? ''));
  5773. if ($label === '') {
  5774. $label = '工序' . $i;
  5775. }
  5776. $lines[] = $label . ':' . $url;
  5777. $i++;
  5778. }
  5779. return implode("\n", $lines);
  5780. }
  5781. /**
  5782. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5783. *
  5784. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5785. */
  5786. protected function buildPlatformLinksHtml(array $detailLinks): string
  5787. {
  5788. $parts = [];
  5789. $i = 1;
  5790. foreach ($detailLinks as $lk) {
  5791. if (!is_array($lk)) {
  5792. continue;
  5793. }
  5794. $url = trim((string)($lk['url'] ?? ''));
  5795. if ($url === '') {
  5796. continue;
  5797. }
  5798. $label = trim((string)($lk['cgymc'] ?? ''));
  5799. if ($label === '') {
  5800. $label = '工序' . $i;
  5801. }
  5802. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5803. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5804. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5805. $i++;
  5806. }
  5807. return implode("<br>\n", $parts);
  5808. }
  5809. /**
  5810. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5811. *
  5812. * @return array<string, mixed>
  5813. */
  5814. protected function loadMailerConfig(): array
  5815. {
  5816. try {
  5817. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5818. } catch (\Throwable $e) {
  5819. $cfg = [];
  5820. }
  5821. return is_array($cfg) ? $cfg : [];
  5822. }
  5823. protected function loadNotifyTemplateRow(string $scene): ?array
  5824. {
  5825. try {
  5826. $row = Db::table('purchase_sms_template')
  5827. ->where('scene', $scene)
  5828. ->where(function ($q) {
  5829. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5830. })
  5831. ->order('id', 'asc')
  5832. ->find();
  5833. } catch (\Throwable $e) {
  5834. return null;
  5835. }
  5836. if (!is_array($row) || $row === []) {
  5837. return null;
  5838. }
  5839. return [
  5840. 'title' => trim((string)($row['title'] ?? '')),
  5841. 'content' => trim((string)($row['content'] ?? '')),
  5842. ];
  5843. }
  5844. /**
  5845. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5846. */
  5847. protected function buildProcessLinesHtml(array $mergeRows): string
  5848. {
  5849. if (count($mergeRows) <= 1) {
  5850. $r = $mergeRows[0] ?? [];
  5851. if (!is_array($r)) {
  5852. return '';
  5853. }
  5854. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5855. $dw = trim((string)($r['CDW'] ?? ''));
  5856. $gzl = trim((string)($r['NGZL'] ?? ''));
  5857. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5858. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5859. if ($dw !== '') {
  5860. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5861. }
  5862. if ($gzl !== '') {
  5863. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5864. }
  5865. if ($qty !== '') {
  5866. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5867. }
  5868. return $html;
  5869. }
  5870. $rows = '';
  5871. $i = 1;
  5872. foreach ($mergeRows as $r) {
  5873. if (!is_array($r)) {
  5874. continue;
  5875. }
  5876. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5877. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5878. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5879. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5880. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5881. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5882. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5883. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5884. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5885. $i++;
  5886. }
  5887. if ($rows === '') {
  5888. return '';
  5889. }
  5890. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5891. . '<thead><tr style="background:#f5f5f5;">'
  5892. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5893. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5894. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5895. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5896. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5897. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5898. }
  5899. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  5900. {
  5901. $sysRq = trim($sysRq);
  5902. if ($sysRq === '') {
  5903. if ($required) {
  5904. $this->error('请选择招标截止日期');
  5905. }
  5906. return '';
  5907. }
  5908. $ts = strtotime($sysRq);
  5909. if ($ts === false || $ts <= 0) {
  5910. $this->error('招标截止日期格式无效');
  5911. }
  5912. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  5913. if (!$allowPast) {
  5914. $ymd = date('Y-m-d', $ts);
  5915. if ($ymd < date('Y-m-d')) {
  5916. $this->error('招标截止日期不能早于今天');
  5917. }
  5918. if ($ts <= time()) {
  5919. $this->error('招标截止时间不能早于当前时间');
  5920. }
  5921. }
  5922. return date('Y-m-d H:i:s', $ts);
  5923. }
  5924. /**
  5925. * 确保 purchase_order.czlyq(类型)存在
  5926. */
  5927. protected function ensurePurchaseOrderCzlyqColumn(): void
  5928. {
  5929. static $done = false;
  5930. if ($done) {
  5931. return;
  5932. }
  5933. $done = true;
  5934. try {
  5935. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  5936. if (empty($cols)) {
  5937. Db::execute(
  5938. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  5939. );
  5940. }
  5941. } catch (\Throwable $e) {
  5942. // ignore
  5943. }
  5944. }
  5945. /**
  5946. * 确保 purchase_order.delivery_deadline 存在
  5947. */
  5948. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  5949. {
  5950. static $done = false;
  5951. if ($done) {
  5952. return;
  5953. }
  5954. $done = true;
  5955. try {
  5956. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  5957. if (empty($cols)) {
  5958. Db::execute(
  5959. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  5960. );
  5961. }
  5962. } catch (\Throwable $e) {
  5963. // ignore
  5964. }
  5965. }
  5966. /**
  5967. * 解析交货截止日期(仅年月日)
  5968. */
  5969. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  5970. {
  5971. $raw = trim($raw);
  5972. if ($raw === '') {
  5973. if ($required) {
  5974. $this->error('请选择交货截止日期');
  5975. }
  5976. return '';
  5977. }
  5978. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  5979. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  5980. } else {
  5981. $ts = strtotime(str_replace('/', '-', $raw));
  5982. if ($ts === false || $ts <= 0) {
  5983. $this->error('交货截止日期格式无效');
  5984. }
  5985. $ymd = date('Y-m-d', $ts);
  5986. }
  5987. if ($ymd < date('Y-m-d')) {
  5988. $this->error('交货截止日期不能早于今天');
  5989. }
  5990. return $ymd;
  5991. }
  5992. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  5993. {
  5994. $s = trim((string)$value);
  5995. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  5996. return '';
  5997. }
  5998. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5999. return $m[1];
  6000. }
  6001. $ts = strtotime(str_replace('/', '-', $s));
  6002. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  6003. }
  6004. /**
  6005. * @param array{pos?:array} $bundle
  6006. */
  6007. protected function resolveBundleDeliveryDeadline(array $bundle): string
  6008. {
  6009. foreach ($bundle['pos'] ?? [] as $po) {
  6010. if (!is_array($po)) {
  6011. continue;
  6012. }
  6013. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  6014. if ($d !== '') {
  6015. return $d;
  6016. }
  6017. }
  6018. return '';
  6019. }
  6020. protected function formatProcuremenSysRqForInput($sysRq): string
  6021. {
  6022. $sr = trim((string)$sysRq);
  6023. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  6024. return '';
  6025. }
  6026. $ts = strtotime($sr);
  6027. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  6028. }
  6029. protected function formatProcuremenSysRqForDisplay($sysRq): string
  6030. {
  6031. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  6032. if ($sr === '') {
  6033. return '—';
  6034. }
  6035. $ts = strtotime($sr);
  6036. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  6037. }
  6038. /**
  6039. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  6040. *
  6041. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  6042. * @return array{ccydh?:string,pos:array,merge_rows:array}
  6043. */
  6044. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  6045. {
  6046. return $bundle;
  6047. }
  6048. /**
  6049. * 写入/更新 purchase_order(单道工序行)
  6050. */
  6051. protected function upsertPurchaseOrderFromRow(
  6052. array $row,
  6053. string $sysRqDb,
  6054. $wflowStatus = null,
  6055. ?string $pickTime = null,
  6056. ?array $exists = null,
  6057. ?string $deliveryDeadline = null
  6058. ): void {
  6059. $ids = $this->extractScydgyRowId($row);
  6060. if (!$this->isValidScydgyRowId($ids)) {
  6061. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  6062. }
  6063. if ($exists === null) {
  6064. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6065. }
  6066. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  6067. $this->ensurePurchaseOrderCzlyqColumn();
  6068. $data = [
  6069. 'scydgy_id' => $ids,
  6070. 'CCYDH' => $row['CCYDH'] ?? null,
  6071. 'CYJMC' => $row['CYJMC'] ?? null,
  6072. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  6073. 'CDXMC' => $row['CDXMC'] ?? null,
  6074. 'CGYBH' => $row['CGYBH'] ?? null,
  6075. 'CGYMC' => $row['CGYMC'] ?? null,
  6076. 'CDW' => $row['CDW'] ?? null,
  6077. 'czlyq' => $row['czlyq'] ?? null,
  6078. 'NGZL' => $row['NGZL'] ?? null,
  6079. 'CDF' => $row['CDF'] ?? null,
  6080. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  6081. 'MBZ' => $row['MBZ'] ?? null,
  6082. 'bwjg' => $row['bwjg'] ?? null,
  6083. 'iStatus' => $row['iStatus'] ?? null,
  6084. 'dStamp' => $row['dStamp'] ?? null,
  6085. 'dputrecord' => $row['dputrecord'] ?? null,
  6086. 'cywyxm' => $row['cywyxm'] ?? null,
  6087. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  6088. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  6089. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6090. 'sys_rq' => $sysRqDb,
  6091. ];
  6092. if ($deliveryDeadline !== null) {
  6093. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  6094. }
  6095. if ($wflowStatus !== null && $wflowStatus !== '') {
  6096. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  6097. }
  6098. if ($pickTime !== null && $pickTime !== '') {
  6099. $data['pick_time'] = $pickTime;
  6100. $data['pick_company_name'] = '';
  6101. }
  6102. if ($exists) {
  6103. $upd = $data;
  6104. unset($upd['scydgy_id']);
  6105. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  6106. } else {
  6107. $data['createtime'] = date('Y-m-d H:i:s');
  6108. Db::table('purchase_order')->insert($data);
  6109. }
  6110. }
  6111. /**
  6112. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  6113. *
  6114. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  6115. */
  6116. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  6117. {
  6118. $toDb = function ($value) {
  6119. if ($value === null) {
  6120. return null;
  6121. }
  6122. if (is_scalar($value)) {
  6123. return $value;
  6124. }
  6125. return json_encode($value, JSON_UNESCAPED_UNICODE);
  6126. };
  6127. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  6128. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  6129. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  6130. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  6131. if ($username === '') {
  6132. $username = $this->resolveCustomerContactName($phone, $companyName);
  6133. }
  6134. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  6135. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  6136. }
  6137. if ($phone === '') {
  6138. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  6139. }
  6140. $detailLinks = [];
  6141. foreach ($mergeRows as $row) {
  6142. if (!is_array($row)) {
  6143. continue;
  6144. }
  6145. $sid = $this->extractScydgyRowId($row);
  6146. $detailId = 0;
  6147. if ($skipExisting) {
  6148. try {
  6149. $existsQuery = Db::table('purchase_order_detail')
  6150. ->where('scydgy_id', $sid)
  6151. ->where('company_name', $companyName);
  6152. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  6153. $exists = $existsQuery->find();
  6154. } catch (\Throwable $e) {
  6155. $exists = null;
  6156. }
  6157. if (is_array($exists)) {
  6158. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  6159. }
  6160. }
  6161. if ($detailId <= 0) {
  6162. $one = [
  6163. 'scydgy_id' => $toDb($sid),
  6164. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  6165. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  6166. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  6167. 'username' => $username !== '' ? $username : null,
  6168. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  6169. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  6170. 'createtime' => date('Y-m-d H:i:s'),
  6171. 'status' => ProcuremenStatus::POD_UNPICKED,
  6172. 'status_name' => '未提交',
  6173. ];
  6174. Db::table('purchase_order_detail')->insert($one);
  6175. $detailId = (int)Db::getLastInsID();
  6176. }
  6177. $mprocUrl = '';
  6178. if ($buildMobileLinks && $detailId > 0) {
  6179. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  6180. }
  6181. $detailLinks[] = [
  6182. 'detail_id' => $detailId,
  6183. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  6184. 'url' => $mprocUrl,
  6185. ];
  6186. }
  6187. return $detailLinks;
  6188. }
  6189. /**
  6190. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  6191. * @return array<string, mixed>
  6192. */
  6193. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  6194. {
  6195. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  6196. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  6197. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  6198. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  6199. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  6200. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  6201. $isMerge = !empty($ctx['is_merge']);
  6202. $contactName = trim((string)($c['username'] ?? ''));
  6203. if ($contactName === '') {
  6204. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  6205. }
  6206. $notifyVars = [
  6207. 'company_name' => $companyName,
  6208. 'contact_name' => $contactName,
  6209. 'phone' => $phone,
  6210. 'email' => $toEmail,
  6211. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  6212. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  6213. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  6214. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  6215. 'deadline' => (string)($ctx['deadline'] ?? ''),
  6216. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  6217. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  6218. 'platform_url' => $platformUrl,
  6219. 'platform_links' => $platformLinksPlain,
  6220. 'platform_links_html' => $platformLinksHtml,
  6221. ];
  6222. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  6223. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  6224. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  6225. return [
  6226. 'company_name' => $companyName,
  6227. 'phone' => $phone,
  6228. 'email' => $toEmail,
  6229. 'sms_content' => $smsContent,
  6230. 'mail_plain' => $mailPlain,
  6231. 'mail_body' => $mailBody,
  6232. 'notify_vars' => $notifyVars,
  6233. 'detail_links' => $detailLinks,
  6234. ];
  6235. }
  6236. /**
  6237. * @param array<string, mixed> $chosen
  6238. * @param array<int, array<string, mixed>> $mergeRows
  6239. * @param array{ccydh:string, pos:array} $bundle
  6240. */
  6241. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  6242. {
  6243. if (!$sendSms && !$sendEmail) {
  6244. return;
  6245. }
  6246. $companyName = trim((string)($chosen['name'] ?? ''));
  6247. $phone = trim((string)($chosen['phone'] ?? ''));
  6248. $toEmail = trim((string)($chosen['email'] ?? ''));
  6249. if ($companyName === '') {
  6250. throw new \Exception('供应商名称无效');
  6251. }
  6252. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  6253. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  6254. }
  6255. if ($sendSms && $phone === '') {
  6256. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  6257. }
  6258. $sids = [];
  6259. foreach ($mergeRows as $mr) {
  6260. if (!is_array($mr)) {
  6261. continue;
  6262. }
  6263. $sid = $this->extractScydgyRowId($mr);
  6264. if ($this->isValidScydgyRowId($sid)) {
  6265. $sids[$sid] = true;
  6266. }
  6267. }
  6268. if ($sids === []) {
  6269. throw new \Exception('未找到工序行,无法发送通知');
  6270. }
  6271. $sysRqNotify = '';
  6272. $pos = $bundle['pos'] ?? [];
  6273. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6274. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  6275. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  6276. $ts = strtotime($sr);
  6277. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  6278. }
  6279. }
  6280. try {
  6281. $detailsQuery = Db::table('purchase_order_detail')
  6282. ->where('scydgy_id', 'in', array_keys($sids))
  6283. ->where('company_name', $companyName);
  6284. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6285. $details = $detailsQuery->order('id', 'asc')->select();
  6286. } catch (\Throwable $e) {
  6287. $details = [];
  6288. }
  6289. if (!is_array($details) || $details === []) {
  6290. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  6291. try {
  6292. $detailsQuery = Db::table('purchase_order_detail')
  6293. ->where('scydgy_id', 'in', array_keys($sids))
  6294. ->where('company_name', $companyName);
  6295. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  6296. $details = $detailsQuery->order('id', 'asc')->select();
  6297. } catch (\Throwable $e) {
  6298. $details = [];
  6299. }
  6300. }
  6301. if (!is_array($details) || $details === []) {
  6302. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  6303. }
  6304. $detailLinks = [];
  6305. foreach ($details as $d) {
  6306. if (!is_array($d)) {
  6307. continue;
  6308. }
  6309. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  6310. if ($detailId <= 0) {
  6311. continue;
  6312. }
  6313. $sid = (int)($d['scydgy_id'] ?? 0);
  6314. $gymc = '';
  6315. foreach ($mergeRows as $mr) {
  6316. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  6317. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6318. break;
  6319. }
  6320. }
  6321. $detailLinks[] = [
  6322. 'detail_id' => $detailId,
  6323. 'cgymc' => $gymc,
  6324. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  6325. ];
  6326. }
  6327. if ($detailLinks === []) {
  6328. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  6329. }
  6330. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  6331. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  6332. $notifyBundle['email_log_scene'] = $emailLogScene;
  6333. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  6334. $poIdLog = 0;
  6335. $pos = $bundle['pos'] ?? [];
  6336. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  6337. $poIdLog = (int)($pos[0]['id'] ?? 0);
  6338. }
  6339. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  6340. if ($sendEmail) {
  6341. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  6342. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  6343. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  6344. }
  6345. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  6346. $mailConfig = $this->loadMailerConfig();
  6347. if (!$this->isProcuremenNotifyDryRun()) {
  6348. if (empty($mailConfig['host'])) {
  6349. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  6350. }
  6351. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  6352. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  6353. }
  6354. }
  6355. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  6356. }
  6357. if ($sendSms) {
  6358. $this->issueSendSupplierSms($notifyBundle);
  6359. }
  6360. }
  6361. /**
  6362. * @param array<int, array<string, mixed>> $quoteGroups
  6363. * @return array<int, array<string, mixed>>
  6364. */
  6365. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  6366. {
  6367. $names = [];
  6368. if (is_string($companiesJson) && $companiesJson !== '') {
  6369. $decoded = json_decode($companiesJson, true);
  6370. if (is_array($decoded)) {
  6371. foreach ($decoded as $nm) {
  6372. $nm = trim((string)$nm);
  6373. if ($nm !== '') {
  6374. $names[] = $nm;
  6375. }
  6376. }
  6377. }
  6378. }
  6379. $names = array_values(array_unique($names));
  6380. if ($names === [] && $selectedCompany !== '') {
  6381. $names = [$selectedCompany];
  6382. }
  6383. if ($names === []) {
  6384. return $quoteGroups;
  6385. }
  6386. $targets = [];
  6387. foreach ($quoteGroups as $g) {
  6388. if (!is_array($g)) {
  6389. continue;
  6390. }
  6391. $cn = trim((string)($g['name'] ?? ''));
  6392. if ($cn !== '' && in_array($cn, $names, true)) {
  6393. $targets[] = $g;
  6394. }
  6395. }
  6396. return $targets;
  6397. }
  6398. /**
  6399. * @return array{pos:array, merge_rows:array, bundle:array}
  6400. */
  6401. protected function loadAuditResendBundle(string $scydgyId): array
  6402. {
  6403. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6404. $pos = $bundle['pos'];
  6405. $mergeRows = $bundle['merge_rows'];
  6406. if ($pos === [] || $mergeRows === []) {
  6407. $this->error('该订单不在待确认供应商状态');
  6408. }
  6409. $sysRqDb = '';
  6410. if (isset($pos[0]) && is_array($pos[0])) {
  6411. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  6412. }
  6413. foreach ($pos as $i => $poRow) {
  6414. if (is_array($pos[$i]) && $sysRqDb !== '') {
  6415. $pos[$i]['sys_rq'] = $sysRqDb;
  6416. }
  6417. }
  6418. $bundle['pos'] = $pos;
  6419. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  6420. }
  6421. /**
  6422. * @param array<int, array<string, mixed>> $targets
  6423. */
  6424. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  6425. {
  6426. if ($targets === []) {
  6427. $this->error('未找到可通知的供应商');
  6428. }
  6429. $notifyErrors = [];
  6430. try {
  6431. $this->notifyDryRunPreview = [];
  6432. foreach ($targets as $g) {
  6433. if (!is_array($g)) {
  6434. continue;
  6435. }
  6436. $cname = trim((string)($g['name'] ?? ''));
  6437. if ($cname === '') {
  6438. continue;
  6439. }
  6440. $chosen = [
  6441. 'name' => $cname,
  6442. 'company_name' => $cname,
  6443. 'email' => trim((string)($g['email'] ?? '')),
  6444. 'phone' => trim((string)($g['phone'] ?? '')),
  6445. 'username' => trim((string)($g['username'] ?? '')),
  6446. ];
  6447. try {
  6448. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  6449. } catch (\Throwable $e) {
  6450. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6451. }
  6452. }
  6453. } catch (\Throwable $e) {
  6454. $this->error('通知发送失败:' . $e->getMessage());
  6455. }
  6456. if ($notifyErrors !== []) {
  6457. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6458. }
  6459. if ($this->isProcuremenNotifyDryRun()) {
  6460. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  6461. 'notify_dry_run' => true,
  6462. 'notify_preview' => $this->notifyDryRunPreview,
  6463. ]);
  6464. }
  6465. $nameLabels = [];
  6466. foreach ($targets as $g) {
  6467. if (!is_array($g)) {
  6468. continue;
  6469. }
  6470. $n = trim((string)($g['name'] ?? ''));
  6471. if ($n !== '') {
  6472. $nameLabels[] = $n;
  6473. }
  6474. }
  6475. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  6476. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  6477. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  6478. $seenLogSid = [];
  6479. foreach ($bundle['pos'] ?? [] as $poRow) {
  6480. if (!is_array($poRow)) {
  6481. continue;
  6482. }
  6483. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6484. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  6485. continue;
  6486. }
  6487. $seenLogSid[$sid] = true;
  6488. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6489. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6490. }
  6491. if ($seenLogSid === []) {
  6492. foreach ($mergeRows as $mr) {
  6493. if (!is_array($mr)) {
  6494. continue;
  6495. }
  6496. $sid = $this->extractScydgyRowId($mr);
  6497. if ($this->isValidScydgyRowId($sid)) {
  6498. $this->addOrderLog($sid, $logAction, $logMsg, null);
  6499. break;
  6500. }
  6501. }
  6502. }
  6503. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  6504. }
  6505. /**
  6506. * 协助下发 — 发送短信(一家供应商)
  6507. *
  6508. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  6509. */
  6510. protected function issueSendSupplierSms(array $bundle): void
  6511. {
  6512. $companyName = (string)($bundle['company_name'] ?? '');
  6513. $phone = (string)($bundle['phone'] ?? '');
  6514. $smsContent = (string)($bundle['sms_content'] ?? '');
  6515. $this->logIssueNotifyDebug('短信', [
  6516. 'company' => $companyName,
  6517. 'phone' => $phone,
  6518. 'sms_content' => $smsContent,
  6519. ]);
  6520. if ($this->isProcuremenNotifyDryRun()) {
  6521. $this->recordNotifyDryRunPreview([
  6522. 'scene' => 'issue_sms',
  6523. 'company_name' => $companyName,
  6524. 'phone' => $phone,
  6525. 'sms_content' => $smsContent,
  6526. ]);
  6527. return;
  6528. }
  6529. $this->smsbao($phone, $smsContent);
  6530. }
  6531. /**
  6532. * 协助下发 — 发送邮件(一家供应商)
  6533. *
  6534. * @param array<string, mixed> $bundle
  6535. * @param array<string, mixed> $mailConfig
  6536. */
  6537. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  6538. {
  6539. $companyName = (string)($bundle['company_name'] ?? '');
  6540. $toEmail = (string)($bundle['email'] ?? '');
  6541. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  6542. $mailBody = (string)($bundle['mail_body'] ?? '');
  6543. $this->logIssueNotifyDebug('邮件', [
  6544. 'company' => $companyName,
  6545. 'email' => $toEmail,
  6546. 'mail_subject' => $mailSubject,
  6547. 'mail_body' => $mailPlain,
  6548. ]);
  6549. if ($this->isProcuremenNotifyDryRun()) {
  6550. $this->recordNotifyDryRunPreview([
  6551. 'scene' => 'issue_email',
  6552. 'company_name' => $companyName,
  6553. 'email' => $toEmail,
  6554. 'mail_subject' => $mailSubject,
  6555. 'mail_body' => $mailPlain,
  6556. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  6557. 'notify_vars' => $bundle['notify_vars'] ?? [],
  6558. 'detail_links' => $bundle['detail_links'] ?? [],
  6559. ]);
  6560. return;
  6561. }
  6562. $mail = new PHPMailer(true);
  6563. $mail->isSMTP();
  6564. $mail->Host = $mailConfig['host'];
  6565. $mail->SMTPAuth = true;
  6566. $mail->Username = $mailConfig['addr'];
  6567. $mail->Password = $mailConfig['pass'];
  6568. $mail->SMTPSecure = $mailConfig['security'];
  6569. $mail->Port = $mailConfig['port'];
  6570. $mail->CharSet = $mailConfig['charset'];
  6571. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  6572. $mail->addAddress($toEmail, $companyName);
  6573. $mail->isHTML(true);
  6574. $mail->Subject = $mailSubject;
  6575. $mail->Body = $mailBody;
  6576. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  6577. $sendOk = true;
  6578. $failReason = '';
  6579. try {
  6580. $mail->send();
  6581. } catch (\Throwable $e) {
  6582. $sendOk = false;
  6583. $failReason = $e->getMessage();
  6584. $this->persistEmailSendLog([
  6585. 'from_email' => $fromEmail,
  6586. 'to_email' => $toEmail,
  6587. 'send_time' => date('Y-m-d H:i:s'),
  6588. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6589. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6590. 'company_name' => $companyName,
  6591. 'mail_subject' => $mailSubject,
  6592. 'status' => 0,
  6593. 'fail_reason' => $failReason,
  6594. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6595. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6596. ]);
  6597. throw $e;
  6598. }
  6599. $this->persistEmailSendLog([
  6600. 'from_email' => $fromEmail,
  6601. 'to_email' => $toEmail,
  6602. 'send_time' => date('Y-m-d H:i:s'),
  6603. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6604. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6605. 'company_name' => $companyName,
  6606. 'mail_subject' => $mailSubject,
  6607. 'status' => 1,
  6608. 'fail_reason' => '',
  6609. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6610. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6611. ]);
  6612. }
  6613. /**
  6614. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  6615. *
  6616. * @param array<int, array<string, mixed>> $mergeRows
  6617. * @return array<string, mixed>
  6618. */
  6619. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  6620. {
  6621. $head = $mergeRows[0] ?? [];
  6622. $isMerge = count($mergeRows) > 1;
  6623. return [
  6624. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  6625. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  6626. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  6627. 'is_merge' => $isMerge,
  6628. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  6629. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  6630. 'deadline' => $sysRqNotify,
  6631. ];
  6632. }
  6633. /**
  6634. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  6635. *
  6636. * @param array<string, mixed> $data
  6637. */
  6638. protected function logIssueNotifyDebug(string $type, array $data): void
  6639. {
  6640. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  6641. return;
  6642. }
  6643. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6644. }
  6645. protected function ensurePurchaseEmailSendLogTableOnce(): void
  6646. {
  6647. try {
  6648. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  6649. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6650. return;
  6651. } catch (\Throwable $e) {
  6652. }
  6653. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  6654. if (is_file($sqlFile)) {
  6655. $sql = file_get_contents($sqlFile);
  6656. if (is_string($sql) && $sql !== '') {
  6657. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  6658. $stmt = trim($stmt);
  6659. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  6660. continue;
  6661. }
  6662. try {
  6663. Db::execute($stmt);
  6664. } catch (\Throwable $ignore) {
  6665. }
  6666. }
  6667. }
  6668. }
  6669. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6670. }
  6671. /**
  6672. * @param array<string, mixed> $row
  6673. */
  6674. protected function persistEmailSendLog(array $row): void
  6675. {
  6676. try {
  6677. $this->ensurePurchaseEmailSendLogTableOnce();
  6678. } catch (\Throwable $e) {
  6679. return;
  6680. }
  6681. list($adminId, $adminName) = $this->GetUseName();
  6682. $cut = function ($s, $max) {
  6683. $s = (string)$s;
  6684. if (function_exists('mb_substr')) {
  6685. return mb_substr($s, 0, $max, 'UTF-8');
  6686. }
  6687. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6688. };
  6689. $data = [
  6690. 'from_email' => $cut($row['from_email'] ?? '', 128),
  6691. 'to_email' => $cut($row['to_email'] ?? '', 128),
  6692. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  6693. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  6694. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  6695. 'company_name' => $cut($row['company_name'] ?? '', 128),
  6696. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6697. 'status' => !empty($row['status']) ? 1 : 0,
  6698. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6699. 'admin_id' => (int)$adminId,
  6700. 'admin_name' => $cut($adminName, 64),
  6701. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6702. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6703. 'createtime' => date('Y-m-d H:i:s'),
  6704. ];
  6705. try {
  6706. Db::table('purchase_email_send_log')->insert($data);
  6707. } catch (\Throwable $e) {
  6708. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6709. }
  6710. }
  6711. protected function formatEmailLogSceneText(string $scene): string
  6712. {
  6713. $map = [
  6714. 'pick_issue' => '初选下发',
  6715. 'audit_resend' => '确认页重发',
  6716. ];
  6717. return $map[$scene] ?? $scene;
  6718. }
  6719. /**
  6720. * 邮件发送日志列表
  6721. */
  6722. public function emailLog()
  6723. {
  6724. $this->relationSearch = false;
  6725. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6726. $this->request->filter(['strip_tags', 'trim']);
  6727. $bakModel = $this->model;
  6728. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6729. if ($this->request->isAjax()) {
  6730. $this->ensurePurchaseEmailSendLogTableOnce();
  6731. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6732. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6733. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6734. $list = $this->model
  6735. ->where($where)
  6736. ->order($sortField, $orderDir)
  6737. ->paginate($limit);
  6738. $rows = [];
  6739. foreach ($list->items() as $item) {
  6740. $row = is_array($item) ? $item : $item->toArray();
  6741. $scene = trim((string)($row['scene'] ?? ''));
  6742. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6743. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6744. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6745. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6746. $rows[] = $row;
  6747. }
  6748. $this->model = $bakModel;
  6749. return json(['total' => $list->total(), 'rows' => $rows]);
  6750. }
  6751. $this->model = $bakModel;
  6752. return $this->view->fetch('procuremen/emaillog');
  6753. }
  6754. /**
  6755. * 协助下发弹窗(选多家供应商并通知)
  6756. */
  6757. public function pickReview()
  6758. {
  6759. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6760. $this->error(__('You have no permission'));
  6761. }
  6762. if ($this->request->isPost()) {
  6763. $this->error('请使用弹窗内「确认下发」提交');
  6764. }
  6765. $this->view->assign('pickMode', 1);
  6766. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  6767. }
  6768. /**
  6769. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6770. */
  6771. public function add()
  6772. {
  6773. if ($this->request->isPost()) {
  6774. $params = $this->request->post('row/a');
  6775. if (!is_array($params)) {
  6776. $this->error(__('Parameter %s can not be empty', ''));
  6777. }
  6778. [, $adminName] = $this->GetUseName();
  6779. $params['cywyxm'] = $adminName;
  6780. try {
  6781. $sid = $this->saveManualPickOrder($params);
  6782. } catch (\InvalidArgumentException $e) {
  6783. $this->error($e->getMessage());
  6784. } catch (\Throwable $e) {
  6785. $this->error($e->getMessage());
  6786. }
  6787. $this->success('新增成功', '', [
  6788. 'scydgy_id' => $sid,
  6789. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  6790. ]);
  6791. }
  6792. [, $adminName] = $this->GetUseName();
  6793. $this->view->assign('adminNickname', $adminName);
  6794. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6795. $this->view->assign('defaultCclbmmc', '营销中心');
  6796. return $this->view->fetch();
  6797. }
  6798. /**
  6799. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6800. */
  6801. public function rfqlist()
  6802. {
  6803. $this->relationSearch = false;
  6804. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6805. $this->request->filter(['strip_tags', 'trim']);
  6806. if ($this->request->isAjax()) {
  6807. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6808. $limit = max(10, min(500, (int)$limit));
  6809. $applyFilters = function ($query) use ($where) {
  6810. $query->where('scydgy_id', '<', 0);
  6811. $query->whereRaw(
  6812. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6813. );
  6814. if (!$this->auth->isSuperAdmin()) {
  6815. [, $adminName] = $this->GetUseName();
  6816. $query->where('cywyxm', $adminName);
  6817. }
  6818. if (!empty($where)) {
  6819. $query->where($where);
  6820. }
  6821. };
  6822. $countQuery = Db::table('purchase_order');
  6823. $applyFilters($countQuery);
  6824. $total = (int)$countQuery->count();
  6825. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6826. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6827. $listQuery = Db::table('purchase_order');
  6828. $applyFilters($listQuery);
  6829. $rows = $listQuery
  6830. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6831. ->order($sortField, $orderDir)
  6832. ->limit($offset, $limit)
  6833. ->select();
  6834. if (!is_array($rows)) {
  6835. $rows = [];
  6836. }
  6837. $out = [];
  6838. foreach ($rows as $r) {
  6839. if (!is_array($r)) {
  6840. continue;
  6841. }
  6842. $sid = (int)($r['scydgy_id'] ?? 0);
  6843. if ($sid >= 0) {
  6844. continue;
  6845. }
  6846. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6847. if ($createdText === '') {
  6848. $createdText = trim((string)($r['dStamp'] ?? ''));
  6849. }
  6850. $out[] = [
  6851. 'id' => (int)($r['id'] ?? 0),
  6852. 'scydgy_id' => $sid,
  6853. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6854. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6855. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6856. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6857. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6858. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6859. 'createtime' => $r['createtime'] ?? null,
  6860. 'createtime_text' => $createdText,
  6861. ];
  6862. }
  6863. return json(['total' => $total, 'rows' => $out]);
  6864. }
  6865. [, $adminName] = $this->GetUseName();
  6866. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6867. $this->view->assign('adminNickname', $adminName);
  6868. return $this->view->fetch('procuremen/rfqlist');
  6869. }
  6870. /**
  6871. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6872. */
  6873. public function rfqlistDetails()
  6874. {
  6875. return $this->details();
  6876. }
  6877. /**
  6878. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6879. */
  6880. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6881. {
  6882. if ($scydgyId >= 0) {
  6883. return;
  6884. }
  6885. try {
  6886. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6887. } catch (\Throwable $e) {
  6888. $po = null;
  6889. }
  6890. if (!is_array($po)) {
  6891. $this->error('订单不存在');
  6892. }
  6893. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6894. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6895. $this->error('订单不存在');
  6896. }
  6897. if ($this->auth->isSuperAdmin()) {
  6898. return;
  6899. }
  6900. [, $adminName] = $this->GetUseName();
  6901. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6902. if ($cywy !== '' && $cywy === $adminName) {
  6903. return;
  6904. }
  6905. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6906. try {
  6907. if ($this->auth->check($rule)) {
  6908. return;
  6909. }
  6910. } catch (\Throwable $e) {
  6911. }
  6912. }
  6913. $this->error('无权查看该订单');
  6914. }
  6915. /**
  6916. * 手工新增协助工序进度文案
  6917. */
  6918. protected function formatProcuremenRfqProgressText(array $row): string
  6919. {
  6920. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6921. return ProcuremenStatus::PO_COMPLETED;
  6922. }
  6923. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6924. return '待采购确认';
  6925. }
  6926. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6927. return '待确认供应商';
  6928. }
  6929. $sid = (int)($row['scydgy_id'] ?? 0);
  6930. if ($sid < 0) {
  6931. try {
  6932. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6933. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6934. $detCnt = (int)$detCntQuery->count();
  6935. if ($detCnt > 0) {
  6936. return '已下发待确认';
  6937. }
  6938. } catch (\Throwable $e) {
  6939. }
  6940. }
  6941. return '待协助下发';
  6942. }
  6943. /**
  6944. * 协助初选列表 — 批量软删除
  6945. */
  6946. public function pickDelete()
  6947. {
  6948. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6949. $this->error(__('Invalid parameters'));
  6950. }
  6951. if (!$this->procuremenCanPickDelete()) {
  6952. $this->error(__('You have no permission'));
  6953. }
  6954. $rowsRaw = $this->request->post('rows_json', '[]');
  6955. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6956. if (!is_array($rows) || $rows === []) {
  6957. $this->error('请至少勾选一条工序');
  6958. }
  6959. $done = 0;
  6960. Db::startTrans();
  6961. try {
  6962. foreach ($rows as $row) {
  6963. if (!is_array($row)) {
  6964. continue;
  6965. }
  6966. $this->softDeleteProcuremenPickRow($row);
  6967. $done++;
  6968. }
  6969. if ($done < 1) {
  6970. throw new \Exception('没有可删除的工序');
  6971. }
  6972. Db::commit();
  6973. } catch (\InvalidArgumentException $e) {
  6974. Db::rollback();
  6975. $this->error($e->getMessage());
  6976. } catch (\Throwable $e) {
  6977. Db::rollback();
  6978. $this->error($e->getMessage());
  6979. }
  6980. $this->pickHiddenScydgySetCache = null;
  6981. $this->success('已删除 ' . $done . ' 条工序');
  6982. }
  6983. /**
  6984. * 下发 — 手工新增工序(弹窗)
  6985. */
  6986. public function pickAdd()
  6987. {
  6988. if ($this->request->isPost()) {
  6989. $params = $this->request->post('row/a');
  6990. if (!is_array($params)) {
  6991. $this->error(__('Parameter %s can not be empty', ''));
  6992. }
  6993. try {
  6994. $sid = $this->saveManualPickOrder($params);
  6995. } catch (\InvalidArgumentException $e) {
  6996. $this->error($e->getMessage());
  6997. } catch (\Throwable $e) {
  6998. $this->error($e->getMessage());
  6999. }
  7000. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  7001. }
  7002. return $this->view->fetch('procuremen/pick_add');
  7003. }
  7004. /**
  7005. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  7006. */
  7007. public function pickSubmit()
  7008. {
  7009. if (!$this->request->isPost()) {
  7010. $this->error(__('Invalid parameters'));
  7011. }
  7012. // ---------- 接口订单数据 ----------
  7013. $rowJson = $this->request->post('row_json', '');
  7014. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  7015. $companiesJson = $this->request->post('companies_json', '[]');
  7016. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  7017. $companies = json_decode($companiesJson, true);
  7018. if (!is_array($companies)) {
  7019. $this->error('供应商数据无效');
  7020. }
  7021. $issueCompanies = $this->normalizePickCompanies($companies);
  7022. if ($issueCompanies === []) {
  7023. $this->error('请至少选择一家合作供应商');
  7024. }
  7025. $issueNameLabels = [];
  7026. foreach ($issueCompanies as $pc) {
  7027. $issueNameLabels[] = $pc['name'];
  7028. }
  7029. $issueNamesSummary = implode('、', $issueNameLabels);
  7030. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  7031. if ($sysRq === '') {
  7032. $this->error('请选择招标截止日期');
  7033. }
  7034. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  7035. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  7036. (string)$this->request->post('delivery_deadline', ''),
  7037. true
  7038. );
  7039. $isMerge = count($mergeRows) > 1;
  7040. $ccydhLog = '';
  7041. foreach ($mergeRows as $row) {
  7042. if (!is_array($row)) {
  7043. continue;
  7044. }
  7045. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  7046. if ($ccydhLog !== '') {
  7047. break;
  7048. }
  7049. }
  7050. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  7051. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  7052. $logMsg = '下发' . $orderPart . $procPart
  7053. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  7054. $issueTime = date('Y-m-d H:i:s');
  7055. $logSidList = [];
  7056. foreach ($mergeRows as $row) {
  7057. if (!is_array($row)) {
  7058. continue;
  7059. }
  7060. $sid = $this->extractScydgyRowId($row);
  7061. if ($this->isValidScydgyRowId($sid)) {
  7062. $logSidList[$sid] = true;
  7063. }
  7064. }
  7065. $existingBySid = [];
  7066. if ($logSidList !== []) {
  7067. try {
  7068. $existingRows = Db::table('purchase_order')
  7069. ->where('scydgy_id', 'in', array_keys($logSidList))
  7070. ->select();
  7071. if (is_array($existingRows)) {
  7072. foreach ($existingRows as $poRow) {
  7073. if (!is_array($poRow)) {
  7074. continue;
  7075. }
  7076. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7077. if ($this->isValidScydgyRowId($sid)) {
  7078. $existingBySid[$sid] = $poRow;
  7079. }
  7080. }
  7081. }
  7082. } catch (\Throwable $e) {
  7083. $existingBySid = [];
  7084. }
  7085. }
  7086. Db::startTrans();
  7087. try {
  7088. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  7089. foreach ($mergeRows as $row) {
  7090. if (!is_array($row)) {
  7091. continue;
  7092. }
  7093. $sid = $this->extractScydgyRowId($row);
  7094. $this->upsertPurchaseOrderFromRow(
  7095. $row,
  7096. $sysRqDb,
  7097. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7098. $issueTime,
  7099. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  7100. $deliveryDeadlineDb
  7101. );
  7102. }
  7103. foreach ($issueCompanies as $c) {
  7104. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  7105. }
  7106. Db::commit();
  7107. } catch (\Throwable $e) {
  7108. Db::rollback();
  7109. $this->error($e->getMessage());
  7110. }
  7111. $poIdBySid = [];
  7112. if ($logSidList !== []) {
  7113. try {
  7114. $poIdBySid = Db::table('purchase_order')
  7115. ->where('scydgy_id', 'in', array_keys($logSidList))
  7116. ->column('id', 'scydgy_id');
  7117. } catch (\Throwable $e) {
  7118. $poIdBySid = [];
  7119. }
  7120. }
  7121. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  7122. if ($logSidList !== []) {
  7123. list($adminId, $adminName) = $this->GetUseName();
  7124. $logRows = [];
  7125. $seenLogSid = [];
  7126. foreach ($mergeRows as $row) {
  7127. if (!is_array($row)) {
  7128. continue;
  7129. }
  7130. $ids = $this->extractScydgyRowId($row);
  7131. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  7132. continue;
  7133. }
  7134. $seenLogSid[$ids] = true;
  7135. $poIdLog = null;
  7136. if (isset($poIdBySid[$ids])) {
  7137. $tid = (int)$poIdBySid[$ids];
  7138. $poIdLog = $tid > 0 ? $tid : null;
  7139. }
  7140. $logRows[] = ProcuremenOperLog::buildInsertRow(
  7141. $ids,
  7142. 'issue_submit',
  7143. $logMsg,
  7144. $poIdLog,
  7145. (int)$adminId,
  7146. (string)$adminName
  7147. );
  7148. }
  7149. if ($logRows !== []) {
  7150. try {
  7151. Db::table('purchase_order_oper_log')->insertAll($logRows);
  7152. } catch (\Throwable $e) {
  7153. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  7154. }
  7155. }
  7156. }
  7157. $notifyErrors = [];
  7158. $posNotify = [];
  7159. if ($logSidList !== []) {
  7160. try {
  7161. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  7162. } catch (\Throwable $e) {
  7163. $posNotify = [];
  7164. }
  7165. }
  7166. if (!is_array($posNotify)) {
  7167. $posNotify = [];
  7168. }
  7169. foreach ($posNotify as $i => $prow) {
  7170. if (is_array($posNotify[$i])) {
  7171. $posNotify[$i]['sys_rq'] = $sysRqDb;
  7172. }
  7173. }
  7174. $ccydhPick = '';
  7175. foreach ($mergeRows as $row) {
  7176. if (!is_array($row)) {
  7177. continue;
  7178. }
  7179. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  7180. if ($ccydhPick !== '') {
  7181. break;
  7182. }
  7183. }
  7184. $notifyBundleBase = [
  7185. 'ccydh' => $ccydhPick,
  7186. 'pos' => $posNotify,
  7187. 'merge_rows' => $mergeRows,
  7188. ];
  7189. try {
  7190. $this->notifyDryRunPreview = [];
  7191. foreach ($issueCompanies as $c) {
  7192. if (!is_array($c)) {
  7193. continue;
  7194. }
  7195. $cname = trim((string)($c['name'] ?? ''));
  7196. if ($cname === '') {
  7197. continue;
  7198. }
  7199. try {
  7200. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  7201. } catch (\Throwable $e) {
  7202. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7203. }
  7204. }
  7205. } catch (\Throwable $e) {
  7206. $this->error('通知发送失败:' . $e->getMessage());
  7207. }
  7208. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  7209. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7210. }
  7211. if ($this->isProcuremenNotifyDryRun()) {
  7212. $this->success('【演练模式】已保存并生成通知预览', '', [
  7213. 'notify_dry_run' => true,
  7214. 'notify_preview' => $this->notifyDryRunPreview,
  7215. ]);
  7216. }
  7217. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  7218. }
  7219. /**
  7220. * 确认供应商弹窗
  7221. */
  7222. public function auditIssue()
  7223. {
  7224. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7225. if (is_array($ids)) {
  7226. $ids = isset($ids[0]) ? $ids[0] : '';
  7227. }
  7228. $ids = trim((string)$ids);
  7229. if ($ids === '') {
  7230. $this->error(__('Invalid parameters'));
  7231. }
  7232. if ($this->request->isPost()) {
  7233. $this->error('请使用弹窗内「确认」提交');
  7234. }
  7235. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7236. $pos = $bundle['pos'];
  7237. if ($pos === []) {
  7238. $this->error('该订单不在待确认供应商状态');
  7239. }
  7240. $po = $pos[0];
  7241. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7242. if ($quoteGroups === []) {
  7243. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  7244. }
  7245. $pickedName = '';
  7246. foreach ($pos as $poRow) {
  7247. if (!is_array($poRow)) {
  7248. continue;
  7249. }
  7250. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7251. if ($pn !== '') {
  7252. $pickedName = $pn;
  7253. break;
  7254. }
  7255. }
  7256. $this->view->assign('po', $po);
  7257. $this->view->assign('scydgyId', $ids);
  7258. $this->view->assign('orderCcydh', $bundle['ccydh']);
  7259. $mergeRows = $bundle['merge_rows'];
  7260. $this->view->assign('processRows', $mergeRows);
  7261. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  7262. $this->view->assign('processCount', count($mergeRows));
  7263. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  7264. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  7265. $this->view->assign('pickedCompanyName', $pickedName);
  7266. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7267. if ($sysRqForView === '') {
  7268. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7269. }
  7270. $this->view->assign('sysRq', $sysRqForView);
  7271. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  7272. if ($deliveryDeadlineForView === '') {
  7273. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7274. }
  7275. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7276. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  7277. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups));
  7278. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups) ? 1 : 0);
  7279. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  7280. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  7281. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  7282. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  7283. return $this->view->fetch('procuremen/audit_issue');
  7284. }
  7285. /**
  7286. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  7287. *
  7288. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7289. */
  7290. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  7291. {
  7292. return !$this->isProcuremenBidOpenVerifiedForBundle($bundle);
  7293. }
  7294. /**
  7295. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  7296. *
  7297. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  7298. */
  7299. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  7300. {
  7301. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7302. return false;
  7303. }
  7304. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  7305. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  7306. return true;
  7307. }
  7308. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  7309. }
  7310. /**
  7311. * 确认页 — 补加供应商弹窗
  7312. */
  7313. public function auditAppend()
  7314. {
  7315. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  7316. $this->error(__('You have no permission'));
  7317. }
  7318. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  7319. if (is_array($ids)) {
  7320. $ids = isset($ids[0]) ? $ids[0] : '';
  7321. }
  7322. $ids = trim((string)$ids);
  7323. if ($ids === '') {
  7324. $this->error(__('Invalid parameters'));
  7325. }
  7326. if ($this->request->isPost()) {
  7327. $this->error('请使用弹窗内「确认」提交');
  7328. }
  7329. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7330. if (($bundle['pos'] ?? []) === []) {
  7331. $this->error('该订单不在待确认供应商状态');
  7332. }
  7333. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7334. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7335. $this->error('已开标验证,不能再补加供应商');
  7336. }
  7337. $this->error('已经超过了招标截止日期,不可操作');
  7338. }
  7339. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7340. $existingNames = [];
  7341. foreach ($quoteGroups as $g) {
  7342. if (!is_array($g)) {
  7343. continue;
  7344. }
  7345. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  7346. if ($n !== '') {
  7347. $existingNames[$n] = true;
  7348. }
  7349. }
  7350. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  7351. $mergeRows = $bundle['merge_rows'] ?? [];
  7352. $this->view->assign('scydgyId', $ids);
  7353. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  7354. $this->view->assign('po', $po);
  7355. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  7356. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  7357. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  7358. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  7359. if ($sysRqForView === '') {
  7360. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7361. }
  7362. $this->view->assign('sysRq', $sysRqForView);
  7363. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7364. if ($deliveryDeadlineForView === '') {
  7365. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  7366. }
  7367. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  7368. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  7369. }
  7370. /**
  7371. * 确认页 — 补加供应商提交
  7372. */
  7373. public function auditAppendSubmit()
  7374. {
  7375. if (!$this->request->isPost()) {
  7376. $this->error(__('Invalid parameters'));
  7377. }
  7378. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  7379. $this->error(__('You have no permission'));
  7380. }
  7381. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  7382. if ($ids === '') {
  7383. $this->error(__('Invalid parameters'));
  7384. }
  7385. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  7386. if (($bundle['pos'] ?? []) === []) {
  7387. $this->error('该订单不在待确认供应商状态');
  7388. }
  7389. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  7390. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7391. $this->error('已开标验证,不能再补加供应商');
  7392. }
  7393. $this->error('已经超过了招标截止日期,不可操作');
  7394. }
  7395. $companiesJson = $this->request->post('companies_json', '[]');
  7396. $companies = json_decode((string)$companiesJson, true);
  7397. if (!is_array($companies)) {
  7398. $this->error('供应商数据无效');
  7399. }
  7400. $issueCompanies = $this->normalizePickCompanies($companies);
  7401. if ($issueCompanies === []) {
  7402. $this->error('请至少选择一家合作供应商');
  7403. }
  7404. $mergeRows = $bundle['merge_rows'] ?? [];
  7405. if (!is_array($mergeRows) || $mergeRows === []) {
  7406. $this->error('未找到工序行,无法补加');
  7407. }
  7408. $existingNames = [];
  7409. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  7410. if (!is_array($g)) {
  7411. continue;
  7412. }
  7413. $n = trim((string)($g['company_name'] ?? ''));
  7414. if ($n !== '') {
  7415. $existingNames[$n] = true;
  7416. }
  7417. }
  7418. $toAdd = [];
  7419. foreach ($issueCompanies as $c) {
  7420. if (!is_array($c)) {
  7421. continue;
  7422. }
  7423. $n = trim((string)($c['name'] ?? ''));
  7424. if ($n === '' || isset($existingNames[$n])) {
  7425. continue;
  7426. }
  7427. $toAdd[] = $c;
  7428. }
  7429. if ($toAdd === []) {
  7430. $this->error('所选供应商均已在本单中,请选择新的供应商');
  7431. }
  7432. $addedNames = [];
  7433. Db::startTrans();
  7434. try {
  7435. foreach ($toAdd as $c) {
  7436. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  7437. $addedNames[] = trim((string)($c['name'] ?? ''));
  7438. }
  7439. Db::commit();
  7440. } catch (\Throwable $e) {
  7441. Db::rollback();
  7442. $this->error($e->getMessage());
  7443. }
  7444. $notifyErrors = [];
  7445. $notifyBundleBase = [
  7446. 'ccydh' => $bundle['ccydh'] ?? '',
  7447. 'pos' => $bundle['pos'] ?? [],
  7448. 'merge_rows' => $mergeRows,
  7449. ];
  7450. foreach ($toAdd as $c) {
  7451. if (!is_array($c)) {
  7452. continue;
  7453. }
  7454. $cname = trim((string)($c['name'] ?? ''));
  7455. if ($cname === '') {
  7456. continue;
  7457. }
  7458. try {
  7459. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  7460. } catch (\Throwable $e) {
  7461. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7462. }
  7463. }
  7464. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  7465. $seenLogSid = [];
  7466. foreach ($bundle['pos'] ?? [] as $poRow) {
  7467. if (!is_array($poRow)) {
  7468. continue;
  7469. }
  7470. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7471. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7472. continue;
  7473. }
  7474. $seenLogSid[$sid] = true;
  7475. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7476. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7477. }
  7478. if ($seenLogSid === []) {
  7479. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  7480. if ($this->isValidScydgyRowId($logSid)) {
  7481. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  7482. }
  7483. }
  7484. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  7485. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  7486. }
  7487. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  7488. }
  7489. /**
  7490. * 开标双重验证 — 可选验证人列表
  7491. */
  7492. public function bidOpenUsers()
  7493. {
  7494. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7495. $this->error('无权限');
  7496. }
  7497. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  7498. if ($scydgyId !== '') {
  7499. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7500. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7501. $this->success('已完成开标验证', null, [
  7502. 'verified' => 1,
  7503. 'users' => [],
  7504. ]);
  7505. }
  7506. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7507. }
  7508. $this->success('', null, [
  7509. 'verified' => 0,
  7510. 'users' => $this->listBidOpenVerifierCandidates(),
  7511. ]);
  7512. }
  7513. /**
  7514. * 开标双重验证 — 向指定管理员发送短信验证码
  7515. */
  7516. public function bidOpenSendCode()
  7517. {
  7518. if (!$this->request->isPost()) {
  7519. $this->error(__('Invalid parameters'));
  7520. }
  7521. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7522. $this->error('无权限');
  7523. }
  7524. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7525. $adminId = (int)$this->request->post('admin_id', 0);
  7526. if ($scydgyId === '' || $adminId <= 0) {
  7527. $this->error('参数无效');
  7528. }
  7529. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7530. if ($bundle['pos'] === []) {
  7531. $this->error('该订单不在待确认供应商状态');
  7532. }
  7533. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7534. $this->success('已完成开标验证,无需重复发送');
  7535. }
  7536. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7537. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7538. if ($ccydh === '') {
  7539. $this->error('订单号无效');
  7540. }
  7541. $admin = $this->loadBidOpenAdminUser($adminId);
  7542. if ($admin === null) {
  7543. $this->error('验证人无效或未绑定手机号');
  7544. }
  7545. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  7546. $cd = max(30, min(120, $cd));
  7547. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  7548. $this->error('发送过于频繁,请稍后再试');
  7549. }
  7550. $code = (string)random_int(100000, 999999);
  7551. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  7552. $ttl = max(60, min(600, $ttl));
  7553. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  7554. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  7555. try {
  7556. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  7557. } catch (\Throwable $e) {
  7558. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  7559. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  7560. $this->error($e->getMessage());
  7561. }
  7562. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  7563. }
  7564. /**
  7565. * 开标双重验证 — 两人验证码校验并记录
  7566. */
  7567. public function bidOpenVerify()
  7568. {
  7569. if (!$this->request->isPost()) {
  7570. $this->error(__('Invalid parameters'));
  7571. }
  7572. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  7573. $this->error('无权限');
  7574. }
  7575. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7576. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  7577. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  7578. $code1 = trim((string)$this->request->post('code1', ''));
  7579. $code2 = trim((string)$this->request->post('code2', ''));
  7580. if ($scydgyId === '') {
  7581. $this->error('参数无效');
  7582. }
  7583. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  7584. $this->error('请选择两位验证人');
  7585. }
  7586. if ($verifier1Id === $verifier2Id) {
  7587. $this->error('两位验证人不能相同');
  7588. }
  7589. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  7590. $this->error('请输入6位短信验证码');
  7591. }
  7592. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7593. if ($bundle['pos'] === []) {
  7594. $this->error('该订单不在待确认供应商状态');
  7595. }
  7596. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7597. if ($ccydh === '') {
  7598. $this->error('订单号无效');
  7599. }
  7600. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7601. $this->success('已完成开标验证');
  7602. }
  7603. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  7604. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  7605. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  7606. if ($verifier1 === null || $verifier2 === null) {
  7607. $this->error('验证人无效或未绑定手机号');
  7608. }
  7609. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  7610. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  7611. }
  7612. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  7613. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  7614. }
  7615. try {
  7616. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  7617. } catch (\Throwable $e) {
  7618. $this->error($e->getMessage());
  7619. }
  7620. $this->success('开标验证成功,可查看供应商报价与交货日期');
  7621. }
  7622. /**
  7623. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  7624. */
  7625. public function auditSubmit()
  7626. {
  7627. if (!$this->request->isPost()) {
  7628. $this->error(__('Invalid parameters'));
  7629. }
  7630. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7631. if ($scydgyId === '') {
  7632. $this->error('参数无效');
  7633. }
  7634. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7635. $pos = $bundle['pos'];
  7636. $mergeRows = $bundle['merge_rows'];
  7637. if ($pos === [] || $mergeRows === []) {
  7638. $this->error('该订单不在待确认供应商状态');
  7639. }
  7640. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7641. if ($quoteGroups === []) {
  7642. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  7643. }
  7644. $companyName = trim((string)$this->request->post('selected_company', ''));
  7645. if ($companyName === '') {
  7646. $this->error('请选择一家供应商');
  7647. }
  7648. $matched = null;
  7649. foreach ($quoteGroups as $g) {
  7650. if (!is_array($g)) {
  7651. continue;
  7652. }
  7653. if (trim((string)($g['name'] ?? '')) === $companyName) {
  7654. $matched = $g;
  7655. break;
  7656. }
  7657. }
  7658. if ($matched === null) {
  7659. $this->error('所选供应商不在本单报价列表中');
  7660. }
  7661. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  7662. if ($sysRqDb === '') {
  7663. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  7664. } else {
  7665. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  7666. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  7667. }
  7668. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  7669. $this->error('未到招标截止日期,暂不可确认');
  7670. }
  7671. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  7672. $this->error('请先完成开标双重验证后再确认供应商');
  7673. }
  7674. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7675. $procCnt = count($mergeRows);
  7676. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  7677. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  7678. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  7679. Db::startTrans();
  7680. try {
  7681. foreach ($pos as $poRow) {
  7682. if (!is_array($poRow)) {
  7683. continue;
  7684. }
  7685. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7686. if (!$this->isValidScydgyRowId($sid)) {
  7687. continue;
  7688. }
  7689. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7690. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  7691. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7692. 'pick_company_name' => $companyName,
  7693. 'sys_rq' => $sysRqDb,
  7694. ]);
  7695. }
  7696. Db::commit();
  7697. } catch (\Throwable $e) {
  7698. Db::rollback();
  7699. $this->error($e->getMessage());
  7700. }
  7701. foreach ($pos as $poRow) {
  7702. if (!is_array($poRow)) {
  7703. continue;
  7704. }
  7705. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7706. if (!$this->isValidScydgyRowId($sid)) {
  7707. continue;
  7708. }
  7709. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7710. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7711. }
  7712. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  7713. }
  7714. /**
  7715. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  7716. */
  7717. public function auditResendSms()
  7718. {
  7719. if (!$this->request->isPost()) {
  7720. $this->error(__('Invalid parameters'));
  7721. }
  7722. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7723. if ($scydgyId === '') {
  7724. $this->error('参数无效');
  7725. }
  7726. $loaded = $this->loadAuditResendBundle($scydgyId);
  7727. $mergeRows = $loaded['merge_rows'];
  7728. $bundle = $loaded['bundle'];
  7729. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7730. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7731. if ($quoteGroups === []) {
  7732. $this->error('暂无可通知的供应商');
  7733. }
  7734. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7735. $companiesJson = (string)$this->request->post('companies_json', '');
  7736. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7737. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  7738. }
  7739. /**
  7740. * 确认供应商 — 二次发送邮件(可选单家/批量)
  7741. */
  7742. public function auditResendEmail()
  7743. {
  7744. if (!$this->request->isPost()) {
  7745. $this->error(__('Invalid parameters'));
  7746. }
  7747. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7748. if ($scydgyId === '') {
  7749. $this->error('参数无效');
  7750. }
  7751. $loaded = $this->loadAuditResendBundle($scydgyId);
  7752. $mergeRows = $loaded['merge_rows'];
  7753. $bundle = $loaded['bundle'];
  7754. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7755. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7756. if ($quoteGroups === []) {
  7757. $this->error('暂无可通知的供应商');
  7758. }
  7759. $companiesJson = (string)$this->request->post('companies_json', '');
  7760. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7761. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7762. if ($companiesJson === '' && $selectedCompany === '') {
  7763. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  7764. }
  7765. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  7766. }
  7767. /**
  7768. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  7769. *
  7770. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  7771. * @return array<int, true> 已处理的 scydgy_id 集合
  7772. */
  7773. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  7774. {
  7775. $pos = $bundle['pos'] ?? [];
  7776. if (!is_array($pos) || $pos === []) {
  7777. return [];
  7778. }
  7779. $sids = [];
  7780. foreach ($pos as $poRow) {
  7781. if (!is_array($poRow)) {
  7782. continue;
  7783. }
  7784. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7785. if ($this->isValidScydgyRowId($sid)) {
  7786. $sids[$sid] = true;
  7787. }
  7788. }
  7789. if ($sids === []) {
  7790. return [];
  7791. }
  7792. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7793. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  7794. $suffix = trim((string)$logSuffix, ',, ');
  7795. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  7796. $logMsg .= ':从历史存证退回协助初选';
  7797. } else {
  7798. $logMsg .= ':退回协助初选';
  7799. }
  7800. Db::table('purchase_order')
  7801. ->where('scydgy_id', 'in', array_keys($sids))
  7802. ->update([
  7803. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  7804. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7805. 'pick_company_name' => '',
  7806. 'pick_time' => null,
  7807. 'sys_rq' => null,
  7808. 'mod_rq' => null,
  7809. ]);
  7810. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  7811. foreach (array_keys($sids) as $sid) {
  7812. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  7813. }
  7814. return $sids;
  7815. }
  7816. /**
  7817. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  7818. *
  7819. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  7820. */
  7821. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  7822. {
  7823. $scydgyId = trim($scydgyId);
  7824. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7825. if ($scydgyId === '') {
  7826. return $empty;
  7827. }
  7828. try {
  7829. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7830. } catch (\Throwable $e) {
  7831. $anchor = null;
  7832. }
  7833. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  7834. return $empty;
  7835. }
  7836. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7837. if ($ccydh === '') {
  7838. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  7839. }
  7840. try {
  7841. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7842. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7843. $pos = $query->order('scydgy_id', 'asc')->select();
  7844. } catch (\Throwable $e) {
  7845. $pos = [$anchor];
  7846. }
  7847. if (!is_array($pos) || $pos === []) {
  7848. $pos = [$anchor];
  7849. }
  7850. return [
  7851. 'ccydh' => $ccydh,
  7852. 'pos' => $pos,
  7853. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7854. ];
  7855. }
  7856. protected function purchaseOrderRowIsCompleted(array $po): bool
  7857. {
  7858. $st = $po['status'] ?? null;
  7859. if ($st === 1 || $st === '1') {
  7860. return true;
  7861. }
  7862. if (is_string($st) && trim($st) === '1') {
  7863. return true;
  7864. }
  7865. return is_numeric($st) && (int)$st === 1;
  7866. }
  7867. /**
  7868. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  7869. */
  7870. public function auditAbandon()
  7871. {
  7872. if (!$this->request->isPost()) {
  7873. $this->error(__('Invalid parameters'));
  7874. }
  7875. $anchorIds = [];
  7876. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7877. if ($batchRaw !== '') {
  7878. $decoded = json_decode($batchRaw, true);
  7879. if (is_array($decoded)) {
  7880. foreach ($decoded as $id) {
  7881. $s = trim((string)$id);
  7882. if ($s !== '') {
  7883. $anchorIds[] = $s;
  7884. }
  7885. }
  7886. }
  7887. }
  7888. if ($anchorIds === []) {
  7889. $single = trim((string)$this->request->post('scydgy_id', ''));
  7890. if ($single !== '') {
  7891. $anchorIds[] = $single;
  7892. }
  7893. }
  7894. if ($anchorIds === []) {
  7895. $this->error('请至少选择一条订单');
  7896. }
  7897. $processedCcydh = [];
  7898. $doneOrders = 0;
  7899. $allSids = [];
  7900. Db::startTrans();
  7901. try {
  7902. foreach ($anchorIds as $anchorId) {
  7903. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  7904. if (($bundle['pos'] ?? []) === []) {
  7905. continue;
  7906. }
  7907. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7908. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7909. if (isset($processedCcydh[$dedupeKey])) {
  7910. continue;
  7911. }
  7912. $processedCcydh[$dedupeKey] = true;
  7913. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  7914. if ($sids === []) {
  7915. continue;
  7916. }
  7917. $doneOrders++;
  7918. foreach (array_keys($sids) as $sid) {
  7919. $allSids[(int)$sid] = true;
  7920. }
  7921. }
  7922. if ($doneOrders < 1) {
  7923. throw new \Exception('所选订单均不在待确认供应商状态');
  7924. }
  7925. Db::commit();
  7926. } catch (\Throwable $e) {
  7927. Db::rollback();
  7928. $this->error($e->getMessage());
  7929. }
  7930. $this->pickHiddenScydgySetCache = null;
  7931. $msg = $doneOrders > 1
  7932. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7933. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7934. $this->success($msg);
  7935. }
  7936. /**
  7937. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7938. */
  7939. public function archiveAbandon()
  7940. {
  7941. if (!$this->request->isPost()) {
  7942. $this->error(__('Invalid parameters'));
  7943. }
  7944. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7945. $this->error(__('You have no permission'));
  7946. }
  7947. $anchorIds = [];
  7948. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7949. if ($batchRaw !== '') {
  7950. $decoded = json_decode($batchRaw, true);
  7951. if (is_array($decoded)) {
  7952. foreach ($decoded as $id) {
  7953. $s = trim((string)$id);
  7954. if ($s !== '') {
  7955. $anchorIds[] = $s;
  7956. }
  7957. }
  7958. }
  7959. }
  7960. if ($anchorIds === []) {
  7961. $single = trim((string)$this->request->post('scydgy_id', ''));
  7962. if ($single !== '') {
  7963. $anchorIds[] = $single;
  7964. }
  7965. }
  7966. if ($anchorIds === []) {
  7967. $this->error('请至少选择一条订单');
  7968. }
  7969. $processedCcydh = [];
  7970. $doneOrders = 0;
  7971. Db::startTrans();
  7972. try {
  7973. foreach ($anchorIds as $anchorId) {
  7974. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7975. if (($bundle['pos'] ?? []) === []) {
  7976. continue;
  7977. }
  7978. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7979. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7980. if (isset($processedCcydh[$dedupeKey])) {
  7981. continue;
  7982. }
  7983. $processedCcydh[$dedupeKey] = true;
  7984. $sids = $this->abandonOrderBundleToPick(
  7985. $bundle,
  7986. 'archive_abandon',
  7987. ',从历史存证退回协助初选'
  7988. );
  7989. if ($sids === []) {
  7990. continue;
  7991. }
  7992. $doneOrders++;
  7993. }
  7994. if ($doneOrders < 1) {
  7995. throw new \Exception('所选订单均不是已完结状态');
  7996. }
  7997. Db::commit();
  7998. } catch (\Throwable $e) {
  7999. Db::rollback();
  8000. $this->error($e->getMessage());
  8001. }
  8002. $this->pickHiddenScydgySetCache = null;
  8003. $msg = $doneOrders > 1
  8004. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  8005. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  8006. $this->success($msg);
  8007. }
  8008. /**
  8009. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  8010. */
  8011. public function purchaseApprovalReject()
  8012. {
  8013. if (!$this->request->isPost() || !$this->request->isAjax()) {
  8014. $this->error(__('Invalid parameters'));
  8015. }
  8016. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  8017. $this->error(__('You have no permission'));
  8018. }
  8019. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  8020. $decoded = json_decode($batchRaw, true);
  8021. if (!is_array($decoded) || $decoded === []) {
  8022. $this->error('提交数据无效');
  8023. }
  8024. $done = 0;
  8025. Db::startTrans();
  8026. try {
  8027. foreach ($decoded as $item) {
  8028. if (!is_array($item)) {
  8029. continue;
  8030. }
  8031. $sid = (int)($item['scydgy_id'] ?? 0);
  8032. if (!$this->isValidScydgyRowId($sid)) {
  8033. continue;
  8034. }
  8035. $this->runPurchaseApprovalRejectForSid($sid);
  8036. $done++;
  8037. }
  8038. if ($done < 1) {
  8039. throw new \Exception('所选订单均不在待审批状态');
  8040. }
  8041. Db::commit();
  8042. } catch (\Throwable $e) {
  8043. Db::rollback();
  8044. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  8045. }
  8046. $this->pickHiddenScydgySetCache = null;
  8047. $this->success('已驳回并退回「协助审批下发」');
  8048. }
  8049. /**
  8050. * @throws \Exception
  8051. */
  8052. protected function runPurchaseApprovalRejectForSid(int $sid): void
  8053. {
  8054. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  8055. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  8056. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  8057. $allIds = $this->purchaseOrderDetail($sid);
  8058. if ($allIds === []) {
  8059. throw new \Exception('未找到下发明细');
  8060. }
  8061. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8062. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  8063. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  8064. 'pick_company_name' => '',
  8065. ]);
  8066. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  8067. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  8068. $poId = 0;
  8069. try {
  8070. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  8071. if (is_array($po)) {
  8072. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8073. }
  8074. } catch (\Throwable $e) {
  8075. }
  8076. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  8077. }
  8078. /**
  8079. * 审核弹窗(旧入口,POST 已关闭)
  8080. */
  8081. public function review()
  8082. {
  8083. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  8084. $this->error(__('You have no permission'));
  8085. }
  8086. if ($this->request->isPost()) {
  8087. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  8088. }
  8089. $this->view->assign('pickMode', 0);
  8090. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  8091. }
  8092. /**
  8093. * 审核弹窗获取公司列表
  8094. */
  8095. public function reviewCompanies()
  8096. {
  8097. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  8098. $this->error(__('You have no permission'));
  8099. }
  8100. if (!$this->request->isAjax()) {
  8101. $this->error(__('Invalid parameters'));
  8102. }
  8103. $list = [];
  8104. try {
  8105. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  8106. $rows = Db::table('customer')
  8107. ->where(function ($q) {
  8108. $q->where('status', 1)
  8109. ->whereOr('status', '1')
  8110. ->whereOr('status', '')
  8111. ->whereNull('status');
  8112. })
  8113. ->order('id', 'desc')
  8114. ->select();
  8115. } catch (\Throwable $e) {
  8116. $this->success('', '', []);
  8117. return;
  8118. }
  8119. if (!is_array($rows)) {
  8120. $this->success('', '', []);
  8121. return;
  8122. }
  8123. $detailColCandidates = [
  8124. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  8125. 'company_detail', 'company_desc', 'address',
  8126. ];
  8127. foreach ($rows as $row) {
  8128. if (!is_array($row)) {
  8129. continue;
  8130. }
  8131. $norm = [];
  8132. foreach ($row as $k => $v) {
  8133. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  8134. }
  8135. $row = $norm;
  8136. $st = $row['status'] ?? '';
  8137. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  8138. continue;
  8139. }
  8140. $payload = $this->buildCustomerContactPayloadFromRow($row);
  8141. if ($payload === null) {
  8142. continue;
  8143. }
  8144. $detail = '';
  8145. foreach ($detailColCandidates as $dk) {
  8146. if (!isset($row[$dk])) {
  8147. continue;
  8148. }
  8149. $dv = trim((string)$row[$dk]);
  8150. if ($dv !== '') {
  8151. $detail = $dv;
  8152. break;
  8153. }
  8154. }
  8155. $payload['detail'] = $detail;
  8156. $list[] = $this->maskSupplierContactFields($payload);
  8157. }
  8158. $this->success('', '', $list);
  8159. }
  8160. /**
  8161. * 采购确认-下发明细弹窗:
  8162. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  8163. */
  8164. public function outward_detail()
  8165. {
  8166. $ids = $this->request->param('ids', $this->request->param('id', ''));
  8167. if (is_array($ids)) {
  8168. $ids = isset($ids[0]) ? $ids[0] : '';
  8169. }
  8170. $ids = trim((string)$ids);
  8171. if ($ids === '') {
  8172. $this->error(__('Invalid parameters'));
  8173. }
  8174. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  8175. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  8176. $wffTab = 'all';
  8177. }
  8178. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  8179. $purchaseOrderId = 0;
  8180. $po = null;
  8181. try {
  8182. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  8183. if (is_array($po)) {
  8184. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8185. }
  8186. } catch (\Throwable $e) {
  8187. $purchaseOrderId = 0;
  8188. $po = null;
  8189. }
  8190. if (!$isPurchaseConfirm && is_array($po)) {
  8191. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  8192. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  8193. $isPurchaseConfirm = true;
  8194. }
  8195. }
  8196. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  8197. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  8198. $confirmProcessCount = 1;
  8199. $confirmPickGroups = [];
  8200. $processDisplayRows = [];
  8201. $allDetailsBySid = [];
  8202. $requiredSidList = [];
  8203. $sidList = [$ids];
  8204. if ($isPurchaseConfirm) {
  8205. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  8206. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  8207. if ($mergeRows !== []) {
  8208. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  8209. }
  8210. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  8211. if ($confirmBundle['pos'] !== []) {
  8212. $sidList = [];
  8213. foreach ($confirmBundle['pos'] as $poRow) {
  8214. if (!is_array($poRow)) {
  8215. continue;
  8216. }
  8217. $sid = (int)($poRow['scydgy_id'] ?? 0);
  8218. if (!$this->isValidScydgyRowId($sid)) {
  8219. continue;
  8220. }
  8221. $sidList[] = (string)$sid;
  8222. $requiredSidList[] = $sid;
  8223. }
  8224. }
  8225. if ($sidList === []) {
  8226. $sidList = [$ids];
  8227. $requiredSidList = [(int)$ids];
  8228. }
  8229. $confirmProcessCount = max(1, count($requiredSidList));
  8230. if (is_array($po) && $purchaseOrderId <= 0) {
  8231. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8232. }
  8233. }
  8234. $rows = [];
  8235. try {
  8236. if (count($sidList) === 1) {
  8237. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  8238. } else {
  8239. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  8240. }
  8241. } catch (\Throwable $e) {
  8242. $rows = [];
  8243. }
  8244. if ($isPurchaseConfirm) {
  8245. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  8246. }
  8247. foreach ($rows as &$r) {
  8248. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  8249. $r['id'] = $r['ID'];
  8250. }
  8251. if (isset($r['createtime'])) {
  8252. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  8253. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  8254. } else {
  8255. $r['createtime_text'] = (string)$r['createtime'];
  8256. }
  8257. } else {
  8258. $r['createtime_text'] = '';
  8259. }
  8260. if (is_array($r)) {
  8261. $r = $this->maskSupplierContactFields($r);
  8262. }
  8263. }
  8264. unset($r);
  8265. $pickedCompanyName = '';
  8266. if ($isPurchaseConfirm) {
  8267. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  8268. if (!is_array($poRow)) {
  8269. continue;
  8270. }
  8271. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  8272. if ($pn !== '') {
  8273. $pickedCompanyName = $pn;
  8274. break;
  8275. }
  8276. }
  8277. }
  8278. $this->view->assign('rows', $rows ?: []);
  8279. $this->view->assign('rowCount', count($rows ?: []));
  8280. $this->view->assign('scydgyId', $ids);
  8281. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  8282. $this->view->assign('headTitle', $headTitle);
  8283. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  8284. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  8285. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  8286. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  8287. $this->view->assign('processDisplayRows', $processDisplayRows);
  8288. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  8289. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  8290. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  8291. $this->view->assign('bidOpenVerified', ($isPurchaseConfirm && $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle)) ? 1 : 0);
  8292. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups));
  8293. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups) ? 1 : 0);
  8294. $sysRqDisplay = '—';
  8295. if ($isPurchaseConfirm) {
  8296. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  8297. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  8298. );
  8299. }
  8300. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  8301. $this->view->assign('sysRq', $isPurchaseConfirm
  8302. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  8303. : '');
  8304. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  8305. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  8306. : '');
  8307. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  8308. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  8309. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  8310. if ($isPurchaseConfirm) {
  8311. return $this->view->fetch();
  8312. }
  8313. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8314. $this->view->engine->layout(false);
  8315. try {
  8316. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  8317. $this->view->assign('dialogBody', $bodyHtml);
  8318. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  8319. } finally {
  8320. if ($restoreLayout) {
  8321. $this->view->engine->layout($restoreLayout);
  8322. }
  8323. }
  8324. }
  8325. /**
  8326. * 月度导出记录表(不存在时自动创建)
  8327. */
  8328. protected function ensurePurchaseMonthExportLogTable(): void
  8329. {
  8330. try {
  8331. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  8332. } catch (\Throwable $e) {
  8333. Db::execute(
  8334. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  8335. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  8336. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  8337. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  8338. `admin_name` varchar(64) NOT NULL DEFAULT '',
  8339. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  8340. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  8341. `createtime` int(10) unsigned DEFAULT NULL,
  8342. PRIMARY KEY (`id`),
  8343. KEY `idx_ym` (`ym`),
  8344. KEY `idx_ct` (`createtime`)
  8345. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  8346. );
  8347. }
  8348. }
  8349. /**
  8350. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  8351. *
  8352. * @param array<int, mixed> $dbRows
  8353. * @return array<int, array<string, mixed>>
  8354. */
  8355. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  8356. {
  8357. $keyword = trim((string)$this->request->get('search', ''));
  8358. if ($keyword === '') {
  8359. $keyword = trim((string)$this->request->request('search', ''));
  8360. }
  8361. $filter = $this->request->get('filter', '');
  8362. $op = $this->request->get('op', '');
  8363. if (is_string($filter) && $filter !== '') {
  8364. $filterArr = (array)json_decode($filter, true);
  8365. } else {
  8366. $filterArr = is_array($filter) ? $filter : [];
  8367. }
  8368. if (is_string($op) && $op !== '') {
  8369. $opArr = (array)json_decode($op, true);
  8370. } else {
  8371. $opArr = is_array($op) ? $op : [];
  8372. }
  8373. if ($keyword === '' && $filterArr === []) {
  8374. return array_values(array_filter($dbRows, 'is_array'));
  8375. }
  8376. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  8377. $out = [];
  8378. foreach ($dbRows as $row) {
  8379. if (!is_array($row)) {
  8380. continue;
  8381. }
  8382. if ($keyword !== '') {
  8383. $hit = false;
  8384. foreach ($searchFields as $f) {
  8385. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  8386. $hit = true;
  8387. break;
  8388. }
  8389. }
  8390. if (!$hit) {
  8391. continue;
  8392. }
  8393. }
  8394. $passFilter = true;
  8395. foreach ($filterArr as $field => $val) {
  8396. $field = (string)$field;
  8397. $val = trim((string)$val);
  8398. if ($field === '' || $val === '') {
  8399. continue;
  8400. }
  8401. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  8402. continue;
  8403. }
  8404. $cell = (string)($row[$field] ?? '');
  8405. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  8406. if ($mode === '=' || $mode === 'EQUAL') {
  8407. if (strcasecmp($cell, $val) !== 0) {
  8408. $passFilter = false;
  8409. break;
  8410. }
  8411. } elseif (mb_stripos($cell, $val) === false) {
  8412. $passFilter = false;
  8413. break;
  8414. }
  8415. }
  8416. if (!$passFilter) {
  8417. continue;
  8418. }
  8419. $out[] = $row;
  8420. }
  8421. return $out;
  8422. }
  8423. /**
  8424. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  8425. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  8426. */
  8427. public function export_month_outward()
  8428. {
  8429. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  8430. $this->error(__('You have no permission'));
  8431. }
  8432. $bundle = $this->prepareMonthOutwardExportBundle();
  8433. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  8434. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  8435. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  8436. $spreadsheet = new Spreadsheet();
  8437. $sheet = $spreadsheet->getActiveSheet();
  8438. $sheet->setTitle('外协加工明细');
  8439. $mon = (int)substr($ym, 5, 2);
  8440. $sheet->mergeCells('A1:H1');
  8441. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  8442. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  8443. $sheet->getStyle('A1')->getAlignment()
  8444. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8445. ->setVertical(Alignment::VERTICAL_CENTER);
  8446. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  8447. $col = 'A';
  8448. foreach ($headers as $h) {
  8449. $sheet->setCellValue($col . '2', $h);
  8450. $col++;
  8451. }
  8452. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  8453. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8454. $rowNum = 3;
  8455. $sumSubtotalCounts = 0;
  8456. $grandAmount = 0.0;
  8457. $globalSeq = 0;
  8458. if ($groups === []) {
  8459. $sheet->mergeCells('A3:H3');
  8460. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  8461. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8462. $rowNum = 4;
  8463. } else {
  8464. foreach ($groups as $items) {
  8465. if ($items === []) {
  8466. continue;
  8467. }
  8468. $groupLineCount = count($items);
  8469. $subAmount = 0.0;
  8470. foreach ($items as $line) {
  8471. $globalSeq++;
  8472. $dr = $line['detail'];
  8473. $amt = $this->procuremenExportAmount($dr);
  8474. $subAmount += $amt;
  8475. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  8476. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  8477. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  8478. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  8479. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  8480. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  8481. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  8482. $sheet->setCellValue('H' . $rowNum, $amt);
  8483. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  8484. $rowNum++;
  8485. }
  8486. $sumSubtotalCounts += $groupLineCount;
  8487. $grandAmount += $subAmount;
  8488. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8489. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  8490. $sheet->getStyle('G' . $rowNum)->getAlignment()
  8491. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8492. ->setVertical(Alignment::VERTICAL_CENTER);
  8493. $rowNum++;
  8494. }
  8495. }
  8496. $sheet->setCellValue('A' . $rowNum, '总计');
  8497. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  8498. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  8499. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  8500. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8501. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  8502. $lastRow = $rowNum;
  8503. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  8504. 'borders' => [
  8505. 'allBorders' => [
  8506. 'borderStyle' => Border::BORDER_THIN,
  8507. 'color' => ['rgb' => '000000'],
  8508. ],
  8509. ],
  8510. ]);
  8511. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8512. if ($lastRow >= 3) {
  8513. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8514. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8515. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8516. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8517. }
  8518. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  8519. $sheet->getColumnDimension('A')->setWidth(7);
  8520. $sheet->getColumnDimension('B')->setWidth(16);
  8521. $sheet->getColumnDimension('C')->setWidth(52);
  8522. $sheet->getColumnDimension('D')->setWidth(32);
  8523. $sheet->getColumnDimension('E')->setWidth(12);
  8524. $sheet->getColumnDimension('F')->setWidth(44);
  8525. $sheet->getColumnDimension('G')->setWidth(26);
  8526. $sheet->getColumnDimension('H')->setWidth(13);
  8527. $sheet->getRowDimension(1)->setRowHeight(28);
  8528. $ymCompact = str_replace('-', '', $ym);
  8529. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  8530. $filename = $fileBase . '.xlsx';
  8531. try {
  8532. $this->ensurePurchaseMonthExportLogTable();
  8533. list($adminId, $adminName) = $this->GetUseName();
  8534. Db::table('purchase_month_export_log')->insert([
  8535. 'ym' => $ym,
  8536. 'admin_id' => (int)$adminId,
  8537. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  8538. 'row_count' => count($exportLines),
  8539. 'total_amount' => round($grandAmount, 2),
  8540. 'createtime' => time(),
  8541. ]);
  8542. } catch (\Throwable $e) {
  8543. Log::write('month export log: ' . $e->getMessage(), 'error');
  8544. }
  8545. if (ob_get_length()) {
  8546. ob_end_clean();
  8547. }
  8548. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  8549. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8550. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  8551. header('Cache-Control: max-age=0');
  8552. $writer = new Xlsx($spreadsheet);
  8553. $writer->save('php://output');
  8554. $spreadsheet->disconnectWorksheets();
  8555. unset($spreadsheet);
  8556. exit;
  8557. }
  8558. /**
  8559. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  8560. */
  8561. public function export_month_quote()
  8562. {
  8563. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  8564. $this->error(__('You have no permission'));
  8565. }
  8566. $bundle = $this->prepareMonthOutwardExportBundle();
  8567. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  8568. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  8569. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  8570. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  8571. $spreadsheet = new Spreadsheet();
  8572. $sheet = $spreadsheet->getActiveSheet();
  8573. $sheet->setTitle('供应商报价明细');
  8574. $mon = (int)substr($ym, 5, 2);
  8575. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  8576. $sheet->getColumnDimension('A')->setWidth(7);
  8577. $sheet->getColumnDimension('B')->setWidth(16);
  8578. $sheet->getColumnDimension('C')->setWidth(52);
  8579. $sheet->getColumnDimension('D')->setWidth(26);
  8580. $sheet->getColumnDimension('E')->setWidth(32);
  8581. $sheet->getColumnDimension('F')->setWidth(12);
  8582. $sheet->getColumnDimension('G')->setWidth(14);
  8583. $sheet->getColumnDimension('H')->setWidth(12);
  8584. if ($quoteLastRow < 1) {
  8585. $quoteLastRow = 3;
  8586. }
  8587. $ymCompact = str_replace('-', '', $ym);
  8588. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  8589. if (ob_get_length()) {
  8590. ob_end_clean();
  8591. }
  8592. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  8593. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8594. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  8595. header('Cache-Control: max-age=0');
  8596. $writer = new Xlsx($spreadsheet);
  8597. $writer->save('php://output');
  8598. $spreadsheet->disconnectWorksheets();
  8599. unset($spreadsheet);
  8600. exit;
  8601. }
  8602. /**
  8603. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  8604. *
  8605. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  8606. */
  8607. protected function prepareMonthOutwardExportBundle(): array
  8608. {
  8609. $this->request->filter(['strip_tags', 'trim']);
  8610. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  8611. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8612. $ym = date('Y-m');
  8613. }
  8614. $dbRows = [];
  8615. try {
  8616. $query = Db::table('purchase_order');
  8617. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  8618. $dbRows = $query->select();
  8619. } catch (\Throwable $e) {
  8620. $dbRows = [];
  8621. }
  8622. if (!is_array($dbRows)) {
  8623. $dbRows = [];
  8624. }
  8625. $completeTsMap = [];
  8626. $sidList = [];
  8627. foreach ($dbRows as $dbRow) {
  8628. if (!is_array($dbRow)) {
  8629. continue;
  8630. }
  8631. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  8632. if ($sid > 0) {
  8633. $sidList[$sid] = true;
  8634. }
  8635. }
  8636. if ($sidList !== []) {
  8637. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  8638. }
  8639. $searchKw = trim((string)$this->request->get('search', ''));
  8640. if ($searchKw === '') {
  8641. $searchKw = trim((string)$this->request->request('search', ''));
  8642. }
  8643. $filterRaw = $this->request->get('filter', '');
  8644. $filterArrTmp = [];
  8645. if (is_string($filterRaw) && $filterRaw !== '') {
  8646. $filterArrTmp = (array)json_decode($filterRaw, true);
  8647. } elseif (is_array($filterRaw)) {
  8648. $filterArrTmp = $filterRaw;
  8649. }
  8650. $hasSearch = ($searchKw !== '');
  8651. if (!$hasSearch) {
  8652. foreach ($filterArrTmp as $fv) {
  8653. if (trim((string)$fv) !== '') {
  8654. $hasSearch = true;
  8655. break;
  8656. }
  8657. }
  8658. }
  8659. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  8660. if (!is_array($dbRow)) {
  8661. return false;
  8662. }
  8663. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  8664. if ($done['ts'] <= 0) {
  8665. return false;
  8666. }
  8667. if ($hasSearch) {
  8668. return true;
  8669. }
  8670. return date('Y-m', $done['ts']) === $ym;
  8671. }));
  8672. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  8673. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  8674. $mainBySid = [];
  8675. foreach ($pool as $rw) {
  8676. if (!is_array($rw)) {
  8677. continue;
  8678. }
  8679. $rid = (int)($rw['ID'] ?? 0);
  8680. if ($rid > 0) {
  8681. $mainBySid[$rid] = $rw;
  8682. }
  8683. }
  8684. if ($mainBySid === []) {
  8685. $detailRows = [];
  8686. } else {
  8687. try {
  8688. $detailRows = Db::table('purchase_order_detail')
  8689. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8690. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8691. ->order('status', 'desc')
  8692. ->order('CCYDH', 'asc')
  8693. ->order('company_name', 'asc')
  8694. ->order('id', 'asc')
  8695. ->select();
  8696. } catch (\Throwable $e) {
  8697. try {
  8698. $detailRows = Db::table('purchase_order_detail')
  8699. ->where('scydgy_id', 'in', array_keys($mainBySid))
  8700. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  8701. ->order('status', 'desc')
  8702. ->order('CCYDH', 'asc')
  8703. ->order('company_name', 'asc')
  8704. ->order('ID', 'asc')
  8705. ->select();
  8706. } catch (\Throwable $e2) {
  8707. $detailRows = [];
  8708. }
  8709. }
  8710. }
  8711. if (!is_array($detailRows)) {
  8712. $detailRows = [];
  8713. }
  8714. $exportLines = [];
  8715. $detailSidSeen = [];
  8716. foreach ($detailRows as $dr) {
  8717. if (!is_array($dr)) {
  8718. continue;
  8719. }
  8720. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8721. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8722. continue;
  8723. }
  8724. if (isset($detailSidSeen[$sid])) {
  8725. continue;
  8726. }
  8727. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  8728. continue;
  8729. }
  8730. $detailSidSeen[$sid] = true;
  8731. $m = $mainBySid[$sid];
  8732. $exportLines[] = [
  8733. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8734. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8735. 'company_name' => (string)($dr['company_name'] ?? ''),
  8736. 'CDF' => (string)($m['CDF'] ?? ''),
  8737. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8738. 'gx' => $this->procuremenExportGxText($m),
  8739. 'detail' => $dr,
  8740. ];
  8741. }
  8742. foreach ($detailRows as $dr) {
  8743. if (!is_array($dr)) {
  8744. continue;
  8745. }
  8746. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8747. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  8748. continue;
  8749. }
  8750. $detailSidSeen[$sid] = true;
  8751. $m = $mainBySid[$sid];
  8752. $exportLines[] = [
  8753. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8754. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8755. 'company_name' => (string)($dr['company_name'] ?? ''),
  8756. 'CDF' => (string)($m['CDF'] ?? ''),
  8757. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8758. 'gx' => $this->procuremenExportGxText($m),
  8759. 'detail' => $dr,
  8760. ];
  8761. }
  8762. foreach ($mainBySid as $sid => $m) {
  8763. if (isset($detailSidSeen[$sid])) {
  8764. continue;
  8765. }
  8766. $company = trim((string)($m['pick_company_name'] ?? ''));
  8767. $exportLines[] = [
  8768. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  8769. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  8770. 'company_name' => $company,
  8771. 'CDF' => (string)($m['CDF'] ?? ''),
  8772. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  8773. 'gx' => $this->procuremenExportGxText($m),
  8774. 'detail' => [],
  8775. ];
  8776. }
  8777. $groups = [];
  8778. foreach ($exportLines as $line) {
  8779. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  8780. if (!isset($groups[$k])) {
  8781. $groups[$k] = [];
  8782. }
  8783. $groups[$k][] = $line;
  8784. }
  8785. ksort($groups, SORT_STRING);
  8786. return [
  8787. 'ym' => $ym,
  8788. 'mainBySid' => $mainBySid,
  8789. 'detailRows' => $detailRows,
  8790. 'exportLines' => $exportLines,
  8791. 'groups' => $groups,
  8792. ];
  8793. }
  8794. /**
  8795. * 导出用:工序列文案
  8796. */
  8797. protected function procuremenExportGxText(array $r)
  8798. {
  8799. $a = trim((string)($r['CDXMC'] ?? ''));
  8800. $b = trim((string)($r['CGYMC'] ?? ''));
  8801. if ($a !== '' && $b !== '') {
  8802. return $a . ':' . $b;
  8803. }
  8804. return $a !== '' ? $a : $b;
  8805. }
  8806. /**
  8807. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  8808. */
  8809. protected function procuremenExportAmount(array $r)
  8810. {
  8811. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  8812. if (!array_key_exists($k, $r)) {
  8813. continue;
  8814. }
  8815. $v = $r[$k];
  8816. if ($v === null || $v === '') {
  8817. continue;
  8818. }
  8819. if (is_numeric($v)) {
  8820. return (float)$v;
  8821. }
  8822. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  8823. if ($v !== '' && is_numeric($v)) {
  8824. return (float)$v;
  8825. }
  8826. }
  8827. return 0.0;
  8828. }
  8829. /**
  8830. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  8831. *
  8832. * @param array<int, array<string, mixed>> $detailRows
  8833. * @param array<int, array<string, mixed>> $mainBySid
  8834. * @return array<int, array<string, mixed>>
  8835. */
  8836. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  8837. {
  8838. $lines = [];
  8839. foreach ($detailRows as $dr) {
  8840. if (!is_array($dr)) {
  8841. continue;
  8842. }
  8843. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  8844. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  8845. continue;
  8846. }
  8847. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  8848. continue;
  8849. }
  8850. $cn = trim((string)($dr['company_name'] ?? ''));
  8851. if ($cn === '') {
  8852. continue;
  8853. }
  8854. $m = $mainBySid[$sid];
  8855. $am = trim((string)($dr['amount'] ?? ''));
  8856. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  8857. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  8858. $amountText = $amountFilled
  8859. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  8860. : '未填写';
  8861. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  8862. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  8863. if ($deliveryShow === '' && $deliveryRaw !== '') {
  8864. $deliveryShow = $deliveryRaw;
  8865. }
  8866. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  8867. ? $deliveryShow
  8868. : '未填写';
  8869. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  8870. $lines[] = [
  8871. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  8872. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  8873. 'gx' => $this->procuremenExportGxText($m),
  8874. 'company_name' => $cn,
  8875. 'amount_text' => $amountText,
  8876. 'amount_num' => $amountFilled ? $amountNum : null,
  8877. 'delivery_text' => $deliveryText,
  8878. 'picked_text' => $picked ? '中标' : '未中标',
  8879. 'picked' => $picked,
  8880. ];
  8881. }
  8882. $winnerSupplierByOrder = [];
  8883. foreach ($lines as $line) {
  8884. $dh = trim((string)($line['CCYDH'] ?? ''));
  8885. $cn = trim((string)($line['company_name'] ?? ''));
  8886. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  8887. $winnerSupplierByOrder[$dh][$cn] = true;
  8888. }
  8889. }
  8890. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  8891. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  8892. if ($c !== 0) {
  8893. return $c;
  8894. }
  8895. $dh = trim((string)($a['CCYDH'] ?? ''));
  8896. $aCn = trim((string)($a['company_name'] ?? ''));
  8897. $bCn = trim((string)($b['company_name'] ?? ''));
  8898. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  8899. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  8900. if ($aSupplierWin !== $bSupplierWin) {
  8901. return $aSupplierWin ? -1 : 1;
  8902. }
  8903. $c = strcmp($aCn, $bCn);
  8904. if ($c !== 0) {
  8905. return $c;
  8906. }
  8907. if (!empty($a['picked']) !== !empty($b['picked'])) {
  8908. return !empty($a['picked']) ? -1 : 1;
  8909. }
  8910. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  8911. if ($c !== 0) {
  8912. return $c;
  8913. }
  8914. return 0;
  8915. });
  8916. return $lines;
  8917. }
  8918. /**
  8919. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  8920. *
  8921. * @param array<int, array<string, mixed>> $quoteLines
  8922. */
  8923. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  8924. {
  8925. $mon = (int)substr($ym, 5, 2);
  8926. $titleRow = $startRow;
  8927. $headerRow = $startRow + 1;
  8928. $dataStartRow = $startRow + 2;
  8929. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  8930. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  8931. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  8932. $sheet->getStyle('A' . $titleRow)->getAlignment()
  8933. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8934. ->setVertical(Alignment::VERTICAL_CENTER);
  8935. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  8936. $col = 'A';
  8937. foreach ($headers as $h) {
  8938. $sheet->setCellValue($col . $headerRow, $h);
  8939. $col++;
  8940. }
  8941. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  8942. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8943. $rowNum = $dataStartRow;
  8944. if ($quoteLines === []) {
  8945. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  8946. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  8947. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8948. $rowNum = $dataStartRow + 1;
  8949. } else {
  8950. $i = 0;
  8951. foreach ($quoteLines as $line) {
  8952. $i++;
  8953. $sheet->setCellValue('A' . $rowNum, $i);
  8954. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  8955. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  8956. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  8957. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  8958. if ($line['amount_num'] !== null) {
  8959. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  8960. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  8961. } else {
  8962. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  8963. }
  8964. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  8965. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  8966. if (!empty($line['picked'])) {
  8967. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8968. }
  8969. $rowNum++;
  8970. }
  8971. }
  8972. $lastRow = $rowNum - 1;
  8973. if ($lastRow >= $headerRow) {
  8974. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  8975. 'borders' => [
  8976. 'allBorders' => [
  8977. 'borderStyle' => Border::BORDER_THIN,
  8978. 'color' => ['rgb' => '000000'],
  8979. ],
  8980. ],
  8981. ]);
  8982. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8983. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8984. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8985. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8986. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  8987. if ($lastRow >= $dataStartRow) {
  8988. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  8989. }
  8990. }
  8991. return $lastRow;
  8992. }
  8993. /**
  8994. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  8995. */
  8996. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  8997. {
  8998. if ($lastRow < $dataStartRow || $headerRow < 1) {
  8999. return;
  9000. }
  9001. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  9002. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  9003. ->setVertical(Alignment::VERTICAL_CENTER);
  9004. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  9005. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  9006. ->setVertical(Alignment::VERTICAL_CENTER);
  9007. if ($lastCol > 'B') {
  9008. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  9009. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  9010. ->setVertical(Alignment::VERTICAL_CENTER);
  9011. }
  9012. }
  9013. /**
  9014. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  9015. */
  9016. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  9017. {
  9018. $s = trim($ccydh);
  9019. if ($s === '') {
  9020. return 'ORDER';
  9021. }
  9022. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  9023. $s = trim($s, '._-');
  9024. if ($s === '') {
  9025. return 'ORDER';
  9026. }
  9027. if (function_exists('mb_substr')) {
  9028. return mb_substr($s, 0, 80, 'UTF-8');
  9029. }
  9030. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  9031. }
  9032. /**
  9033. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  9034. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  9035. *
  9036. * @return array{objectKey: string, webPath: string}
  9037. */
  9038. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  9039. {
  9040. $sid = (int)$scydgyId;
  9041. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  9042. $y = date('Y');
  9043. $m = date('m');
  9044. $d = date('d');
  9045. $basename = $safeOrder . '_' . $sid . '.pdf';
  9046. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  9047. return [
  9048. 'objectKey' => $objectKey,
  9049. 'webPath' => '/' . $objectKey,
  9050. ];
  9051. }
  9052. /**
  9053. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  9054. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  9055. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  9056. *
  9057. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  9058. */
  9059. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  9060. {
  9061. if (!$this->isValidScydgyRowId($scydgyId)) {
  9062. return '';
  9063. }
  9064. $ids = trim((string)$scydgyId);
  9065. $prep = $this->prepareProcuremenDetailsView($ids);
  9066. if (!$prep['ok']) {
  9067. return '';
  9068. }
  9069. $ccydh = $prep['ccydh'];
  9070. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  9071. $objectKey = $paths['objectKey'];
  9072. $webPath = $paths['webPath'];
  9073. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  9074. $this->view->assign([
  9075. 'pdf_export' => 1,
  9076. 'pdfMetaLine' => $meta,
  9077. ]);
  9078. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  9079. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  9080. $this->view->engine->layout(false);
  9081. try {
  9082. $html = $this->view->fetch('procuremen/details_pdf_shell');
  9083. } catch (\Throwable $e) {
  9084. if ($restoreLayout) {
  9085. $this->view->engine->layout($restoreLayout);
  9086. }
  9087. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  9088. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  9089. return '';
  9090. }
  9091. if ($restoreLayout) {
  9092. $this->view->engine->layout($restoreLayout);
  9093. }
  9094. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  9095. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  9096. if (!is_dir($tempDir)) {
  9097. @mkdir($tempDir, 0755, true);
  9098. }
  9099. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  9100. try {
  9101. $mpdf = new \Mpdf\Mpdf([
  9102. 'mode' => 'utf-8',
  9103. 'format' => 'A4',
  9104. 'margin_left' => 12,
  9105. 'margin_right' => 12,
  9106. 'margin_top' => 14,
  9107. 'margin_bottom' => 14,
  9108. 'tempDir' => $tempDir,
  9109. 'autoScriptToLang' => true,
  9110. 'autoLangToFont' => true,
  9111. ]);
  9112. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  9113. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  9114. $mpdf->SetBasePath('http://127.0.0.1/');
  9115. $mpdf->WriteHTML($html);
  9116. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  9117. } catch (\Throwable $e) {
  9118. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  9119. if (is_file($tempPdf)) {
  9120. @unlink($tempPdf);
  9121. }
  9122. return '';
  9123. }
  9124. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  9125. if ($ossUrl !== '') {
  9126. @unlink($tempPdf);
  9127. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  9128. return $ossUrl;
  9129. }
  9130. $pi = pathinfo($objectKey);
  9131. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  9132. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  9133. if ($baseFile === '') {
  9134. @unlink($tempPdf);
  9135. return '';
  9136. }
  9137. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  9138. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  9139. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  9140. @unlink($tempPdf);
  9141. return '';
  9142. }
  9143. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  9144. if (!@copy($tempPdf, $fullPath)) {
  9145. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  9146. @unlink($tempPdf);
  9147. return '';
  9148. }
  9149. @unlink($tempPdf);
  9150. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  9151. return $webPath;
  9152. }
  9153. /**
  9154. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  9155. */
  9156. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  9157. {
  9158. if ($scydgyId <= 0 || $webPath === '') {
  9159. return;
  9160. }
  9161. try {
  9162. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  9163. } catch (\Throwable $e) {
  9164. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  9165. }
  9166. }
  9167. /**
  9168. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  9169. *
  9170. * @param array<string, string> $vars
  9171. * @return array<string, string>
  9172. */
  9173. protected function normalizeSmsTemplateVars(array $vars): array
  9174. {
  9175. $out = [];
  9176. foreach ($vars as $k => $v) {
  9177. $out[(string)$k] = trim((string)$v);
  9178. }
  9179. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  9180. $out['contact_name'] = $out['company_name'];
  9181. }
  9182. return $out;
  9183. }
  9184. /**
  9185. * 按手机号或公司名称查 customer 表联系人姓名
  9186. */
  9187. protected function resolveCustomerContactName(string $phone, string $companyName): string
  9188. {
  9189. $phone = trim($phone);
  9190. $companyName = trim($companyName);
  9191. try {
  9192. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  9193. $row = Db::table('customer')
  9194. ->where(function ($q) use ($phone) {
  9195. $q->where('phone', $phone)->whereOr('account', $phone);
  9196. })
  9197. ->order('id', 'asc')
  9198. ->find();
  9199. if (is_array($row)) {
  9200. $nm = trim((string)($row['username'] ?? ''));
  9201. if ($nm !== '') {
  9202. return $nm;
  9203. }
  9204. }
  9205. }
  9206. if ($companyName !== '') {
  9207. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  9208. if (is_array($row)) {
  9209. return trim((string)($row['username'] ?? ''));
  9210. }
  9211. }
  9212. } catch (\Throwable $e) {
  9213. }
  9214. return '';
  9215. }
  9216. /**
  9217. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  9218. */
  9219. protected function plainTextToHtmlEmailBody(string $text): string
  9220. {
  9221. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  9222. $parts = explode("\n", $text);
  9223. $out = [];
  9224. foreach ($parts as $line) {
  9225. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  9226. $out[] = $line;
  9227. } else {
  9228. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  9229. }
  9230. }
  9231. return implode("<br>\n", $out);
  9232. }
  9233. /**
  9234. * 短信场景:去掉链接类变量,避免误填 URL
  9235. *
  9236. * @param array<string, string> $vars
  9237. * @return array<string, string>
  9238. */
  9239. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  9240. {
  9241. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  9242. return $vars;
  9243. }
  9244. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  9245. $vars[$k] = '';
  9246. }
  9247. return $vars;
  9248. }
  9249. /**
  9250. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  9251. *
  9252. * @param array<string, string> $vars
  9253. */
  9254. protected function renderNotifyTemplate(string $scene, array $vars): string
  9255. {
  9256. $vars = $this->normalizeSmsTemplateVars($vars);
  9257. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  9258. $row = $this->loadNotifyTemplateRow($scene);
  9259. if ($row === null) {
  9260. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  9261. }
  9262. $tpl = trim((string)($row['content'] ?? ''));
  9263. if ($tpl === '') {
  9264. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  9265. }
  9266. foreach ($vars as $k => $v) {
  9267. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  9268. }
  9269. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  9270. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  9271. return $tpl;
  9272. }
  9273. protected function resolveProcuremenEmailSubject(string $scene): string
  9274. {
  9275. $map = [
  9276. 'review_email' => '您有新的协助加工订单',
  9277. ];
  9278. $subject = trim((string)($map[$scene] ?? ''));
  9279. if ($subject === '') {
  9280. $this->error('未配置邮件主题:' . $scene);
  9281. }
  9282. return $subject;
  9283. }
  9284. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  9285. {
  9286. $map = [
  9287. 'review_email' => '协助下发-邮箱',
  9288. 'review_sms' => '协助下发-短信',
  9289. 'confirm_ok' => '采购确认-通过',
  9290. 'confirm_fail' => '采购确认-未通过',
  9291. 'bid_open' => '开标双重验证',
  9292. ];
  9293. $label = $map[$scene] ?? $scene;
  9294. if ($titleRequired) {
  9295. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  9296. }
  9297. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  9298. }
  9299. /**
  9300. * 是否开启协助通知演练(不发真实短信/邮件)
  9301. */
  9302. protected function isProcuremenNotifyDryRun(): bool
  9303. {
  9304. return (bool)Config::get('procuremen_notify_dry_run');
  9305. }
  9306. /**
  9307. * @param array<string, mixed> $payload
  9308. */
  9309. protected function recordNotifyDryRunPreview(array $payload): void
  9310. {
  9311. $this->notifyDryRunPreview[] = $payload;
  9312. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  9313. }
  9314. /**
  9315. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  9316. * @throws \Exception
  9317. */
  9318. protected function smsbao($phone, $content)
  9319. {
  9320. if ($this->isProcuremenNotifyDryRun()) {
  9321. $this->recordNotifyDryRunPreview([
  9322. 'scene' => 'sms_only',
  9323. 'phone' => $phone,
  9324. 'sms_content' => $content,
  9325. ]);
  9326. return;
  9327. }
  9328. $statusStr = [
  9329. '0' => '短信发送成功',
  9330. '-1' => '参数不全',
  9331. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  9332. '30' => '密码错误',
  9333. '40' => '账号不存在',
  9334. '41' => '余额不足',
  9335. '42' => '帐户已过期',
  9336. '43' => 'IP地址限制',
  9337. '50' => '内容含有敏感词',
  9338. ];
  9339. $smsapi = 'http://api.smsbao.com/';
  9340. $user = 'zhuwei123';
  9341. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  9342. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  9343. $result = @file_get_contents($sendurl);
  9344. if ($result === false) {
  9345. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  9346. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  9347. }
  9348. $result = trim((string)$result);
  9349. if ($result !== '0') {
  9350. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  9351. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  9352. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  9353. }
  9354. }
  9355. }