| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053 |
- <?php
- namespace app\admin\controller;
- use app\common\controller\Backend;
- use app\common\library\AliyunOss;
- use app\common\library\ProcuremenGuard;
- use app\common\library\ProcuremenOperLog;
- use app\common\library\ProcuremenStatus;
- use app\common\library\ProcuremenTime;
- use PHPMailer\PHPMailer\PHPMailer;
- use think\Config;
- use PhpOffice\PhpSpreadsheet\Spreadsheet;
- use PhpOffice\PhpSpreadsheet\Style\Alignment;
- use PhpOffice\PhpSpreadsheet\Style\Border;
- use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
- use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
- use think\Db;
- use think\Log;
- class Procuremen extends Backend
- {
- /**
- * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
- */
- protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
- /**
- * Procuremen模型对象
- * @var \app\admin\model\Procuremen
- */
- protected $model = null;
- /**
- * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
- */
- protected $notifyDryRunPreview = [];
- /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
- protected $procuremenRedisCache = null;
- /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
- protected $pickHiddenScydgySetCache = null;
- /**
- * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
- * @var array
- */
- protected $noNeedRight = [
- 'pickreview', 'review', 'reviewcompanies',
- ];
- public function _initialize()
- {
- parent::_initialize();
- $this->model = new \app\admin\model\Procuremen;
- $this->maybeMigrateLegacyWflowStatusText();
- $this->assignProcuremenAuthConfig();
- }
- /**
- * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
- */
- protected function maybeMigrateLegacyWflowStatusText(): void
- {
- $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
- if (is_file($flagFile)) {
- return;
- }
- $map = [
- '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
- '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
- '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
- '3' => ProcuremenStatus::WFLOW_APPROVED,
- ];
- try {
- foreach ($map as $num => $text) {
- Db::table('purchase_order')
- ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
- ->update(['wflow_status' => $text]);
- }
- @file_put_contents($flagFile, date('c'));
- } catch (\Throwable $e) {
- Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
- }
- }
- /**
- * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
- *
- * @param string[] $actions 如 pickreview、procuremen/picksubmit
- */
- protected function hasProcuremenPerm(array $actions): bool
- {
- foreach ($actions as $action) {
- $action = strtolower(trim((string)$action));
- if ($action === '') {
- continue;
- }
- if (strpos($action, 'procuremen/') !== 0) {
- $action = 'procuremen/' . $action;
- }
- if ($this->auth->check($action)) {
- return true;
- }
- }
- $suffixes = [];
- foreach ($actions as $action) {
- $action = strtolower(trim((string)$action));
- $action = preg_replace('#^procuremen/#', '', $action);
- if ($action !== '') {
- $suffixes[$action] = true;
- }
- }
- if ($suffixes === []) {
- return false;
- }
- try {
- foreach ($this->auth->getRuleList() as $rule) {
- $rule = strtolower((string)$rule);
- if (strpos($rule, 'procuremen/') !== 0) {
- continue;
- }
- foreach (array_keys($suffixes) as $suffix) {
- if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
- return true;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- return false;
- }
- /**
- * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
- *
- * @param string[] $actions
- */
- protected function hasProcuremenPermStrict(array $actions): bool
- {
- foreach ($actions as $action) {
- $action = strtolower(trim((string)$action));
- if ($action === '') {
- continue;
- }
- if (strpos($action, 'procuremen/') !== 0) {
- $action = 'procuremen/' . $action;
- }
- if ($this->auth->check($action)) {
- return true;
- }
- }
- return false;
- }
- /**
- * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
- *
- * @param string[] $titles
- */
- protected function authHasAssignedRuleTitle(array $titles): bool
- {
- $titles = array_values(array_filter(array_map('trim', $titles)));
- if ($titles === []) {
- return false;
- }
- try {
- $ids = $this->auth->getRuleIds();
- if (in_array('*', $ids, true)) {
- return true;
- }
- if ($ids === []) {
- return false;
- }
- $rows = Db::name('auth_rule')
- ->where('status', 'normal')
- ->whereIn('id', $ids)
- ->column('title');
- foreach ($rows as $title) {
- $t = trim((string)$title);
- if ($t !== '' && in_array($t, $titles, true)) {
- return true;
- }
- }
- } catch (\Throwable $e) {
- }
- return false;
- }
- protected function procuremenCanPickDelete(): bool
- {
- if ($this->hasProcuremenPermStrict(['pickdelete'])) {
- return true;
- }
- return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
- }
- protected function procuremenCanComplete(): bool
- {
- if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
- return true;
- }
- return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
- }
- protected function procuremenCanDispatch(): bool
- {
- return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
- }
- /**
- * 前端按钮显隐(Config.procuremenAuth)
- */
- protected function assignProcuremenAuthConfig(): void
- {
- $authMap = [
- 'pickreview' => $this->procuremenCanDispatch(),
- 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
- 'pickdelete' => $this->procuremenCanPickDelete(),
- 'completedirectly' => $this->procuremenCanComplete(),
- 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
- 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
- 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
- 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
- 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
- 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
- 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
- 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
- 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
- 'details' => $this->hasProcuremenPerm(['details']),
- 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon']),
- 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
- 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
- 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
- 'add' => $this->hasProcuremenPerm(['add']),
- 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
- 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
- ];
- $this->assignconfig('procuremenAuth', $authMap);
- }
- /**
- * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
- * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
- *
- * @param int $purchaseOrderDetailId purchase_order_detail 主键
- */
- protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
- {
- static $mprocCfgLoaded = false;
- if (!$mprocCfgLoaded) {
- $mprocCfgLoaded = true;
- if (is_file(APP_PATH . 'extra/mproc.php')) {
- Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
- }
- }
- $eid = (int)$purchaseOrderDetailId;
- $base = $this->resolveMprocMobilePublicBaseUrl();
- if ($base === '') {
- throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
- }
- $path = trim((string)Config::get('mproc.mobile_index_path'));
- if ($path === '') {
- $path = '/index.php/index/index/index';
- } else {
- $path = '/' . ltrim($path, '/');
- }
- // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(& 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
- if ($eid > 0) {
- return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
- }
- return $base . $path . '?main_tab=orders';
- }
- /**
- * 邮件/短信外链:须为带点的公网域名
- */
- protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
- {
- $u = trim((string)$baseUrl);
- if ($u === '' || !preg_match('#^https?://#i', $u)) {
- return false;
- }
- $host = parse_url($u, PHP_URL_HOST);
- if (!is_string($host) || $host === '') {
- return false;
- }
- if (strcasecmp($host, 'localhost') === 0) {
- return false;
- }
- if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
- return false;
- }
- if (strpos($host, '.') === false) {
- return false;
- }
- return true;
- }
- /**
- * 解析用于协助邮件/短信的手机端站点根
- */
- protected function resolveMprocMobilePublicBaseUrl()
- {
- $candidates = [];
- $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
- $candidates[] = trim((string)Config::get('site.indexurl'));
- $cdn = trim((string)Config::get('site.cdnurl'));
- if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
- $candidates[] = rtrim($cdn, '/');
- }
- $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
- $candidates[] = $reqBase;
- foreach ($candidates as $c) {
- if ($c === '') {
- continue;
- }
- $c = rtrim($c, '/');
- if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
- return $c;
- }
- }
- // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
- $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
- if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
- return $reqBase;
- }
- Log::write('协助邮件手机链接:配置地址失效', 'warning');
- return '';
- }
- /**
- * 获取 Redis 中 procuremen_redis
- */
- protected function ProcuremenRedis(): array
- {
- if ($this->procuremenRedisCache !== null) {
- return $this->procuremenRedisCache;
- }
- try {
- $redis = redis();
- $raw = $redis->get('procuremen_redis');
- if ($raw === false || $raw === '') {
- $this->procuremenRedisCache = [];
- return $this->procuremenRedisCache;
- }
- $decoded = json_decode($raw, true);
- if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
- $this->procuremenRedisCache = [];
- return $this->procuremenRedisCache;
- }
- $this->procuremenRedisCache = $decoded['data'];
- return $this->procuremenRedisCache;
- } catch (\Throwable $e) {
- $this->procuremenRedisCache = [];
- return $this->procuremenRedisCache;
- }
- }
- /**
- * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
- *
- * @return array<int, array<string, mixed>>
- */
- protected function procuremenFetchErpPoolFromDb(): array
- {
- try {
- $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
- $endTime = date('Y-m-d 23:59:59');
- $list = Db::table('scydgy')
- ->alias('a')
- ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
- ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
- ->where([
- 'a.bwjg' => 1,
- 'a.iEndBz' => 0,
- 'a.iType' => 0,
- 'a.iStatus' => 10,
- ])
- ->where('a.dStamp', '>=', $startTime)
- ->where('a.dStamp', '<=', $endTime)
- ->order('a.dStamp', 'desc')
- ->select();
- if (!is_array($list)) {
- return [];
- }
- try {
- $redis = redis();
- $payload = [
- 'code' => 200,
- 'msg' => 'success',
- 'data' => $list,
- ];
- $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
- $this->procuremenRedisCache = $list;
- } catch (\Throwable $e) {
- }
- return $list;
- } catch (\Throwable $e) {
- Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
- return [];
- }
- }
- /**
- * Redis 为空时从库补一份缓存(同请求内只尝试一次)
- *
- * @return array<int, array<string, mixed>>
- */
- protected function procuremenEnsureRedisPool(): array
- {
- $pool = $this->ProcuremenRedis();
- if (is_array($pool) && $pool !== []) {
- return $pool;
- }
- static $warmed = false;
- if ($warmed) {
- return is_array($pool) ? $pool : [];
- }
- $warmed = true;
- return $this->procuremenFetchErpPoolFromDb();
- }
- /**
- * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
- *
- * @param array<string, mixed> $row
- */
- protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
- {
- $t = $this->procuremenRowListSortTime($row, $primary);
- if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
- return null;
- }
- $mo = (int)$m[2];
- if ($mo < 1 || $mo > 12) {
- return null;
- }
- return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
- }
- /**
- * @param array<int, array{year:string, months:array}> $sidebar
- * @return array<int, array{year:string, months:array}>
- */
- protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
- {
- $ym = trim($ym);
- if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
- return $sidebar;
- }
- foreach ($sidebar as $block) {
- if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
- continue;
- }
- foreach ($block['months'] as $item) {
- if (is_array($item) && ($item['ym'] ?? '') === $ym) {
- return $sidebar;
- }
- }
- }
- $y = substr($ym, 0, 4);
- $mo = (int)substr($ym, 5, 2);
- $sidebar[] = [
- 'year' => $y,
- 'months' => [['ym' => $ym, 'label' => $mo . '月']],
- ];
- return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
- }
- /**
- * @param array<int, array{year:string, months:array}> $sidebar
- * @return string[]
- */
- protected function flattenProcuremenSidebarYms(array $sidebar): array
- {
- $yms = [];
- foreach ($sidebar as $block) {
- if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
- continue;
- }
- foreach ($block['months'] as $item) {
- if (!is_array($item)) {
- continue;
- }
- $ym = trim((string)($item['ym'] ?? ''));
- if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
- $yms[$ym] = true;
- }
- }
- }
- return array_keys($yms);
- }
- /**
- * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
- */
- protected function GetIndexYearMonths()
- {
- $ymSet = [];
- $pool = $this->procuremenEnsureRedisPool();
- foreach ($pool as $r) {
- if (!is_array($r)) {
- continue;
- }
- $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
- if ($ym !== null) {
- $ymSet[$ym] = true;
- }
- }
- foreach ($this->loadPickManualOrderRows() as $r) {
- if (!is_array($r)) {
- continue;
- }
- $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
- if ($ym !== null) {
- $ymSet[$ym] = true;
- }
- }
- $ymList = array_keys($ymSet);
- if ($ymList === []) {
- $ymList[] = $this->resolveProcuremenDefaultYm('pick');
- }
- return $this->buildYearMonthSidebar($ymList);
- }
- /**
- * @param string[] $ymList 形如 2026-06
- * @return array<int, array{year:string, months:array}>
- */
- protected function buildYearMonthSidebar(array $ymList): array
- {
- rsort($ymList, SORT_STRING);
- $byYear = [];
- foreach ($ymList as $ym) {
- $y = substr($ym, 0, 4);
- $mo = (int)substr($ym, 5, 2);
- if (!isset($byYear[$y])) {
- $byYear[$y] = [];
- }
- $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
- }
- krsort($byYear, SORT_NUMERIC);
- foreach ($byYear as $y => $items) {
- usort($byYear[$y], function ($a, $b) {
- return strcmp($b['ym'], $a['ym']);
- });
- }
- $sidebar = [];
- foreach ($byYear as $y => $months) {
- $sidebar[] = ['year' => $y, 'months' => $months];
- }
- return $sidebar;
- }
- /**
- * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
- */
- protected function GetIssuedOrderYearMonths(string $stage): array
- {
- $ymSet = [];
- try {
- $query = Db::table('purchase_order');
- $this->applyPurchaseOrderNotDeletedWhere($query);
- if ($stage === 'audit') {
- $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
- } elseif ($stage === 'confirm') {
- $this->applyPurchaseOrderConfirmStageWhere($query);
- } else {
- return $this->GetIndexYearMonths();
- }
- $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
- if (is_array($rows)) {
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
- if ($ym !== null) {
- $ymSet[$ym] = true;
- }
- }
- }
- } catch (\Throwable $e) {
- $ymSet = [];
- }
- $ymList = array_keys($ymSet);
- if ($ymList === []) {
- $def = $this->resolveProcuremenDefaultYm($stage);
- $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
- }
- return $this->buildYearMonthSidebar($ymList);
- }
- /**
- * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
- */
- protected function resolveProcuremenDefaultYm(string $stage): string
- {
- if ($stage === 'pick') {
- return date('Y-m');
- }
- try {
- $query = Db::table('purchase_order');
- $this->applyPurchaseOrderNotDeletedWhere($query);
- if ($stage === 'audit') {
- $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
- } elseif ($stage === 'confirm') {
- $this->applyPurchaseOrderConfirmStageWhere($query);
- } else {
- return date('Y-m');
- }
- $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
- if ($latest === null || $latest === '') {
- $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
- }
- $t = $this->formatProcuremenDetailTime($latest);
- if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
- return $m[1] . '-' . $m[2];
- }
- } catch (\Throwable $e) {
- }
- return date('Y-m');
- }
- protected function applyPurchaseOrderNotDeletedWhere($query): void
- {
- $query->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%\')'
- );
- }
- /**
- * 审批列表:wflow_status = 待审批(兼容旧值 2)
- */
- protected function applyPurchaseOrderConfirmStageWhere($query): void
- {
- $vals = ProcuremenStatus::wflowPendingApprovalValues();
- $quoted = [];
- foreach ($vals as $v) {
- $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
- }
- if ($quoted === []) {
- $query->whereRaw('1 = 0');
- return;
- }
- $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
- $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
- }
- /**
- * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
- *
- * @param array<string, mixed> $row
- * @return array<string, mixed>
- */
- protected function normalizePurchaseOrderListTimeRow(array $row): array
- {
- $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
- $pick = trim((string)($row['pick_time'] ?? ''));
- if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
- foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
- $t = trim((string)($row[$key] ?? ''));
- if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
- $row['pick_time'] = $t;
- break;
- }
- }
- }
- return $row;
- }
- /**
- * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
- */
- protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
- {
- if (!in_array($stage, ['audit', 'confirm'], true)) {
- return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
- }
- if ($pool === []) {
- $def = $this->resolveProcuremenDefaultYm($stage);
- return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
- }
- $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
- if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
- return false;
- }
- $monthStart = $ym . '-01 00:00:00';
- $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
- $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
- return $probe !== [];
- };
- if ($tryYm($requestedYm)) {
- return $requestedYm;
- }
- $fallback = $this->resolveProcuremenDefaultYm($stage);
- if ($tryYm($fallback)) {
- return $fallback;
- }
- $bestYm = '';
- $bestTime = '';
- foreach ($pool as $row) {
- if (!is_array($row)) {
- continue;
- }
- $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
- if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
- continue;
- }
- $ymRow = $m[1];
- if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
- $bestTime = $t;
- $bestYm = $ymRow;
- }
- }
- if ($bestYm !== '') {
- return $bestYm;
- }
- return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
- }
- protected function isPurchaseOrderDetailVoid(array $row): bool
- {
- if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
- return true;
- }
- return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
- }
- /**
- * 仅当前有效下发明细(排除废弃归档)
- */
- protected function applyActivePurchaseOrderDetailWhere($query): void
- {
- $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
- ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
- }
- /**
- * @param array<string, mixed> $detailRow
- */
- protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
- {
- if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
- return false;
- }
- $statusName = trim((string)($detailRow['status_name'] ?? ''));
- return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
- }
- /**
- * 废弃退回初选:下发明细标记归档,不物理删除
- *
- * @param array<int, int|string> $scydgyIds
- */
- protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
- {
- $ids = [];
- foreach ($scydgyIds as $sid) {
- $n = (int)$sid;
- if ($this->isValidScydgyRowId($n) || $n < 0) {
- $ids[$n] = true;
- }
- }
- if ($ids === []) {
- return;
- }
- $void = ProcuremenStatus::POD_VOID;
- Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($ids))
- ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
- ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
- ->update([
- 'status' => $void,
- 'status_name' => $void,
- ]);
- }
- /**
- * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
- */
- protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
- {
- $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
- $norm = function (string $col) use ($p): string {
- return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
- };
- $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
- $parts = [];
- foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
- if ($key === 'createtime') {
- $parts[] = $createtime;
- } else {
- $parts[] = $norm($key);
- }
- }
- return 'COALESCE(' . implode(', ', $parts) . ')';
- }
- protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
- {
- $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
- $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
- }
- /**
- * @return array<int, array<string, mixed>>
- */
- protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
- {
- $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
- . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
- try {
- $query = Db::table('purchase_order')->field($fields);
- $this->applyPurchaseOrderNotDeletedWhere($query);
- if ($stage === 'audit') {
- $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
- } elseif ($stage === 'confirm') {
- $this->applyPurchaseOrderConfirmStageWhere($query);
- } else {
- return [];
- }
- $query->order('pick_time', 'desc')->order('id', 'desc');
- if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
- $monthStart = $ym . '-01 00:00:00';
- $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
- $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
- }
- $rows = $query->select();
- } catch (\Throwable $e) {
- Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
- $rows = [];
- }
- return is_array($rows) ? $rows : [];
- }
- /**
- * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
- */
- protected function resolveProcuremenListStage(): string
- {
- $tab = trim((string)$this->request->request('wff_tab', ''));
- if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
- return $tab;
- }
- $action = strtolower((string)$this->request->action());
- if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
- return $action;
- }
- return 'pick';
- }
- protected function assignProcuremenListPage(string $stage, string $pageTitle): void
- {
- $rootTrue = rtrim((string)$this->request->root(true), '/');
- $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
- if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
- $indexPhpRoot = $rootTrue . '/index.php';
- }
- $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
- $defaultYm = $this->resolveProcuremenDefaultYm($stage);
- $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
- $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
- $this->view->assign('defaultYm', $defaultYm);
- $this->view->assign('sidebarYearMonths', $sidebar);
- $this->view->assign('procuremenStage', $stage);
- $this->view->assign('procuremenPageTitle', $pageTitle);
- $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
- $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
- $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
- $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
- }
- /** 协助下发(选工序+供应商,发短信邮件通知报价) */
- public function pick()
- {
- $this->request->filter(['strip_tags', 'trim']);
- if (!$this->request->isAjax()) {
- $this->assignProcuremenListPage('pick', '协助下发');
- return $this->view->fetch('procuremen/index');
- }
- return $this->index();
- }
- /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
- public function audit()
- {
- $this->request->filter(['strip_tags', 'trim']);
- if (!$this->request->isAjax()) {
- $this->assignProcuremenListPage('audit', '确认供应商');
- return $this->view->fetch('procuremen/index');
- }
- return $this->index();
- }
- /** 采购确认(定标) */
- public function confirm()
- {
- $this->request->filter(['strip_tags', 'trim']);
- if (!$this->request->isAjax()) {
- $this->assignProcuremenListPage('confirm', '采购确认');
- return $this->view->fetch('procuremen/index');
- }
- return $this->index();
- }
- /**
- * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
- */
- public function index()
- {
- $this->request->filter(['strip_tags', 'trim']);
- if (!$this->request->isAjax()) {
- $this->assignProcuremenListPage('pick', '协助下发');
- return $this->view->fetch('procuremen/index');
- }
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- list(, $sort, $order, $offset, $limit) = $this->buildparams();
- $limit = max(10, min(500, (int)$limit));
- $ym = $this->request->request('ym', '');
- $ym = is_string($ym) ? trim($ym) : '';
- /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
- $wffTab = $this->resolveProcuremenListStage();
- if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
- $ym = in_array($wffTab, ['audit', 'confirm'], true)
- ? $this->resolveProcuremenDefaultYm($wffTab)
- : date('Y-m');
- }
- if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
- $ym = date('Y-m');
- }
- $monthStart = $ym . '-01 00:00:00';
- $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
- $search = trim((string)$this->request->get('search', ''));
- $hasActiveSearch = ($search !== '');
- if (!$hasActiveSearch) {
- $filterStr = $this->request->get('filter', '');
- if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
- $arr = json_decode($filterStr, true);
- if (is_array($arr) && count($arr) > 0) {
- foreach ($arr as $v) {
- if (is_array($v)) {
- if (array_filter($v, function ($x) {
- return $x !== '' && $x !== null;
- })) {
- $hasActiveSearch = true;
- break;
- }
- } elseif ($v !== '' && $v !== null) {
- $hasActiveSearch = true;
- break;
- }
- }
- }
- }
- }
- $applyMonthRange = !$hasActiveSearch;
- $filterArr = (array)json_decode($this->request->get('filter', ''), true);
- $opArr = (array)json_decode($this->request->get('op', ''), true);
- try {
- $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
- if ($wffTab === 'audit') {
- $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
- $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
- );
- } elseif ($wffTab === 'confirm') {
- $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
- if ($dbRows === []) {
- try {
- $dbRows = Db::table('purchase_order')
- ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
- . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
- ->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%\')')
- ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
- ->order('pick_time', 'desc')->order('id', 'desc')
- ->select();
- } catch (\Throwable $e) {
- Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
- $dbRows = [];
- }
- }
- $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
- if ($pool === []) {
- Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
- }
- } else {
- $pool = $this->procuremenEnsureRedisPool();
- if (!is_array($pool)) {
- $pool = [];
- }
- // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
- $hideSet = $this->loadPickHiddenScydgySet();
- if ($pool !== [] && $hideSet !== []) {
- $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
- if (!is_array($r)) {
- return false;
- }
- $id = (int)($r['ID'] ?? $r['id'] ?? 0);
- return $id <= 0 || !isset($hideSet[$id]);
- }));
- }
- $manualPool = $this->loadPickManualOrderRows();
- if ($manualPool !== []) {
- $pool = array_merge($pool, $manualPool);
- }
- if ($pool === []) {
- return json([
- 'total' => 0,
- 'rows' => [],
- ]);
- }
- }
- if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
- $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
- $monthStart = $ym . '-01 00:00:00';
- $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
- }
- $filtered = $this->filterProcuremenIndexPool(
- $pool,
- $monthStart,
- $monthEnd,
- $applyMonthRange,
- $search,
- $filterArr,
- $opArr,
- $listTimePrimary
- );
- /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
- if (in_array($wffTab, ['audit', 'confirm'], true)) {
- $filtered = $this->collapseProcuremenPoolByOrder($filtered);
- }
- $sortField = 'ID';
- if (is_string($sort) && $sort !== '') {
- $parts = explode(',', $sort);
- $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
- if ($sortField === '') {
- $sortField = 'ID';
- }
- }
- $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
- $nFiltered = count($filtered);
- if ($nFiltered > 1) {
- if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
- usort($filtered, function ($a, $b) use ($sortField, $ord) {
- $ta = $this->procuremenRowListSortTime($a, $sortField);
- $tb = $this->procuremenRowListSortTime($b, $sortField);
- if ($ta === $tb) {
- return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
- }
- if ($ta === '') {
- return 1;
- }
- if ($tb === '') {
- return -1;
- }
- return strcmp($ta, $tb) * $ord;
- });
- } elseif ($sortField === 'ID') {
- $sortKeys = [];
- foreach ($filtered as $i => $row) {
- $sortKeys[$i] = (int)($row['ID'] ?? 0);
- }
- $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
- array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
- } elseif ($sortField === 'CCYDH') {
- usort($filtered, function ($a, $b) use ($ord) {
- $sa = trim((string)($a['CCYDH'] ?? ''));
- $sb = trim((string)($b['CCYDH'] ?? ''));
- if ($sa === $sb) {
- return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
- }
- if ($sa === '') {
- return 1;
- }
- if ($sb === '') {
- return -1;
- }
- return strcmp($sa, $sb) * $ord;
- });
- } else {
- usort($filtered, function ($a, $b) use ($sortField, $ord) {
- $va = $a[$sortField] ?? null;
- $vb = $b[$sortField] ?? null;
- $sa = (string)$va;
- $sb = (string)$vb;
- if ($sa === $sb) {
- return 0;
- }
- return strcmp($sa, $sb) * $ord;
- });
- }
- }
- $offset = max(0, (int)$offset);
- $limit = max(1, (int)$limit);
- $rows = array_slice($filtered, $offset, $limit);
- foreach ($rows as &$rw) {
- if (!is_array($rw)) {
- continue;
- }
- $rid = (int)($rw['ID'] ?? 0);
- $rw['_iss_out'] = ($wffTab !== 'pick');
- }
- unset($rw);
- if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
- $idList = [];
- foreach ($rows as $rw) {
- if (!is_array($rw)) {
- continue;
- }
- if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
- foreach ($rw['_order_merge_rows'] as $mr) {
- $mid = (int)($mr['ID'] ?? 0);
- if ($this->isValidScydgyRowId($mid)) {
- $idList[$mid] = true;
- }
- }
- }
- $id = (int)($rw['ID'] ?? 0);
- if ($this->isValidScydgyRowId($id)) {
- $idList[$id] = true;
- }
- }
- $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
- foreach ($rows as &$rw) {
- if (!is_array($rw)) {
- continue;
- }
- $mergeIds = [];
- if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
- foreach ($rw['_order_merge_rows'] as $mr) {
- $mid = (int)($mr['ID'] ?? 0);
- if ($this->isValidScydgyRowId($mid)) {
- $mergeIds[$mid] = true;
- }
- }
- }
- $rid = (int)($rw['ID'] ?? 0);
- if ($this->isValidScydgyRowId($rid)) {
- $mergeIds[$rid] = true;
- }
- $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
- $rw['po_detail_count'] = $s['cnt'];
- $rw['po_amount_fill_cnt'] = $s['amt'];
- $rw['po_delivery_fill_cnt'] = $s['deliv'];
- }
- unset($rw);
- }
- if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
- $idList = [];
- foreach ($rows as $rw) {
- if (!is_array($rw)) {
- continue;
- }
- if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
- foreach ($rw['_order_merge_rows'] as $mr) {
- $mid = (int)($mr['ID'] ?? 0);
- if ($this->isValidScydgyRowId($mid)) {
- $idList[$mid] = true;
- }
- }
- }
- $id = (int)($rw['ID'] ?? 0);
- if ($this->isValidScydgyRowId($id)) {
- $idList[$id] = true;
- }
- }
- $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
- foreach ($rows as &$rw) {
- if (!is_array($rw)) {
- continue;
- }
- $mergeIds = [];
- if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
- foreach ($rw['_order_merge_rows'] as $mr) {
- $mid = (int)($mr['ID'] ?? 0);
- if ($this->isValidScydgyRowId($mid)) {
- $mergeIds[$mid] = true;
- }
- }
- }
- $rid = (int)($rw['ID'] ?? 0);
- if ($this->isValidScydgyRowId($rid)) {
- $mergeIds[$rid] = true;
- }
- $buckets = [];
- foreach (array_keys($mergeIds) as $mid) {
- if (isset($quoteBucket[$mid])) {
- $buckets[] = $quoteBucket[$mid];
- }
- }
- $supplierText = $buckets !== []
- ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
- : '';
- if ($wffTab === 'confirm') {
- $rw['picked_supplier_name'] = $supplierText;
- } else {
- $rw['notify_supplier_text'] = $supplierText;
- }
- }
- unset($rw);
- }
- if ($wffTab === 'all' && count($rows) > 0) {
- $this->mergePurchaseOrder($rows);
- }
- if ($wffTab === 'pick' && count($rows) > 0) {
- $this->mergePurchaseOrder($rows);
- }
- foreach ($rows as &$rwClean) {
- if (is_array($rwClean)) {
- unset($rwClean['_order_merge_rows']);
- if (array_key_exists('NGZL', $rwClean)) {
- $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
- }
- }
- }
- unset($rwClean);
- return json([
- 'total' => count($filtered),
- 'rows' => $rows,
- 'activeYm' => $ym,
- ]);
- } catch (\Throwable $e) {
- Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
- return json([
- 'total' => 0,
- 'rows' => [],
- ]);
- }
- }
- /**
- * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
- *
- * @return array<int, true>
- */
- protected function loadPickHiddenScydgySet(): array
- {
- if ($this->pickHiddenScydgySetCache !== null) {
- return $this->pickHiddenScydgySetCache;
- }
- $hideSet = [];
- try {
- $poIds = Db::table('purchase_order')
- ->where(function ($q) {
- $q->whereIn('wflow_status', array_merge(
- ProcuremenStatus::wflowPendingConfirmValues(),
- ProcuremenStatus::wflowPendingApprovalValues()
- ))
- ->whereOr(function ($q1) {
- $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
- })
- ->whereOr(function ($q2) {
- $q2->whereNotNull('pick_time')
- ->where('pick_time', '<>', '')
- ->where('pick_time', '<>', '0000-00-00 00:00:00');
- })
- ->whereOr(function ($q3) {
- $q3->whereNotNull('mod_rq')
- ->where('mod_rq', '<>', '')
- ->where('mod_rq', 'not like', '0000-00-00%');
- });
- })
- ->column('scydgy_id');
- if (is_array($poIds)) {
- foreach ($poIds as $pid) {
- $k = (int)$pid;
- if ($k !== 0) {
- $hideSet[$k] = true;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- try {
- $detIdsQuery = Db::table('purchase_order_detail');
- $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
- $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
- if (is_array($detIds)) {
- foreach ($detIds as $pid) {
- $k = (int)$pid;
- if ($this->isValidScydgyRowId($k)) {
- $hideSet[$k] = true;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- $this->pickHiddenScydgySetCache = $hideSet;
- return $hideSet;
- }
- /**
- * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
- *
- * @return array<int, array<string, mixed>>
- */
- protected function loadPickManualOrderRows(): array
- {
- try {
- $dbRows = Db::table('purchase_order')
- ->where('scydgy_id', '<', 0)
- ->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%\')')
- ->order('scydgy_id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- try {
- $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
- } catch (\Throwable $e2) {
- return [];
- }
- }
- if (!is_array($dbRows) || $dbRows === []) {
- return [];
- }
- $detailSidSet = [];
- try {
- $negIds = [];
- foreach ($dbRows as $dbRow) {
- if (!is_array($dbRow)) {
- continue;
- }
- $sid = (int)($dbRow['scydgy_id'] ?? 0);
- if ($sid < 0) {
- $negIds[$sid] = true;
- }
- }
- if ($negIds !== []) {
- $detQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($negIds));
- $this->applyActivePurchaseOrderDetailWhere($detQuery);
- $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
- if (is_array($detRows)) {
- foreach ($detRows as $did) {
- $detailSidSet[(int)$did] = true;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- $pool = [];
- foreach ($dbRows as $dbRow) {
- if (!is_array($dbRow)) {
- continue;
- }
- $sid = (int)($dbRow['scydgy_id'] ?? 0);
- if ($sid >= 0) {
- continue;
- }
- $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
- if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
- continue;
- }
- $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
- if ($st === ProcuremenStatus::PO_COMPLETED || $st === ProcuremenStatus::PO_IN_PROGRESS) {
- continue;
- }
- if (isset($detailSidSet[$sid])) {
- continue;
- }
- $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
- $r['_is_manual'] = 1;
- $pool[] = $r;
- }
- return $pool;
- }
- /**
- * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
- */
- protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
- {
- $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
- foreach ($keys as $k) {
- $t = trim((string)($row[$k] ?? ''));
- if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
- return $t;
- }
- }
- return '';
- }
- /**
- * 分配手工新增工序行 ID(负数递减)
- */
- protected function allocateManualScydgyId(): int
- {
- try {
- $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
- $min = (int)$min;
- return $min < 0 ? $min - 1 : -1;
- } catch (\Throwable $e) {
- return -1;
- }
- }
- /**
- * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
- */
- protected function allocateManualOrderCcydh(): string
- {
- $prefix = 'YW' . date('Ymd');
- $maxSeq = 0;
- try {
- $rows = Db::table('purchase_order')
- ->where('CCYDH', 'like', $prefix . '%')
- ->column('CCYDH');
- if (is_array($rows)) {
- foreach ($rows as $ccydh) {
- $ccydh = trim((string)$ccydh);
- if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
- $maxSeq = max($maxSeq, (int)$m[1]);
- }
- }
- }
- } catch (\Throwable $e) {
- }
- return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
- }
- /**
- * purchase_order.mod_rq 是否有有效软删除时间
- */
- protected function isPurchaseOrderSoftDeleted($modRq): bool
- {
- $t = trim((string)$modRq);
- return $t !== '' && stripos($t, '0000-00-00') !== 0;
- }
- /**
- * 列表行 → purchase_order 写入字段
- *
- * @return array<string, mixed>
- */
- protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
- {
- return [
- 'scydgy_id' => $scydgyId,
- 'CCYDH' => $row['CCYDH'] ?? null,
- 'CYJMC' => $row['CYJMC'] ?? null,
- 'CCLBMMC' => $row['CCLBMMC'] ?? null,
- 'CDXMC' => $row['CDXMC'] ?? null,
- 'CGYBH' => $row['CGYBH'] ?? null,
- 'CGYMC' => $row['CGYMC'] ?? null,
- 'CDW' => $row['CDW'] ?? null,
- 'NGZL' => $row['NGZL'] ?? null,
- 'CDF' => $row['CDF'] ?? null,
- 'cGzzxMc' => $row['cGzzxMc'] ?? null,
- 'MBZ' => $row['MBZ'] ?? null,
- 'bwjg' => $row['bwjg'] ?? null,
- 'iStatus' => $row['iStatus'] ?? null,
- 'dStamp' => $row['dStamp'] ?? null,
- 'dputrecord' => $row['dputrecord'] ?? null,
- 'cywyxm' => $row['cywyxm'] ?? null,
- 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
- 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
- ];
- }
- /**
- * 初选行对应的 purchase_order 与是否应从初选列表隐藏
- *
- * @return array{po:?array<string,mixed>, hidden:bool}
- */
- protected function resolvePickRowPoContext(int $sid): array
- {
- $po = null;
- try {
- $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- if (is_array($found)) {
- $po = $found;
- }
- } catch (\Throwable $e) {
- }
- $hideSet = $this->loadPickHiddenScydgySet();
- return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
- }
- /**
- * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
- */
- protected function assertPickRowCanDelete(int $sid, array $row): void
- {
- $ctx = $this->resolvePickRowPoContext($sid);
- $po = $ctx['po'];
- if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
- return;
- }
- if (is_array($po)) {
- if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
- throw new \InvalidArgumentException('该工序已完结,无法删除');
- }
- if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
- throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
- }
- }
- if ($ctx['hidden']) {
- $ccydh = trim((string)($row['CCYDH'] ?? ''));
- $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
- throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
- }
- }
- /**
- * 初选直接完结前校验
- */
- protected function assertPickRowCanComplete(int $sid, array $row): void
- {
- $ctx = $this->resolvePickRowPoContext($sid);
- $po = $ctx['po'];
- if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
- throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
- }
- if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
- throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
- }
- if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
- throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
- }
- }
- /**
- * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
- */
- protected function softDeleteProcuremenPickRow(array $row): void
- {
- $sid = $this->extractScydgyRowId($row);
- if (!$this->isValidScydgyRowId($sid)) {
- throw new \InvalidArgumentException('无效的行主键');
- }
- $this->assertPickRowCanDelete($sid, $row);
- $po = $this->resolvePickRowPoContext($sid)['po'];
- if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
- return;
- }
- if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
- throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
- }
- $now = date('Y-m-d H:i:s');
- $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- if (is_array($exists)) {
- Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
- $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
- } else {
- $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
- $data['mod_rq'] = $now;
- $data['createtime'] = $now;
- Db::table('purchase_order')->insert($data);
- $poIdLog = (int)Db::getLastInsID();
- }
- $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
- $gymcLog = trim((string)($row['CGYMC'] ?? ''));
- $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
- if ($gymcLog !== '') {
- $logTail .= ' / ' . $gymcLog;
- }
- $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
- }
- /**
- * 手工新增协助工序(写入 purchase_order)
- *
- * @param array<string, mixed> $params
- * @return int scydgy_id
- */
- protected function saveManualPickOrder(array $params): int
- {
- $cyjmc = trim((string)($params['CYJMC'] ?? ''));
- $cgymc = trim((string)($params['CGYMC'] ?? ''));
- $ccydh = trim((string)($params['CCYDH'] ?? ''));
- if ($ccydh === '') {
- $ccydh = $this->allocateManualOrderCcydh();
- }
- $now = date('Y-m-d H:i:s');
- $sid = $this->allocateManualScydgyId();
- $data = [
- 'scydgy_id' => $sid,
- 'CCYDH' => $ccydh,
- 'CYJMC' => $cyjmc,
- 'CGYMC' => $cgymc,
- 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
- 'CDW' => trim((string)($params['CDW'] ?? '')),
- 'NGZL' => trim((string)($params['NGZL'] ?? '')),
- 'CDF' => trim((string)($params['CDF'] ?? '')),
- 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
- 'MBZ' => trim((string)($params['MBZ'] ?? '')),
- 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
- 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
- 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
- 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
- 'createtime' => $now,
- 'dStamp' => $now,
- 'dputrecord' => $now,
- ];
- Db::table('purchase_order')->insert($data);
- $poId = (int)Db::getLastInsID();
- $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
- return $sid;
- }
- protected function formatProcuremenRowLabel(array $row): string
- {
- $dh = trim((string)($row['CCYDH'] ?? ''));
- $gymc = trim((string)($row['CGYMC'] ?? ''));
- if ($dh !== '' && $gymc !== '') {
- return '订单「' . $dh . '」、工序「' . $gymc . '」';
- }
- if ($dh !== '') {
- return '订单「' . $dh . '」';
- }
- if ($gymc !== '') {
- return '工序「' . $gymc . '」';
- }
- $id = $this->extractScydgyRowId($row);
- return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
- }
- /**
- * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
- */
- protected function extractScydgyRowId(array $row): int
- {
- return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
- }
- protected function isValidScydgyRowId(int $id): bool
- {
- return ProcuremenGuard::isValidScydgyId($id);
- }
- protected function isManualScydgyRowId(int $id): bool
- {
- return $id < 0;
- }
- /**
- * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
- *
- * @param int[] $scydgyIds
- * @return array<int, string[]>
- */
- protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
- {
- $out = [];
- $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
- if ($scydgyIds === []) {
- return $out;
- }
- try {
- $rows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', $scydgyIds)
- ->field('scydgy_id,company_name')
- ->order('company_name', 'asc')
- ->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- if (!is_array($rows)) {
- return $out;
- }
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- $cn = trim((string)($r['company_name'] ?? ''));
- if (!$this->isValidScydgyRowId($sid) || $cn === '') {
- continue;
- }
- if (!isset($out[$sid])) {
- $out[$sid] = [];
- }
- if (!in_array($cn, $out[$sid], true)) {
- $out[$sid][] = $cn;
- }
- }
- return $out;
- }
- /**
- * 列表展示通知供应商(完整列表,前端单行省略展开)
- *
- * @param string[] $names
- */
- protected function formatNotifySupplierDisplay(array $names): string
- {
- $names = array_values(array_unique(array_filter(array_map(function ($n) {
- return trim((string)$n);
- }, $names))));
- if ($names === []) {
- return '';
- }
- sort($names, SORT_STRING);
- return implode("\n", $names);
- }
- /**
- * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
- *
- * @param int[] $scydgyIds
- * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
- */
- protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
- {
- $out = [];
- $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
- if ($scydgyIds === []) {
- return $out;
- }
- try {
- $rows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', $scydgyIds)
- ->field('scydgy_id,company_name,amount')
- ->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- if (!is_array($rows)) {
- return $out;
- }
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- $cn = trim((string)($r['company_name'] ?? ''));
- if (!$this->isValidScydgyRowId($sid) || $cn === '') {
- continue;
- }
- if (!isset($out[$sid])) {
- $out[$sid] = ['all' => [], 'quoted' => []];
- }
- $out[$sid]['all'][$cn] = true;
- $am = trim((string)($r['amount'] ?? ''));
- if ($am !== '' && $am !== '0' && $am !== '0.00') {
- $out[$sid]['quoted'][$cn] = true;
- }
- }
- return $out;
- }
- /**
- * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
- * @return array{all: array<string, bool>, quoted: array<string, bool>}
- */
- protected function mergeQuotedSupplierBuckets(array $buckets): array
- {
- $merged = ['all' => [], 'quoted' => []];
- foreach ($buckets as $b) {
- if (!is_array($b)) {
- continue;
- }
- foreach ($b['all'] ?? [] as $cn => $_) {
- $merged['all'][$cn] = true;
- }
- foreach ($b['quoted'] ?? [] as $cn => $_) {
- $merged['quoted'][$cn] = true;
- }
- }
- return $merged;
- }
- /**
- * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
- */
- protected function formatQuotedSupplierLines(array $bucket): string
- {
- $all = array_keys($bucket['all'] ?? []);
- if ($all === []) {
- return '';
- }
- sort($all, SORT_STRING);
- $lines = [];
- foreach ($all as $cn) {
- $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
- $lines[] = $cn . '(' . $status . ')';
- }
- return implode("\n", $lines);
- }
- /**
- * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
- */
- protected function resolveBundleSysRq(array $bundle): string
- {
- foreach ($bundle['pos'] ?? [] as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sr = trim((string)($po['sys_rq'] ?? ''));
- if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
- return $sr;
- }
- }
- return '';
- }
- /**
- * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
- */
- protected function isProcuremenQuoteDeadlineReached($sysRq): bool
- {
- $raw = trim((string)$sysRq);
- if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
- return true;
- }
- $ts = strtotime(str_replace('T', ' ', $raw));
- if ($ts === false || $ts <= 0) {
- return true;
- }
- return time() >= $ts;
- }
- /**
- * 截止时间前:隐藏单价/交期真实值,统一展示文案
- *
- * @param array<string, mixed> $line
- */
- protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
- {
- $amountFilled = !empty($line['amount_filled']);
- $deliveryFilled = !empty($line['delivery_filled']);
- $line['unit_price_text'] = $amountFilled ? '未到截止时间' : '未填写';
- $line['amount_show'] = '';
- if (array_key_exists('amount_text', $line)) {
- $line['amount_text'] = $line['unit_price_text'];
- }
- $deliveryText = $deliveryFilled ? '未到截止时间' : '未填写';
- $line['delivery_show'] = $deliveryText;
- if (array_key_exists('delivery_text', $line)) {
- $line['delivery_text'] = $deliveryText;
- }
- $line['delivery_ymd'] = '';
- $line['subtotal_text'] = $amountFilled ? '未到截止时间' : '';
- $line['subtotal_num'] = null;
- $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
- $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
- $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled) ? 1 : 0;
- $line['amount_filled'] = false;
- $line['delivery_filled'] = false;
- $line['is_quoted'] = false;
- if (array_key_exists('quote_label', $line)) {
- $line['quote_label'] = ($amountFilled || $deliveryFilled) ? '未到截止时间' : '未报价';
- }
- }
- /**
- * 报价行展示字段默认值(模板安全访问)
- *
- * @param array<string, mixed> $line
- * @return array<string, mixed>
- */
- protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
- {
- if (!array_key_exists('amount_quote_pending', $line)) {
- $line['amount_quote_pending'] = 0;
- }
- if (!array_key_exists('delivery_quote_pending', $line)) {
- $line['delivery_quote_pending'] = 0;
- }
- if (!array_key_exists('quote_before_deadline', $line)) {
- $line['quote_before_deadline'] = 0;
- }
- if (!array_key_exists('amount_filled', $line)) {
- $line['amount_filled'] = 0;
- }
- if (!array_key_exists('delivery_filled', $line)) {
- $line['delivery_filled'] = 0;
- }
- return $line;
- }
- /**
- * 审核弹窗:按供应商汇总报价明细
- *
- * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
- * @return array<int, array<string, mixed>>
- */
- protected function loadAuditSupplierQuoteGroups(array $bundle): array
- {
- $sids = [];
- foreach ($bundle['pos'] ?? [] as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $sids[$sid] = true;
- }
- }
- if ($sids === []) {
- return [];
- }
- $deadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle));
- $gymcMap = [];
- $qtyBySid = [];
- foreach ($bundle['merge_rows'] ?? [] as $mr) {
- if (!is_array($mr)) {
- continue;
- }
- $gid = $this->extractScydgyRowId($mr);
- if ($this->isValidScydgyRowId($gid)) {
- $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
- $qty = trim((string)($mr['This_quantity'] ?? ''));
- if ($qty === '') {
- $qty = trim((string)($mr['NGZL'] ?? ''));
- }
- $qtyBySid[$gid] = $qty;
- }
- }
- foreach ($bundle['pos'] ?? [] as $po) {
- if (!is_array($po)) {
- continue;
- }
- $gid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($gid)) {
- $nm = trim((string)($po['CGYMC'] ?? ''));
- if ($nm !== '') {
- $gymcMap[$gid] = $nm;
- }
- }
- }
- try {
- $detailsQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids));
- $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
- $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
- } catch (\Throwable $e) {
- try {
- $detailsQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids));
- $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
- $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
- } catch (\Throwable $e2) {
- $details = [];
- }
- }
- if (!is_array($details)) {
- $details = [];
- }
- $byCompany = [];
- foreach ($details as $d) {
- if (!is_array($d)) {
- continue;
- }
- $cn = trim((string)($d['company_name'] ?? ''));
- if ($cn === '') {
- continue;
- }
- if (!isset($byCompany[$cn])) {
- $ph = trim((string)($d['phone'] ?? ''));
- $username = trim((string)($d['username'] ?? ''));
- if ($username === '') {
- $username = $this->resolveCustomerContactName($ph, $cn);
- }
- $byCompany[$cn] = [
- 'name' => $cn,
- 'email' => trim((string)($d['email'] ?? '')),
- 'phone' => $ph,
- 'username' => $username,
- 'has_quote' => false,
- 'lines' => [],
- ];
- }
- $sid = (int)($d['scydgy_id'] ?? 0);
- $am = trim((string)($d['amount'] ?? ''));
- $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
- if ($gymc === '') {
- $gymc = '工序';
- }
- $deliveryRaw = trim((string)($d['delivery'] ?? ''));
- $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
- if ($deliveryShow === '' && $deliveryRaw !== '') {
- $deliveryShow = $deliveryRaw;
- }
- $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
- $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
- $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
- $subtotal = null;
- if ($amountNum !== null) {
- $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
- }
- $unitPriceText = $amountFilled
- ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
- : '未填写';
- $lineRow = [
- 'cgymc' => $gymc,
- 'amount' => $am,
- 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
- 'amount_filled' => $amountFilled,
- 'unit_price_text' => $unitPriceText,
- 'delivery' => $deliveryRaw,
- 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
- 'delivery_filled' => $deliveryFilled,
- 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
- 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
- 'subtotal_num' => $subtotal,
- 'status_name' => trim((string)($d['status_name'] ?? '')),
- 'is_quoted' => $amountFilled,
- 'quote_label' => $amountFilled ? '已报价' : '未报价',
- ];
- if (!$deadlineReached) {
- $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
- }
- $byCompany[$cn]['lines'][] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
- }
- foreach ($byCompany as $cn => $g) {
- $total = count($g['lines']);
- $quoted = 0;
- $groupTotal = 0.0;
- $groupHasTotal = false;
- if ($deadlineReached) {
- foreach ($g['lines'] as $ln) {
- $am = trim((string)($ln['amount'] ?? ''));
- if ($am !== '' && $am !== '0' && $am !== '0.00') {
- $quoted++;
- }
- if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
- $groupTotal += (float)$ln['subtotal_num'];
- $groupHasTotal = true;
- }
- }
- }
- $byCompany[$cn]['has_quote'] = $deadlineReached && $total > 0 && $quoted === $total;
- $byCompany[$cn]['line_count'] = $total;
- $byCompany[$cn]['has_total'] = $total > 0;
- $byCompany[$cn]['total_text'] = ($deadlineReached && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
- $byCompany[$cn]['display_rowspan'] = $total + ($total > 0 ? 1 : 0);
- }
- return array_values($byCompany);
- }
- /**
- * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
- *
- * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
- * @return array<int, array<string, mixed>>
- */
- protected function loadConfirmSupplierPickGroups(array $bundle): array
- {
- $sids = [];
- $poIdMap = [];
- foreach ($bundle['pos'] ?? [] as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $sids[$sid] = true;
- $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
- }
- }
- if ($sids === []) {
- return [];
- }
- $deadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle));
- $gymcMap = [];
- $qtyBySid = [];
- $orderedSids = [];
- foreach ($bundle['merge_rows'] ?? [] as $mr) {
- if (!is_array($mr)) {
- continue;
- }
- $gid = $this->extractScydgyRowId($mr);
- if ($this->isValidScydgyRowId($gid)) {
- $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
- $orderedSids[] = $gid;
- $qty = trim((string)($mr['This_quantity'] ?? ''));
- if ($qty === '') {
- $qty = trim((string)($mr['NGZL'] ?? ''));
- }
- $qtyBySid[$gid] = $qty;
- }
- }
- foreach ($bundle['pos'] ?? [] as $po) {
- if (!is_array($po)) {
- continue;
- }
- $gid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($gid)) {
- $nm = trim((string)($po['CGYMC'] ?? ''));
- if ($nm !== '') {
- $gymcMap[$gid] = $nm;
- }
- }
- }
- try {
- $details = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->order('company_name', 'asc')
- ->order('id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- try {
- $details = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->order('company_name', 'asc')
- ->order('ID', 'asc')
- ->select();
- } catch (\Throwable $e2) {
- $details = [];
- }
- }
- if (!is_array($details)) {
- $details = [];
- }
- $byCompany = [];
- foreach ($details as $d) {
- if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
- continue;
- }
- $cn = trim((string)($d['company_name'] ?? ''));
- if ($cn === '') {
- continue;
- }
- $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
- $sid = (int)($d['scydgy_id'] ?? 0);
- if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
- continue;
- }
- if (!isset($byCompany[$cn])) {
- $ph = trim((string)($d['phone'] ?? ''));
- $username = trim((string)($d['username'] ?? ''));
- if ($username === '') {
- $username = $this->resolveCustomerContactName($ph, $cn);
- }
- $byCompany[$cn] = [
- 'name' => $cn,
- 'email' => trim((string)($d['email'] ?? '')),
- 'phone' => $ph,
- 'username' => $username,
- 'pick_lines' => [],
- 'detail_picks' => [],
- ];
- }
- $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
- if ($gymc === '') {
- $gymc = '工序';
- }
- $am = trim((string)($d['amount'] ?? ''));
- $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
- $deliveryRaw = trim((string)($d['delivery'] ?? ''));
- $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
- if ($deliveryShow === '' && $deliveryRaw !== '') {
- $deliveryShow = $deliveryRaw;
- }
- $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
- $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
- $subtotal = null;
- if ($amountNum !== null) {
- $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
- }
- $unitPriceText = $amountFilled
- ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
- : '未填写';
- $pickLine = [
- 'cgymc' => $gymc,
- 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
- 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
- 'amount_filled' => $amountFilled,
- 'delivery_filled' => $deliveryFilled,
- 'unit_price_text' => $unitPriceText,
- 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
- 'subtotal_num' => $subtotal,
- 'is_quoted' => $amountFilled,
- ];
- if (!$deadlineReached) {
- $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
- }
- $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
- $byCompany[$cn]['detail_picks'][$sid] = [
- 'scydgy_id' => $sid,
- 'detail_id' => $detailId,
- 'purchase_order_id' => $poIdMap[$sid] ?? 0,
- 'cgymc' => $gymc,
- ];
- }
- $out = [];
- foreach ($byCompany as $g) {
- $pickLinesMap = $g['pick_lines'] ?? [];
- if (!is_array($pickLinesMap) || $pickLinesMap === []) {
- continue;
- }
- $pickLines = [];
- $usedLineSids = [];
- foreach ($orderedSids as $sid) {
- if (!isset($pickLinesMap[$sid])) {
- continue;
- }
- $pickLines[] = $pickLinesMap[$sid];
- $usedLineSids[$sid] = true;
- }
- foreach ($pickLinesMap as $sid => $ln) {
- if (isset($usedLineSids[$sid])) {
- continue;
- }
- $pickLines[] = $ln;
- }
- $groupTotal = 0.0;
- $groupHasTotal = false;
- if ($deadlineReached) {
- foreach ($pickLines as $ln) {
- if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
- $groupTotal += (float)$ln['subtotal_num'];
- $groupHasTotal = true;
- }
- }
- }
- $lineCount = count($pickLines);
- $g['pick_lines'] = $pickLines;
- $g['line_count'] = $lineCount;
- $g['has_total'] = $lineCount > 0;
- $g['total_text'] = ($deadlineReached && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
- $g['display_rowspan'] = $lineCount + ($lineCount > 0 ? 1 : 0);
- $detailPicks = $g['detail_picks'] ?? [];
- $g['detail_picks'] = array_values(is_array($detailPicks) ? $detailPicks : []);
- $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
- unset($g['detail_picks']);
- $out[] = $g;
- }
- return $out;
- }
- /**
- * @param array<int, array<string, mixed>> $details purchase_order_detail 行
- * @return array<int, int[]> scydgy_id => detail_id[]
- */
- protected function mapDetailIdsByScydgyId(array $details): array
- {
- $out = [];
- foreach ($details as $d) {
- if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
- continue;
- }
- $sid = (int)($d['scydgy_id'] ?? 0);
- $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
- if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
- continue;
- }
- if (!isset($out[$sid])) {
- $out[$sid] = [];
- }
- $out[$sid][] = $pk;
- }
- foreach ($out as $sid => $ids) {
- $out[$sid] = array_values(array_unique($ids));
- }
- return $out;
- }
- /**
- * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
- *
- * @param array<string, mixed> $dbRow
- * @param array<int, mixed> $dStampMap scydgy_id => dStamp
- */
- protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
- {
- $sid = (int)($dbRow['scydgy_id'] ?? 0);
- $r = [
- 'ID' => $sid,
- 'CCYDH' => $dbRow['CCYDH'] ?? '',
- 'CYJMC' => $dbRow['CYJMC'] ?? '',
- 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
- 'CDXMC' => $dbRow['CDXMC'] ?? '',
- 'CGYBH' => $dbRow['CGYBH'] ?? '',
- 'CGYMC' => $dbRow['CGYMC'] ?? '',
- 'CDW' => $dbRow['CDW'] ?? '',
- 'NGZL' => $dbRow['NGZL'] ?? '',
- 'CDF' => $dbRow['CDF'] ?? '',
- 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
- 'MBZ' => $dbRow['MBZ'] ?? '',
- 'bwjg' => $dbRow['bwjg'] ?? '',
- 'iStatus' => $dbRow['iStatus'] ?? '',
- 'dputrecord' => $dbRow['dputrecord'] ?? '',
- 'cywyxm' => $dbRow['cywyxm'] ?? '',
- 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
- 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
- 'dStamp' => $dbRow['dStamp'] ?? '',
- 'pick_time' => $dbRow['pick_time'] ?? '',
- ];
- if ($sid > 0 && isset($dStampMap[$sid])) {
- $t = trim((string)$dStampMap[$sid]);
- if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
- $r['dStamp'] = $dStampMap[$sid];
- }
- }
- $dsOut = trim((string)($r['dStamp'] ?? ''));
- if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
- $ct = $dbRow['createtime'];
- if (is_numeric($ct) && (int)$ct > 946684800) {
- $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
- } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
- $r['dStamp'] = trim($ct);
- }
- }
- // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
- $dpOut = trim((string)($r['dputrecord'] ?? ''));
- if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
- $fallback = trim((string)($r['dStamp'] ?? ''));
- if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
- $r['dputrecord'] = $fallback;
- }
- }
- if (array_key_exists('id', $dbRow)) {
- $r['purchase_order_id'] = (int)$dbRow['id'];
- }
- if ($sid < 0) {
- $r['_is_manual'] = 1;
- }
- $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
- $pickOut = trim((string)($r['pick_time'] ?? ''));
- if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
- foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
- $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
- if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
- $r['pick_time'] = $pickFallback;
- break;
- }
- }
- }
- $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
- if ($pickNm !== '') {
- $r['pick_company_name'] = $pickNm;
- $r['picked_supplier_name'] = $pickNm;
- }
- return $r;
- }
- /**
- * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
- *
- * @return array<int, array<string, mixed>>
- */
- protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
- {
- $pool = [];
- if (!is_array($dbRows) || $dbRows === []) {
- return $pool;
- }
- $dStampMap = [];
- $sidList = [];
- foreach ($dbRows as $tmpRow) {
- if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
- $sid = (int)$tmpRow['scydgy_id'];
- if ($sid > 0) {
- $ds = trim((string)($tmpRow['dStamp'] ?? ''));
- if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
- $sidList[$sid] = true;
- }
- }
- }
- }
- if ($sidList !== []) {
- try {
- $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
- } catch (\Throwable $e) {
- $dStampMap = [];
- }
- }
- foreach ($dbRows as $dbRow) {
- if (!is_array($dbRow)) {
- continue;
- }
- $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
- }
- return $pool;
- }
- /**
- * 批量读取 purchase_order_detail(确认/审批列表统计用)
- *
- * @param int[] $scydgyIds
- * @return array<int, array<string, mixed>>
- */
- protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
- {
- $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
- if ($scydgyIds === []) {
- return [];
- }
- try {
- $list = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', $scydgyIds)
- ->field('scydgy_id,company_name,amount,delivery')
- ->select();
- } catch (\Throwable $e) {
- $list = [];
- }
- return is_array($list) ? $list : [];
- }
- /**
- * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
- *
- * @param int[] $scydgyIds
- * @param array<int, array<string, mixed>> $allRows
- * @return array{cnt:int, amt:int, deliv:int}
- */
- protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
- {
- $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
- $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
- if ($scydgyIds === [] || $allRows === []) {
- return $out;
- }
- $idSet = array_flip($scydgyIds);
- $all = [];
- $withAmt = [];
- $withDeliv = [];
- foreach ($allRows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- if (!isset($idSet[$sid])) {
- continue;
- }
- $cn = trim((string)($r['company_name'] ?? ''));
- if ($cn === '') {
- continue;
- }
- $all[$cn] = true;
- $am = $r['amount'] ?? null;
- if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
- $withAmt[$cn] = true;
- }
- $dv = $r['delivery'] ?? null;
- if ($dv !== null && trim((string)$dv) !== '') {
- $withDeliv[$cn] = true;
- }
- }
- return [
- 'cnt' => count($all),
- 'amt' => count($withAmt),
- 'deliv' => count($withDeliv),
- ];
- }
- /**
- * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
- *
- * @param int[] $scydgyIds
- * @return array<int, array{cnt:int, amt:int, deliv:int}>
- * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
- */
- protected function OrderDetailSummary(array $scydgyIds)
- {
- $out = [];
- $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
- if ($scydgyIds === []) {
- return $out;
- }
- $list = [];
- try {
- $list = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', $scydgyIds)
- ->field('id,scydgy_id,amount,delivery')
- ->select();
- } catch (\Throwable $e) {
- $list = [];
- }
- if (!is_array($list)) {
- return $out;
- }
- foreach ($list as $r) {
- if (!is_array($r)) {
- continue;
- }
- $ids = (int)($r['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($ids)) {
- continue;
- }
- if (!isset($out[$ids])) {
- $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
- }
- $out[$ids]['cnt']++;
- $am = $r['amount'] ?? null;
- if ($am !== null && $am !== '') {
- if (!(is_string($am) && trim($am) === '')) {
- $out[$ids]['amt']++;
- }
- }
- $dv = $r['delivery'] ?? null;
- if ($dv !== null && trim((string)$dv) !== '') {
- $out[$ids]['deliv']++;
- }
- }
- return $out;
- }
- /**
- * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
- *
- * @return array
- */
- protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
- {
- $strContains = function ($haystack, $needle) {
- if ($needle === '') {
- return false;
- }
- $haystack = (string)$haystack;
- if (function_exists('mb_stripos')) {
- return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
- }
- return stripos($haystack, $needle) !== false;
- };
- $stripAlias = function ($f) {
- return preg_replace('/^[ab]\./i', '', (string)$f);
- };
- $searchColNames = [];
- foreach (explode(',', $this->searchFields) as $colRaw) {
- $c = $stripAlias(trim($colRaw));
- if ($c !== '') {
- $searchColNames[] = $c;
- }
- }
- $filtered = [];
- foreach ($pool as $r) {
- if (!is_array($r)) {
- continue;
- }
- $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
- $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
- if (!$isManual) {
- if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
- || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
- continue;
- }
- if ($applyMonthRange) {
- $mo = (int)$m[2];
- if ($mo < 1 || $mo > 12) {
- continue;
- }
- $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
- $rowMonthStart = $ymRow . '-01 00:00:00';
- $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
- if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
- continue;
- }
- }
- } elseif ($applyMonthRange) {
- $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
- if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
- $ds = $listTime;
- }
- if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
- continue;
- }
- $mo = (int)$m[2];
- if ($mo < 1 || $mo > 12) {
- continue;
- }
- $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
- $rowMonthStart = $ymRow . '-01 00:00:00';
- $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
- if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
- continue;
- }
- }
- if ($search !== '') {
- $hitSearch = false;
- foreach ($searchColNames as $c) {
- $cell = isset($r[$c]) ? (string)$r[$c] : '';
- if ($cell !== '' && $strContains($cell, $search)) {
- $hitSearch = true;
- break;
- }
- }
- if (!$hitSearch) {
- continue;
- }
- }
- foreach ($filterArr as $fk => $fv) {
- if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
- continue;
- }
- if (is_array($fv)) {
- continue;
- }
- if ($fv === '' && $fv !== '0' && $fv !== 0) {
- continue;
- }
- $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
- $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
- $field = $stripAlias($fk);
- $cell = array_key_exists($field, $r) ? $r[$field] : null;
- $cellStr = trim((string)$cell);
- switch ($sym) {
- case '=':
- if ((string)$cell !== (string)$fv) {
- continue 3;
- }
- break;
- case '<>':
- if ((string)$cell === (string)$fv) {
- continue 3;
- }
- break;
- case 'LIKE':
- case 'NOT LIKE':
- $needle = trim((string)$fv);
- $hit = ($needle !== '' && $strContains($cellStr, $needle));
- if ($sym === 'LIKE' && !$hit) {
- continue 3;
- }
- if ($sym === 'NOT LIKE' && $hit) {
- continue 3;
- }
- break;
- case '>':
- case '>=':
- case '<':
- case '<=':
- if (!is_numeric($cell) && $cellStr === '') {
- continue 3;
- }
- $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
- $vv = (float)$fv;
- if ($sym === '>' && !($cv > $vv)) {
- continue 3;
- }
- if ($sym === '>=' && !($cv >= $vv)) {
- continue 3;
- }
- if ($sym === '<' && !($cv < $vv)) {
- continue 3;
- }
- if ($sym === '<=' && !($cv <= $vv)) {
- continue 3;
- }
- break;
- case 'RANGE':
- case 'NOT RANGE':
- case 'BETWEEN':
- case 'NOT BETWEEN':
- case 'BETWEEN TIME':
- case 'NOT BETWEEN TIME':
- $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
- $rawR = str_replace(' - ', ',', $rawR);
- $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
- if (count($arr) < 2) {
- break;
- }
- $lo = $arr[0];
- $hi = $arr[1];
- if ($lo === '' && $hi === '') {
- break;
- }
- $isNot = (strpos($sym, 'NOT') !== false);
- if ($lo === '') {
- $in = ($cellStr !== '' && $cellStr <= $hi);
- if ($isNot ? $in : !$in) {
- continue 3;
- }
- break;
- }
- if ($hi === '') {
- $in = ($cellStr !== '' && $cellStr >= $lo);
- if ($isNot ? $in : !$in) {
- continue 3;
- }
- break;
- }
- $in = ($cellStr >= $lo && $cellStr <= $hi);
- if ($isNot ? $in : !$in) {
- continue 3;
- }
- break;
- case 'NULL':
- case 'IS NULL':
- if ($cell !== null && $cell !== '') {
- continue 3;
- }
- break;
- case 'NOT NULL':
- case 'IS NOT NULL':
- if ($cell === null || $cell === '') {
- continue 3;
- }
- break;
- default:
- break;
- }
- }
- $filtered[] = $r;
- }
- return $filtered;
- }
- /**
- * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
- */
- public function snapshotToProcure()
- {
- if (!$this->request->isPost() || !$this->request->isAjax()) {
- $this->error(__('Invalid parameters'));
- }
- $row = json_decode($this->request->post('row_json', ''), true);
- if (!is_array($row)) {
- $this->error(__('Invalid parameters'));
- }
- try {
- $ids = $this->extractScydgyRowId($row);
- if (!$this->isValidScydgyRowId($ids)) {
- throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
- }
- $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- $data = [
- 'scydgy_id' => $ids,
- 'CCYDH' => $row['CCYDH'] ?? null,
- 'CYJMC' => $row['CYJMC'] ?? null,
- 'CCLBMMC' => $row['CCLBMMC'] ?? null,
- 'CDXMC' => $row['CDXMC'] ?? null,
- 'CGYBH' => $row['CGYBH'] ?? null,
- 'CGYMC' => $row['CGYMC'] ?? null,
- 'CDW' => $row['CDW'] ?? null,
- 'NGZL' => $row['NGZL'] ?? null,
- 'CDF' => $row['CDF'] ?? null,
- 'cGzzxMc' => $row['cGzzxMc'] ?? null,
- 'MBZ' => $row['MBZ'] ?? null,
- 'bwjg' => $row['bwjg'] ?? null,
- 'iStatus' => $row['iStatus'] ?? null,
- 'dStamp' => $row['dStamp'] ?? null,
- 'dputrecord' => $row['dputrecord'] ?? null,
- 'cywyxm' => $row['cywyxm'] ?? null,
- 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
- 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
- ];
- $qtySnap = trim((string)($data['This_quantity'] ?? ''));
- $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
- if (!$exists && $qtySnap === '' && $priceSnap === '') {
- $this->success('操作成功');
- return;
- }
- if ($exists) {
- $upd = $data;
- unset($upd['scydgy_id'], $upd['status']);
- Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
- } else {
- // 新增:不写 status(空/走库默认);仅写创建时间
- $data['createtime'] = date('Y-m-d H:i:s');
- Db::table('purchase_order')->insert($data);
- }
- } catch (\Throwable $e) {
- $this->error($e->getMessage());
- }
- // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
- $this->success('操作成功');
- }
- /**
- * 未发列表
- * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
- * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
- */
- public function completeDirectly()
- {
- if (!$this->request->isPost() || !$this->request->isAjax()) {
- $this->error(__('参数错误'));
- }
- if (!$this->procuremenCanComplete()) {
- $this->error(__('You have no permission'));
- }
- $row = json_decode($this->request->post('row_json', ''), true);
- if (!is_array($row)) {
- $this->error(__('Invalid parameters'));
- }
- $finishRaw = $this->request->post('finish', '1');
- $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
- $poIdLog = null;
- try {
- // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
- $ids = $this->extractScydgyRowId($row);
- if (!$this->isValidScydgyRowId($ids)) {
- throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
- }
- if ($asComplete) {
- $this->assertPickRowCanComplete($ids, $row);
- }
- $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- $data = [
- 'scydgy_id' => $ids,
- 'CCYDH' => $row['CCYDH'] ?? null,
- 'CYJMC' => $row['CYJMC'] ?? null,
- 'CCLBMMC' => $row['CCLBMMC'] ?? null,
- 'CDXMC' => $row['CDXMC'] ?? null,
- 'CGYBH' => $row['CGYBH'] ?? null,
- 'CGYMC' => $row['CGYMC'] ?? null,
- 'CDW' => $row['CDW'] ?? null,
- 'NGZL' => $row['NGZL'] ?? null,
- 'CDF' => $row['CDF'] ?? null,
- 'cGzzxMc' => $row['cGzzxMc'] ?? null,
- 'MBZ' => $row['MBZ'] ?? null,
- 'bwjg' => $row['bwjg'] ?? null,
- 'iStatus' => $row['iStatus'] ?? null,
- 'dStamp' => $row['dStamp'] ?? null,
- 'dputrecord' => $row['dputrecord'] ?? null,
- 'cywyxm' => $row['cywyxm'] ?? null,
- 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
- 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
- ];
- if ($asComplete) {
- $data['status'] = ProcuremenStatus::PO_COMPLETED;
- $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
- }
- $qtyCd = trim((string)($data['This_quantity'] ?? ''));
- $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
- if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
- $this->success('操作成功');
- return;
- }
- if ($exists) {
- $upd = $data;
- unset($upd['scydgy_id']);
- if (!$asComplete) {
- unset($upd['status']);
- }
- Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
- } else {
- // 新增:不写 status;完结时 $data 已含 status=1
- $data['createtime'] = date('Y-m-d H:i:s');
- Db::table('purchase_order')->insert($data);
- }
- } catch (\Throwable $e) {
- $this->error($e->getMessage());
- }
- try {
- $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- if (is_array($rpo)) {
- $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
- $poIdLog = $tid > 0 ? $tid : null;
- }
- } catch (\Throwable $e) {
- $poIdLog = null;
- }
- $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
- $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
- if ($asComplete) {
- $this->addOrderLog(
- $ids,
- 'mark_complete',
- '点击「完结」,已标记为已完结',
- $poIdLog
- );
- try {
- $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
- if ($pdfPublicPath === '') {
- Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
- }
- } catch (\Throwable $e) {
- Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
- }
- } else {
- $this->addOrderLog(
- $ids,
- 'save_qty_price',
- '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
- $poIdLog
- );
- }
- $this->pickHiddenScydgySetCache = null;
- $this->success("操作成功");
- }
- /**
- * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
- *
- * @param array<int, array> $rows 引用传递当前页行
- */
- protected function mergePurchaseOrder(array &$rows)
- {
- if ($rows === []) {
- return;
- }
- $ids = [];
- foreach ($rows as $rw) {
- if (!is_array($rw)) {
- continue;
- }
- $id = (int)($rw['ID'] ?? 0);
- if ($id > 0) {
- $ids[$id] = true;
- }
- }
- $idList = array_keys($ids);
- if ($idList === []) {
- return;
- }
- try {
- $list = Db::table('purchase_order')
- ->where('scydgy_id', 'in', $idList)
- ->field('scydgy_id,This_quantity,ceilingPrice')
- ->select();
- } catch (\Throwable $e) {
- return;
- }
- if (!is_array($list)) {
- return;
- }
- $byId = [];
- foreach ($list as $dbRow) {
- if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
- continue;
- }
- $byId[(int)$dbRow['scydgy_id']] = $dbRow;
- }
- foreach ($rows as &$rw) {
- if (!is_array($rw)) {
- continue;
- }
- $sid = (int)($rw['ID'] ?? 0);
- if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
- continue;
- }
- $db = $byId[$sid];
- if (array_key_exists('This_quantity', $db) && $db['This_quantity'] !== null && $db['This_quantity'] !== '') {
- $rw['This_quantity'] = $db['This_quantity'];
- }
- if (array_key_exists('ceilingPrice', $db) && $db['ceilingPrice'] !== null && $db['ceilingPrice'] !== '') {
- $rw['ceilingPrice'] = $db['ceilingPrice'];
- } elseif (array_key_exists('ceiling_price', $db) && $db['ceiling_price'] !== null && $db['ceiling_price'] !== '') {
- $rw['ceilingPrice'] = $db['ceiling_price'];
- }
- }
- unset($rw);
- }
- /**
- * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
- */
- public function purchaseConfirmPick()
- {
- if (!$this->request->isPost() || !$this->request->isAjax()) {
- $this->error(__('Invalid parameters'));
- }
- if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
- $this->error(__('You have no permission'));
- }
- $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
- if ($batchRaw !== '') {
- $this->handlePurchaseConfirmOrderBatch($batchRaw);
- return;
- }
- $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
- $sid = (int)$scydgyId;
- if (!$this->isValidScydgyRowId($sid)) {
- $this->error('参数无效');
- }
- $parseIdList = function ($raw) {
- if (is_array($raw)) {
- $arr = $raw;
- } else {
- $decoded = json_decode((string)$raw, true);
- $arr = is_array($decoded) ? $decoded : [];
- }
- return array_values(array_unique(array_filter(array_map('intval', $arr))));
- };
- $selectedRaw = $this->request->post('selected_ids', null);
- if ($selectedRaw === null || $selectedRaw === '') {
- $legacy = (int)$this->request->post('selected_id', 0);
- $selectedIds = $legacy > 0 ? [$legacy] : [];
- } else {
- $selectedIds = $parseIdList($selectedRaw);
- }
- $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
- $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
- try {
- $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
- } catch (\InvalidArgumentException $e) {
- $this->error($e->getMessage());
- } catch (\Throwable $e) {
- $this->error($e->getMessage());
- }
- $this->pickHiddenScydgySetCache = null;
- $this->success('操作成功', '', $result);
- }
- /**
- * 整单采购确认(多道工序一次提交)
- */
- protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
- {
- $decoded = json_decode($batchRaw, true);
- if (!is_array($decoded) || $decoded === []) {
- $this->error('提交数据无效');
- }
- $picks = [];
- foreach ($decoded as $item) {
- if (!is_array($item)) {
- continue;
- }
- $sid = (int)($item['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
- if (!is_array($sel)) {
- $sel = [(int)$sel];
- }
- $unsel = $item['unselected_ids'] ?? [];
- if (!is_array($unsel)) {
- $unsel = json_decode((string)$unsel, true);
- $unsel = is_array($unsel) ? $unsel : [];
- }
- $picks[] = [
- 'scydgy_id' => $sid,
- 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
- 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
- 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
- ];
- }
- if ($picks === []) {
- $this->error('提交数据无效');
- }
- Db::startTrans();
- $results = [];
- try {
- foreach ($picks as $pick) {
- $results[] = $this->runPurchaseConfirmPick(
- (int)$pick['scydgy_id'],
- $pick['selected_ids'],
- $pick['unselected_ids'],
- (int)$pick['purchase_order_id'],
- false,
- false
- );
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $msg = $e->getMessage();
- $this->error($msg !== '' ? $msg : '提交失败');
- }
- try {
- $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
- $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
- } catch (\Throwable $e) {
- Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
- }
- $this->pickHiddenScydgySetCache = null;
- $this->success('操作成功', '', ['batch' => $results]);
- }
- /**
- * @return array<string, mixed>
- */
- protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
- {
- $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
- ProcuremenGuard::assertWflowPendingApproval($poRow);
- ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
- $scydgyId = (string)$sid;
- if ($selectedIds === []) {
- throw new \InvalidArgumentException('请至少勾选一条明细');
- }
- $inter = array_intersect($selectedIds, $unselectedIds);
- if ($inter !== []) {
- throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
- }
- $allIds = $this->purchaseOrderDetail($sid);
- if ($allIds === []) {
- throw new \InvalidArgumentException('未找到该工序行的下发明细');
- }
- foreach ($selectedIds as $id) {
- if (!in_array($id, $allIds, true)) {
- throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
- }
- }
- foreach ($unselectedIds as $id) {
- if (!in_array($id, $allIds, true)) {
- throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
- }
- }
- $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
- sort($union, SORT_NUMERIC);
- $expect = $allIds;
- sort($expect, SORT_NUMERIC);
- if ($union !== $expect) {
- throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
- }
- if ($manageTransaction) {
- Db::startTrans();
- }
- try {
- Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
- $aff = 0;
- try {
- $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
- } catch (\Throwable $e) {
- $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
- }
- if ($aff < 1) {
- throw new \Exception('更新选中状态失败');
- }
- $poPayload = [
- 'status' => ProcuremenStatus::PO_COMPLETED,
- 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
- ];
- if ($purchaseOrderId > 0) {
- $poAff = (int)Db::table('purchase_order')
- ->where('id', $purchaseOrderId)
- ->where('scydgy_id', $sid)
- ->update($poPayload);
- if ($poAff < 1) {
- throw new \Exception('主表订单不存在或与工序行不匹配');
- }
- } else {
- $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
- if ($poAff < 1) {
- throw new \Exception('未找到');
- }
- }
- $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
- $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
- if ($manageTransaction) {
- Db::commit();
- }
- } catch (\Throwable $e) {
- if ($manageTransaction) {
- Db::rollback();
- }
- throw $e;
- }
- $poIdFinal = $purchaseOrderId;
- if ($poIdFinal <= 0) {
- try {
- $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- if (is_array($rpo)) {
- $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
- }
- } catch (\Throwable $e) {
- $poIdFinal = 0;
- }
- }
- $pickNames = [];
- foreach ($selectedIds as $pid) {
- $dr = $this->purchaseOrderDetai($sid, $pid);
- $nm = trim((string)($dr['company_name'] ?? ''));
- $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
- }
- $this->addOrderLog(
- $sid,
- 'purchase_confirm',
- '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
- $poIdFinal > 0 ? $poIdFinal : null
- );
- if ($sendNotifications) {
- try {
- $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
- $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
- 'scydgy_id' => $sid,
- 'selected_ids' => $selectedIds,
- 'unselected_ids' => $unselectedIds,
- 'purchase_order_id' => $purchaseOrderId,
- ]]);
- } catch (\Throwable $e) {
- Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
- }
- }
- Log::write(sprintf(
- 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
- $scydgyId,
- $purchaseOrderId,
- json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
- json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
- ), 'notice');
- $pdfPublicPath = '';
- try {
- $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
- } catch (\Throwable $e) {
- Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
- }
- return [
- 'scydgy_id' => $scydgyId,
- 'purchase_order_id' => $purchaseOrderId,
- 'selected_ids' => $selectedIds,
- 'unselected_ids' => $unselectedIds,
- 'purchase_confirm_pdf' => $pdfPublicPath,
- ];
- }
- /**
- * 审批通过短信:按本次涉及的工序汇总 process_lines
- *
- * @param int[]|string[] $scydgyIds
- * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
- */
- protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
- {
- $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
- $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
- if ($scydgyIds === []) {
- return $empty;
- }
- $pos = [];
- try {
- $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- if (is_array($rows)) {
- foreach ($rows as $po) {
- if (is_array($po)) {
- $pos[] = $po;
- }
- }
- }
- if ($pos === []) {
- return $empty;
- }
- $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
- return [
- 'ccydh' => $ccydh,
- 'pos' => $pos,
- 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
- ];
- }
- /**
- * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
- *
- * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
- * @param array<int, array<string, mixed>> $picks
- */
- protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
- {
- if ($picks === []) {
- return;
- }
- $fallbackDetailId = 0;
- $winners = [];
- $losers = [];
- foreach ($picks as $pick) {
- if (!is_array($pick)) {
- continue;
- }
- $sid = (int)($pick['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
- $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
- if ($fallbackDetailId <= 0 && $selectedIds !== []) {
- $fallbackDetailId = (int)$selectedIds[0];
- }
- foreach ($selectedIds as $pid) {
- $dr = $this->purchaseOrderDetai($sid, $pid);
- if (!is_array($dr)) {
- continue;
- }
- $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
- }
- foreach ($unselectedIds as $pid) {
- $dr = $this->purchaseOrderDetai($sid, $pid);
- if (!is_array($dr)) {
- continue;
- }
- $key = $this->notifySupplierDedupeKey($dr);
- if (!isset($winners[$key])) {
- $losers[$key] = $dr;
- }
- }
- }
- if ($winners === [] && $losers === []) {
- return;
- }
- $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
- $sendSmsSafe = function ($phone, $content) {
- $phone = trim((string)$phone);
- if ($phone === '') {
- return;
- }
- try {
- $this->smsbao($phone, $content);
- } catch (\Throwable $e) {
- Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
- }
- };
- foreach ($winners as $dr) {
- $cname = trim((string)($dr['company_name'] ?? ''));
- $ph = trim((string)($dr['phone'] ?? ''));
- $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
- 'company_name' => $cname,
- 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
- 'phone' => $ph,
- ]));
- $sendSmsSafe($ph, $sms);
- }
- foreach ($losers as $dr) {
- $cname = trim((string)($dr['company_name'] ?? ''));
- $ph = trim((string)($dr['phone'] ?? ''));
- $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
- 'company_name' => $cname,
- 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
- 'phone' => $ph,
- ]));
- $sendSmsSafe($ph, $sms);
- }
- }
- /**
- * 短信去重键:优先手机号,否则公司名
- */
- protected function notifySupplierDedupeKey(array $detailRow): string
- {
- $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
- if ($ph !== '') {
- return 'p:' . $ph;
- }
- $cn = trim((string)($detailRow['company_name'] ?? ''));
- return 'c:' . $cn;
- }
- /**
- * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
- *
- * @param int[] $detailIds
- */
- protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
- {
- $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
- if ($detailIds === []) {
- return;
- }
- $payload = ['status_name' => $statusName];
- try {
- Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
- } catch (\Throwable $e) {
- Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
- }
- }
- /**
- * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
- */
- protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
- {
- try {
- $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
- } catch (\Throwable $e) {
- return;
- }
- if (!is_array($rows)) {
- return;
- }
- foreach ($rows as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
- if ($id <= 0) {
- continue;
- }
- $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
- $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
- try {
- Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
- } catch (\Throwable $e) {
- }
- }
- }
- /**
- * @param array<string, mixed> $detailRow
- */
- protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
- {
- $am = $detailRow['amount'] ?? null;
- $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
- $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
- $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
- return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
- }
- /**
- * @return int[]
- */
- protected function purchaseOrderDetail(int $scydgyId): array
- {
- if (!$this->isValidScydgyRowId($scydgyId)) {
- return [];
- }
- try {
- $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
- $this->applyActivePurchaseOrderDetailWhere($listQuery);
- $list = $listQuery->select();
- } catch (\Throwable $e) {
- return [];
- }
- if (!is_array($list)) {
- return [];
- }
- $ids = [];
- foreach ($list as $r) {
- if (!is_array($r)) {
- continue;
- }
- $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
- if ($pk > 0) {
- $ids[] = $pk;
- }
- }
- return array_values(array_unique($ids));
- }
- /**
- * 获取当前登录用户信息 [id, 展示名]
- */
- protected function GetUseName(): array
- {
- $id = 0;
- $name = '';
- try {
- if ($this->auth && $this->auth->isLogin()) {
- $u = $this->auth->getUserInfo();
- if (is_array($u)) {
- $id = (int)($u['id'] ?? 0);
- $name = trim((string)($u['nickname'] ?? ''));
- if ($name === '') {
- $name = trim((string)($u['username'] ?? ''));
- }
- }
- }
- } catch (\Throwable $e) {
- }
- if ($name === '') {
- $name = '未知用户';
- }
- return [$id, $name];
- }
- /**
- * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
- */
- protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
- {
- ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
- }
- /**
- * 按主键取一条
- */
- protected function purchaseOrderDetai(int $scydgyId, int $pk): array
- {
- if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
- return [];
- }
- try {
- $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
- if (is_array($one)) {
- return $one;
- }
- } catch (\Throwable $e) {
- }
- try {
- $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
- if (is_array($one)) {
- return $one;
- }
- } catch (\Throwable $e) {
- }
- return [];
- }
- /**
- * 主表/明细时间字段统一为可读字符串(用于详情进度)
- */
- protected function formatProcuremenDetailTime($v): string
- {
- if ($v === null || $v === '') {
- return '';
- }
- if (is_numeric($v) && (int)$v > 946684800) {
- return date('Y-m-d H:i:s', (int)$v);
- }
- return ProcuremenTime::formatDisplayDateTime($v);
- }
- /**
- * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
- */
- protected function formatDeliveryYmd($v): string
- {
- if ($v === null || $v === '') {
- return '';
- }
- $s = trim((string)$v);
- if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
- return '';
- }
- if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
- return $m[1];
- }
- $ts = strtotime($s);
- return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
- }
- /**
- * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
- */
- protected function detailRowSupplierOperated(array $r): bool
- {
- $am = $r['amount'] ?? null;
- $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
- $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
- $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
- return $okAmt || $okDel;
- }
- /**
- * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
- */
- protected function resolveDetailSupplierOperTime(array $r): string
- {
- if (!$this->detailRowSupplierOperated($r)) {
- return '';
- }
- $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
- if ($t !== '') {
- return $t;
- }
- foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
- if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
- continue;
- }
- $t = $this->formatProcuremenDetailTime($r[$col]);
- if ($t !== '') {
- return $t;
- }
- }
- return '';
- }
- /**
- * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
- */
- protected function detailRowSupplierAccepted(array $r): bool
- {
- $am = $r['amount'] ?? null;
- $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
- $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
- $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
- return $okAmt && $okDel;
- }
- /**
- * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
- */
- protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
- {
- if ($detailCount > 0) {
- return true;
- }
- if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
- return true;
- }
- $pickTime = trim((string)($main['pick_time'] ?? ''));
- if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
- return true;
- }
- return false;
- }
- /**
- * 下发时间:优先 pick_time,其次首条下发明细时间
- */
- protected function resolveProcuremenIssueTime(array $main, array $details): string
- {
- $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
- if ($issueTime !== '') {
- return $issueTime;
- }
- foreach ($details as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
- if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
- $issueTime = $t;
- }
- }
- if ($issueTime !== '') {
- return $issueTime;
- }
- return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
- }
- /**
- * 直接点「完结」时间:优先操作记录 mark_complete
- */
- protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
- {
- return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
- }
- /**
- * 操作记录时间(取指定 action 最近一条)
- *
- * @param string|array<int, string> $actions
- */
- protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
- {
- return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
- }
- /**
- * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
- *
- * @param array $main purchase_order 一行
- * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
- * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
- */
- protected function buildProcuremenDetailsViewData(array $main, array $details): array
- {
- $issueCnt = count($details);
- $acceptCnt = 0;
- $pickedName = '';
- $pickedTime = '';
- foreach ($details as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- if ($this->detailRowSupplierAccepted($dr)) {
- $acceptCnt++;
- }
- if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
- if ($pickedName === '') {
- $pickedName = trim((string)($dr['company_name'] ?? ''));
- }
- if ($pickedTime === '') {
- $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
- if ($pickedTime === '') {
- $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
- }
- }
- }
- }
- $hasMain = $main !== [];
- $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
- if ($poTime === '') {
- $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
- }
- $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
- $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
- $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
- $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
- $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
- $scydgyId = (int)($main['scydgy_id'] ?? 0);
- $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
- $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
- $supplierTime = '';
- if ($acceptCnt > 0) {
- foreach ($details as $dr) {
- if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
- continue;
- }
- $t = $this->resolveDetailSupplierOperTime($dr);
- if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
- $supplierTime = $t;
- }
- }
- }
- $directComplete = ($mainCompleted && !$issued);
- $doneTime = '';
- if ($mainCompleted) {
- if ($directComplete) {
- $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
- }
- if ($doneTime === '') {
- $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
- }
- if ($doneTime === '') {
- foreach ($details as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
- if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
- $doneTime = $t;
- }
- }
- }
- if ($doneTime === '') {
- $doneTime = $poTime;
- }
- if ($confirmApproveTime !== '') {
- $doneTime = $confirmApproveTime;
- }
- }
- if ($directComplete) {
- // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
- $step1Done = $hasMain;
- $step2Done = false;
- $step3Done = false;
- $step4Done = false;
- $step5Done = false;
- $step6Done = true;
- } else {
- $step1Done = $issued;
- $step2Done = $issued;
- $step3Done = $acceptCnt > 0;
- $step4Done = $wflowPendingApproval;
- if (!$step4Done) {
- foreach ($details as $dr) {
- if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
- $step4Done = true;
- break;
- }
- }
- }
- $step5Done = $confirmApproveTime !== '' || $mainCompleted;
- $step6Done = $mainCompleted;
- // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
- if ($mainCompleted && $issued) {
- $step3Done = true;
- $step4Done = true;
- $step5Done = true;
- if ($supplierTime === '') {
- $fillT = $doneTime !== '' ? $doneTime : $poTime;
- if ($fillT !== '') {
- $supplierTime = $fillT;
- }
- }
- if ($pickedTime === '') {
- $fillT = $doneTime !== '' ? $doneTime : $poTime;
- if ($fillT !== '') {
- $pickedTime = $fillT;
- }
- }
- if ($auditSelectTime === '') {
- $fillT = $doneTime !== '' ? $doneTime : $poTime;
- if ($fillT !== '') {
- $auditSelectTime = $fillT;
- }
- }
- if ($confirmApproveTime === '') {
- $fillT = $doneTime !== '' ? $doneTime : $poTime;
- if ($fillT !== '') {
- $confirmApproveTime = $fillT;
- }
- }
- }
- }
- $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
- $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
- $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
- $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
- $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
- $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
- $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
- $steps = [
- [
- 'title' => '未发',
- 'subtitle' => '',
- 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
- 'done' => $step1Done,
- ],
- [
- 'title' => '下发',
- 'subtitle' => '',
- 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
- 'done' => $step2Done,
- ],
- [
- 'title' => '供应商接单',
- 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
- 'time' => '',
- 'done' => $step3Done,
- ],
- [
- 'title' => '待确认',
- 'subtitle' => $step4Done
- ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
- : ($issued ? '待选供应商' : ''),
- 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
- 'done' => $step4Done,
- ],
- [
- 'title' => '待审批',
- 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
- 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
- 'done' => $step5Done,
- ],
- [
- 'title' => '已完结',
- 'subtitle' => '',
- 'time' => $step6Done ? $doneTime : '',
- 'done' => $step6Done,
- ],
- ];
- $currentIdx = count($steps) - 1;
- if (!$directComplete) {
- foreach ($steps as $i => $s) {
- if (!$s['done']) {
- $currentIdx = $i;
- break;
- }
- }
- }
- $nSteps = count($steps);
- foreach ($steps as $idx => &$s) {
- $s['current'] = ($idx === $currentIdx);
- if ($idx === 0) {
- $s['pdf_left_bg'] = '';
- } else {
- $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
- }
- if ($idx >= $nSteps - 1) {
- $s['pdf_right_bg'] = '';
- } else {
- $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
- }
- }
- unset($s);
- $labelMap = [
- 'CCYDH' => '订单号',
- 'CYJMC' => '印件名称',
- 'CCLBMMC' => '承揽部门',
- 'CGYMC' => '工序名称',
- 'CDW' => '单位',
- 'NGZL' => '工作量',
- 'CDF' => '单价',
- 'cGzzxMc' => '工作中心',
- 'MBZ' => '备注',
- 'This_quantity' => '本次数量',
- 'ceilingPrice' => '最高限价',
- ];
- $orderSummary = [];
- foreach ($labelMap as $key => $lab) {
- if (!array_key_exists($key, $main)) {
- continue;
- }
- $val = $main[$key];
- if ($val === null) {
- $val = '';
- } elseif (!is_scalar($val)) {
- $val = json_encode($val, JSON_UNESCAPED_UNICODE);
- } else {
- $val = (string)$val;
- }
- $orderSummary[] = ['label' => $lab, 'value' => $val];
- }
- $orderSummaryGrid = [];
- $n = count($orderSummary);
- for ($i = 0; $i < $n; $i += 2) {
- $left = $orderSummary[$i];
- $hasRight = ($i + 1) < $n;
- $orderSummaryGrid[] = [
- 'l1' => $left['label'],
- 'v1' => $left['value'],
- 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
- 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
- ];
- }
- return [
- 'steps' => $steps,
- 'orderSummary' => $orderSummary,
- 'orderSummaryGrid' => $orderSummaryGrid,
- 'detailRows' => $details,
- ];
- }
- /**
- * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
- *
- * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
- */
- protected function prepareProcuremenDetailsView(string $ids): array
- {
- $main = [];
- try {
- $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- $main = is_array($one) ? $one : [];
- } catch (\Throwable $e) {
- $main = [];
- }
- $details = [];
- $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
- if ($mergeRows === []) {
- $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
- if ($mergeRows === [] && $main !== []) {
- $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
- }
- }
- $detailSidList = [];
- $anchorSid = (int)$ids;
- if ($anchorSid !== 0) {
- $detailSidList[$anchorSid] = true;
- }
- foreach ($mergeRows as $mr) {
- if (!is_array($mr)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($mr);
- if ($sid !== 0) {
- $detailSidList[$sid] = true;
- }
- }
- try {
- if ($detailSidList !== []) {
- $details = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($detailSidList))
- ->order('id', 'asc')
- ->select();
- }
- } catch (\Throwable $e) {
- $details = [];
- }
- if (!is_array($details)) {
- $details = [];
- }
- foreach ($details as &$r) {
- if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
- $r['id'] = $r['ID'];
- }
- if (isset($r['createtime'])) {
- if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
- $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
- } else {
- $r['createtime_text'] = (string)$r['createtime'];
- }
- } else {
- $r['createtime_text'] = '';
- }
- $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
- $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
- $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
- $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
- }
- unset($r);
- $activeDetails = [];
- foreach ($details as $r) {
- if (is_array($r) && empty($r['is_void'])) {
- $activeDetails[] = $r;
- }
- }
- $operLogs = [];
- try {
- $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
- } catch (\Throwable $e) {
- $operLogs = [];
- }
- if (!is_array($operLogs)) {
- $operLogs = [];
- }
- $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
- $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
- $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
- $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
- if ($ccydh === '') {
- foreach ($details as $r) {
- if (!is_array($r)) {
- continue;
- }
- $ccydh = trim((string)($r['CCYDH'] ?? ''));
- if ($ccydh !== '') {
- break;
- }
- }
- }
- $this->view->assign('ccydh', $ccydh);
- $this->view->assign('steps', $bundle['steps']);
- $this->view->assign('orderSummary', $bundle['orderSummary']);
- $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
- $this->view->assign('processDisplayRows', $quoteView['process_rows']);
- $this->view->assign('processCount', count($mergeRows));
- $this->view->assign('detailRows', $details);
- $this->view->assign('supplierQuoteGroups', $quoteView['supplier_groups']);
- $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
- $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
- $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
- $this->view->assign('operLogs', $operLogs);
- return [
- 'ok' => $main !== [] || $details !== [],
- 'ccydh' => $ccydh,
- ];
- }
- /**
- * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
- */
- public function details()
- {
- $ids = $this->request->param('ids', $this->request->param('id', ''));
- if (is_array($ids)) {
- $ids = isset($ids[0]) ? $ids[0] : '';
- }
- $ids = trim((string)$ids);
- if ($ids === '') {
- $this->error(__('Invalid parameters'));
- }
- $this->assertManualOrderDetailsViewable((int)$ids);
- $this->prepareProcuremenDetailsView($ids);
- /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
- $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
- $this->view->engine->layout(false);
- try {
- return $this->view->fetch('procuremen/details_dialog_shell');
- } finally {
- if ($restoreLayout) {
- $this->view->engine->layout($restoreLayout);
- }
- }
- }
- /**
- * 解析合并审核工序行(订单号须一致,且均未协助)
- *
- * @return array<int, array<string, mixed>>
- */
- protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
- {
- $primary = json_decode($rowJson, true);
- if (!is_array($primary)) {
- $this->error(__('Invalid parameters'));
- }
- $merge = json_decode($mergeRowsJson, true);
- if (!is_array($merge) || $merge === []) {
- $merge = [$primary];
- }
- $seen = [];
- $out = [];
- foreach ($merge as $r) {
- if (!is_array($r)) {
- continue;
- }
- $id = $this->extractScydgyRowId($r);
- if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
- continue;
- }
- $seen[$id] = true;
- $out[] = $r;
- }
- if ($out === []) {
- $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
- }
- $ccydh = null;
- foreach ($out as $r) {
- $dh = trim((string)($r['CCYDH'] ?? ''));
- if ($ccydh === null) {
- $ccydh = $dh;
- } elseif ($dh !== $ccydh) {
- $this->error('合并审核要求所选行的订单号一致');
- }
- }
- $ids = [];
- foreach ($out as $r) {
- $id = $this->extractScydgyRowId($r);
- if ($this->isValidScydgyRowId($id)) {
- $ids[$id] = true;
- }
- }
- $poBySid = [];
- $detCntBySid = [];
- if ($ids !== []) {
- $idList = array_keys($ids);
- try {
- $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
- if (is_array($poList)) {
- foreach ($poList as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $poBySid[$sid] = $po;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- try {
- $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
- $this->applyActivePurchaseOrderDetailWhere($detQuery);
- $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
- if (is_array($detRows)) {
- foreach ($detRows as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $sid = (int)($dr['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
- }
- }
- }
- } catch (\Throwable $e) {
- }
- }
- foreach ($out as $r) {
- $id = $this->extractScydgyRowId($r);
- if (!$this->isValidScydgyRowId($id)) {
- continue;
- }
- $po = $poBySid[$id] ?? null;
- if (!is_array($po)) {
- continue;
- }
- if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
- $gymc = trim((string)($r['CGYMC'] ?? ''));
- $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
- }
- $detCnt = (int)($detCntBySid[$id] ?? 0);
- if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
- $gymc = trim((string)($r['CGYMC'] ?? ''));
- $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
- }
- }
- return $out;
- }
- /**
- * 规范化下发/确认时勾选的供应商
- *
- * @param array<int, mixed> $companies
- * @return array<int, array<string, string>>
- */
- protected function normalizePickCompanies(array $companies): array
- {
- $out = [];
- foreach ($companies as $c) {
- if (!is_array($c)) {
- continue;
- }
- $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
- if ($name === '') {
- continue;
- }
- $out[] = [
- 'name' => $name,
- 'company_name' => $name,
- 'username' => trim((string)($c['username'] ?? '')),
- 'email' => trim((string)($c['email'] ?? '')),
- 'phone' => trim((string)($c['phone'] ?? '')),
- 'company_type' => trim((string)($c['company_type'] ?? $c['category'] ?? '')),
- ];
- }
- return $out;
- }
- /**
- * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
- *
- * @param array<int, array<string, mixed>> $pool
- * @return array<int, array<string, mixed>>
- */
- protected function collapseProcuremenPoolByOrder(array $pool): array
- {
- if ($pool === []) {
- return [];
- }
- $groups = [];
- foreach ($pool as $row) {
- if (!is_array($row)) {
- continue;
- }
- $dh = trim((string)($row['CCYDH'] ?? ''));
- $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
- if (!isset($groups[$key])) {
- $groups[$key] = [];
- }
- $groups[$key][] = $row;
- }
- $out = [];
- foreach ($groups as $ccydh => $rows) {
- if ($rows === []) {
- continue;
- }
- usort($rows, function ($a, $b) {
- return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
- });
- $head = $rows[0];
- $gymcList = [];
- foreach ($rows as $r) {
- $g = trim((string)($r['CGYMC'] ?? ''));
- if ($g !== '' && !in_array($g, $gymcList, true)) {
- $gymcList[] = $g;
- }
- }
- $merged = $head;
- $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
- $merged['process_count'] = count($rows);
- $merged['_order_merge_rows'] = $rows;
- if (count($rows) > 1) {
- $merged['CGYMC'] = implode('、', $gymcList);
- }
- $mergedPickTime = '';
- foreach ($rows as $r) {
- $t = $this->procuremenRowListSortTime($r, 'pick_time');
- if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
- $mergedPickTime = $t;
- }
- }
- if ($mergedPickTime !== '') {
- $merged['pick_time'] = $mergedPickTime;
- }
- $out[] = $merged;
- }
- usort($out, function ($a, $b) {
- $ta = $this->procuremenRowListSortTime($a, 'pick_time');
- $tb = $this->procuremenRowListSortTime($b, 'pick_time');
- if ($ta === $tb) {
- $ida = (int)($a['purchase_order_id'] ?? 0);
- $idb = (int)($b['purchase_order_id'] ?? 0);
- if ($ida !== $idb) {
- return $idb <=> $ida;
- }
- return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
- }
- if ($ta === '') {
- return 1;
- }
- if ($tb === '') {
- return -1;
- }
- return strcmp($tb, $ta);
- });
- return $out;
- }
- /**
- * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
- *
- * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
- */
- protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
- {
- $scydgyId = trim($scydgyId);
- $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
- if ($scydgyId === '') {
- return $empty;
- }
- try {
- $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
- } catch (\Throwable $e) {
- $anchor = null;
- }
- if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
- return $empty;
- }
- $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
- if ($ccydh === '') {
- return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
- }
- try {
- $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
- } catch (\Throwable $e) {
- $pos = [$anchor];
- }
- if (!is_array($pos) || $pos === []) {
- $pos = [$anchor];
- }
- return [
- 'ccydh' => $ccydh,
- 'pos' => $pos,
- 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
- ];
- }
- /**
- * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
- */
- protected function purchaseOrderRowInConfirmStage(array $po): bool
- {
- if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
- return false;
- }
- if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
- return false;
- }
- if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
- return true;
- }
- if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
- $sid = (int)($po['scydgy_id'] ?? 0);
- return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
- }
- return false;
- }
- /**
- * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
- *
- * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
- */
- protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
- {
- $scydgyId = trim($scydgyId);
- $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
- if ($scydgyId === '') {
- return $empty;
- }
- try {
- $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
- } catch (\Throwable $e) {
- $anchor = null;
- }
- if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
- return $empty;
- }
- $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
- if ($ccydh === '') {
- return [
- 'ccydh' => '',
- 'pos' => [$anchor],
- 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
- ];
- }
- try {
- $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
- $this->applyPurchaseOrderConfirmStageWhere($posQuery);
- $pos = $posQuery->order('scydgy_id', 'asc')->select();
- } catch (\Throwable $e) {
- $pos = [$anchor];
- }
- if (!is_array($pos) || $pos === []) {
- $pos = [$anchor];
- }
- $pos = array_values(array_filter($pos, function ($po) {
- return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
- }));
- if ($pos === []) {
- $pos = [$anchor];
- }
- return [
- 'ccydh' => $ccydh,
- 'pos' => $pos,
- 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
- ];
- }
- /**
- * @param array<int, array<string, mixed>> $purchaseOrders
- * @return array<int, array<string, mixed>>
- */
- protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
- {
- $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
- $byId = [];
- foreach ($pool as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $byId[$sid] = $r;
- }
- }
- $out = [];
- foreach ($purchaseOrders as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
- $out[] = $byId[$sid];
- }
- }
- return $out;
- }
- /**
- * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
- *
- * @return array<int, array<string, mixed>>
- */
- protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
- {
- $scydgyId = trim($scydgyId);
- if ($scydgyId === '') {
- return [];
- }
- try {
- $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
- } catch (\Throwable $e) {
- $anchor = null;
- }
- if (!is_array($anchor)) {
- return [];
- }
- if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
- return [];
- }
- $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
- $pickTime = trim((string)($anchor['pick_time'] ?? ''));
- $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
- try {
- $q = Db::table('purchase_order');
- if ($ccydh !== '') {
- $q->where('CCYDH', $ccydh);
- } else {
- $q->where('scydgy_id', $scydgyId);
- }
- if ($isValidPick) {
- $q->where('pick_time', $pickTime);
- }
- $pos = $q->order('scydgy_id', 'asc')->select();
- } catch (\Throwable $e) {
- $pos = [$anchor];
- }
- if (!is_array($pos) || $pos === []) {
- $pos = [$anchor];
- }
- $pos = array_values(array_filter($pos, function ($po) {
- if (!is_array($po)) {
- return false;
- }
- $mr = $po['mod_rq'] ?? null;
- if ($mr === null || $mr === '') {
- return true;
- }
- $mrs = trim((string)$mr);
- return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
- }));
- if ($pos === []) {
- $pos = [$anchor];
- }
- $rows = $this->scydgyRowsForPurchaseOrders($pos);
- if ($rows === []) {
- $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
- }
- return $rows;
- }
- /**
- * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
- *
- * @param array<int, array<string, mixed>> $mergeRows
- * @return array<int, array<string, mixed>>
- */
- protected function buildAuditProcessDisplayRows(array $mergeRows): array
- {
- $list = array_values($mergeRows);
- $n = count($list);
- $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
- $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
- $mergeSame = $n > 1 && $orderKey0 !== '';
- if ($mergeSame) {
- foreach ($list as $rr) {
- if (!is_array($rr)) {
- $mergeSame = false;
- break;
- }
- if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
- || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
- $mergeSame = false;
- break;
- }
- }
- }
- $out = [];
- foreach ($list as $idx => $r) {
- if (!is_array($r)) {
- continue;
- }
- $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
- if (is_scalar($qty)) {
- $qty = trim((string)$qty);
- } else {
- $qty = '';
- }
- if ($qty === '') {
- $gzl = $r['NGZL'] ?? '';
- if (is_scalar($gzl)) {
- $qty = trim((string)$gzl);
- }
- }
- $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
- $sid = $this->extractScydgyRowId($r);
- $out[] = [
- 'seq' => $idx + 1,
- 'scydgy_id' => $sid,
- 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
- 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
- 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
- 'CDW' => trim((string)($r['CDW'] ?? '')),
- 'NGZL' => $r['NGZL'] ?? '',
- 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
- 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
- 'CDF' => trim((string)($r['CDF'] ?? '')),
- 'MBZ' => trim((string)($r['MBZ'] ?? '')),
- 'show_order_cells' => !$mergeSame || $idx === 0,
- 'order_rowspan' => $mergeSame ? $n : 1,
- ];
- }
- return $out;
- }
- /**
- * 解析金额/数量(去千分位等非数字字符)
- */
- protected function parseProcuremenMoneyNumber($value): ?float
- {
- if ($value === null || $value === '') {
- return null;
- }
- if (is_numeric($value)) {
- return (float)$value;
- }
- $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
- return ($v !== '' && is_numeric($v)) ? (float)$v : null;
- }
- protected function formatProcuremenMoneyDisplay(?float $amount): string
- {
- if ($amount === null) {
- return '';
- }
- return (string)(int)round($amount);
- }
- /**
- * 列表/详情展示:工作量为 0 时显示空
- */
- protected function formatProcuremenWorkloadDisplay($value): string
- {
- if ($value === null || $value === '') {
- return '';
- }
- $s = trim((string)$value);
- if ($s === '') {
- return '';
- }
- if (is_numeric($s) && (float)$s == 0) {
- return '';
- }
- return $s;
- }
- /**
- * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
- */
- protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
- {
- foreach ($details as $d) {
- if (!is_array($d)) {
- continue;
- }
- if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
- $cn = trim((string)($d['company_name'] ?? ''));
- if ($cn !== '') {
- return $cn;
- }
- }
- }
- return trim((string)($main['pick_company_name'] ?? ''));
- }
- /**
- * 详情报价小计:单价 × 本工序本次数量
- */
- protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
- {
- $unit = $this->parseProcuremenMoneyNumber($amountRaw);
- if ($unit === null) {
- return null;
- }
- $qty = $this->parseProcuremenMoneyNumber($qtyStr);
- if ($qty === null || $qty <= 0) {
- return null;
- }
- return $unit * $qty;
- }
- /**
- * 详情页:工序小计 + 供应商分组报价与总计
- *
- * @param array<int, array<string, mixed>> $mergeRows
- * @param array<int, array<string, mixed>> $details 含有效与历史明细
- * @return array{
- * process_rows: array,
- * supplier_groups: array,
- * order_total_text: string,
- * order_total_has: bool,
- * selected_company: string
- * }
- */
- protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
- {
- $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
- $deadlineReached = $this->isProcuremenQuoteDeadlineReached($main['sys_rq'] ?? '');
- $qtyBySid = [];
- $gymcBySid = [];
- $orderedSids = [];
- foreach ($mergeRows as $mr) {
- if (!is_array($mr)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($mr);
- if ($sid > 0) {
- $orderedSids[] = $sid;
- }
- $qty = trim((string)($mr['This_quantity'] ?? ''));
- if ($qty === '') {
- $qty = trim((string)($mr['NGZL'] ?? ''));
- }
- $qtyBySid[$sid] = $qty;
- $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
- }
- $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
- $detailByCompanySid = [];
- foreach ($details as $d) {
- if (!is_array($d)) {
- continue;
- }
- $cn = trim((string)($d['company_name'] ?? ''));
- $sid = (int)($d['scydgy_id'] ?? 0);
- if ($cn === '' || $sid === 0) {
- continue;
- }
- if (!isset($detailByCompanySid[$cn])) {
- $detailByCompanySid[$cn] = [];
- }
- $detailByCompanySid[$cn][$sid] = $d;
- }
- $supplierGroups = [];
- foreach ($detailByCompanySid as $cn => $bySid) {
- $lines = [];
- $groupTotal = 0.0;
- $groupHas = false;
- $groupVoid = true;
- $usedSids = [];
- $appendLine = function (int $sid, array $d) use (
- &$lines,
- &$groupTotal,
- &$groupHas,
- &$groupVoid,
- $qtyBySid,
- $gymcBySid,
- $deadlineReached
- ) {
- $isVoid = $this->isPurchaseOrderDetailVoid($d);
- if (!$isVoid) {
- $groupVoid = false;
- }
- $qtyStr = $qtyBySid[$sid] ?? '';
- $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
- $am = trim((string)($d['amount'] ?? ''));
- $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
- $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
- $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
- $sub = null;
- if (!$isVoid && $amountNum !== null) {
- $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
- }
- $ct = $this->resolveDetailSupplierOperTime($d);
- $line = [
- 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
- 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am,
- 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
- 'delivery_ymd' => $deliveryYmd,
- 'amount_filled' => $amountFilled,
- 'delivery_filled' => $deliveryFilled,
- 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
- 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
- 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
- 'is_void' => $isVoid,
- 'oper_time_text' => $ct,
- ];
- if (!$deadlineReached && !$isVoid) {
- $this->maskSupplierQuoteLineBeforeDeadline($line);
- } elseif ($sub !== null) {
- $groupTotal += $sub;
- $groupHas = true;
- }
- $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
- };
- foreach ($orderedSids as $sid) {
- if (!isset($bySid[$sid])) {
- continue;
- }
- $usedSids[$sid] = true;
- $appendLine($sid, $bySid[$sid]);
- }
- foreach ($bySid as $sid => $d) {
- if (isset($usedSids[$sid])) {
- continue;
- }
- $appendLine((int)$sid, $d);
- }
- $firstDetail = null;
- foreach ($bySid as $d) {
- if (is_array($d)) {
- $firstDetail = $d;
- break;
- }
- }
- $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
- $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
- if ($username === '' && $ph !== '') {
- $username = $this->resolveCustomerContactName($ph, $cn);
- }
- $lineCount = count($lines);
- $supplierGroups[] = [
- 'company_name' => $cn,
- 'username' => $username,
- 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
- 'phone' => $ph,
- 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
- 'is_void' => $groupVoid,
- 'lines' => $lines,
- 'line_count' => $lineCount,
- 'display_rowspan'=> $lineCount + ($lineCount > 0 ? 1 : 0),
- 'total_text' => ($deadlineReached && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
- 'has_total' => $lineCount > 0,
- ];
- }
- usort($supplierGroups, function ($a, $b) {
- if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
- return ($a['is_void'] ?? false) ? 1 : -1;
- }
- if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
- return ($a['is_selected'] ?? false) ? -1 : 1;
- }
- return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
- });
- return [
- 'process_rows' => $processRows,
- 'supplier_groups' => $supplierGroups,
- 'order_total_text' => '',
- 'order_total_has' => false,
- 'selected_company' => $selectedCompany,
- ];
- }
- /**
- * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
- */
- protected function buildProcessLinesPlain(array $mergeRows): string
- {
- $lines = [];
- $i = 1;
- foreach ($mergeRows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $gymc = trim((string)($r['CGYMC'] ?? ''));
- $dw = trim((string)($r['CDW'] ?? ''));
- $gzl = trim((string)($r['NGZL'] ?? ''));
- $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
- $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
- if ($dw !== '') {
- $parts[] = '单位:' . $dw;
- }
- if ($gzl !== '') {
- $parts[] = '工作量:' . $gzl;
- }
- if ($qty !== '') {
- $parts[] = '本次数量:' . $qty;
- }
- $lines[] = implode(' ', $parts);
- $i++;
- }
- return implode("\n", $lines);
- }
- /**
- * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
- *
- * @return array<string, string>
- */
- protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
- {
- if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
- $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
- }
- $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
- $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
- $ccydh = trim((string)($bundle['ccydh'] ?? ''));
- $cyjmc = '';
- foreach ($mergeRows as $mr) {
- if (!is_array($mr)) {
- continue;
- }
- if ($ccydh === '') {
- $ccydh = trim((string)($mr['CCYDH'] ?? ''));
- }
- if ($cyjmc === '') {
- $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
- }
- }
- if ($pos !== []) {
- $firstPo = $pos[0];
- if (is_array($firstPo)) {
- if ($ccydh === '') {
- $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
- }
- if ($cyjmc === '') {
- $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
- }
- }
- }
- if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
- $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
- if (is_array($any)) {
- if ($ccydh === '') {
- $ccydh = trim((string)($any['CCYDH'] ?? ''));
- }
- if ($cyjmc === '') {
- $cyjmc = trim((string)($any['CYJMC'] ?? ''));
- }
- }
- }
- $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
- $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
- $cgymc = '';
- if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
- $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
- }
- return [
- 'ccydh' => $ccydh,
- 'cyjmc' => $cyjmc,
- 'cgymc' => $cgymc,
- 'process_lines' => $processLines,
- 'process_lines_html' => '',
- ];
- }
- /**
- * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
- */
- protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
- {
- $lines = [];
- if ($ccydh !== '') {
- $lines[] = '订单号:' . $ccydh;
- }
- if ($cyjmc !== '') {
- $lines[] = '印件名称:' . $cyjmc;
- }
- if ($processPlain !== '') {
- $lines[] = $processPlain;
- }
- return implode("\n", $lines);
- }
- /**
- * 各工序手机端链接(纯文本,供短信模版 {platform_links})
- *
- * @param array<int, array{cgymc:string,url:string}> $detailLinks
- */
- protected function buildPlatformLinksPlain(array $detailLinks): string
- {
- $lines = [];
- $i = 1;
- foreach ($detailLinks as $lk) {
- if (!is_array($lk)) {
- continue;
- }
- $url = trim((string)($lk['url'] ?? ''));
- if ($url === '') {
- continue;
- }
- $label = trim((string)($lk['cgymc'] ?? ''));
- if ($label === '') {
- $label = '工序' . $i;
- }
- $lines[] = $label . ':' . $url;
- $i++;
- }
- return implode("\n", $lines);
- }
- /**
- * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
- *
- * @param array<int, array{cgymc:string,url:string}> $detailLinks
- */
- protected function buildPlatformLinksHtml(array $detailLinks): string
- {
- $parts = [];
- $i = 1;
- foreach ($detailLinks as $lk) {
- if (!is_array($lk)) {
- continue;
- }
- $url = trim((string)($lk['url'] ?? ''));
- if ($url === '') {
- continue;
- }
- $label = trim((string)($lk['cgymc'] ?? ''));
- if ($label === '') {
- $label = '工序' . $i;
- }
- $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
- $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
- . ' — <a href="' . $urlEsc . '">点击查看</a>';
- $i++;
- }
- return implode("<br>\n", $parts);
- }
- /**
- * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
- *
- * @return array<string, mixed>
- */
- protected function loadMailerConfig(): array
- {
- try {
- $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
- } catch (\Throwable $e) {
- $cfg = [];
- }
- return is_array($cfg) ? $cfg : [];
- }
- protected function loadNotifyTemplateRow(string $scene): ?array
- {
- try {
- $row = Db::table('purchase_sms_template')
- ->where('scene', $scene)
- ->where(function ($q) {
- $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
- })
- ->order('id', 'asc')
- ->find();
- } catch (\Throwable $e) {
- return null;
- }
- if (!is_array($row) || $row === []) {
- return null;
- }
- return [
- 'title' => trim((string)($row['title'] ?? '')),
- 'content' => trim((string)($row['content'] ?? '')),
- ];
- }
- /**
- * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
- */
- protected function buildProcessLinesHtml(array $mergeRows): string
- {
- if (count($mergeRows) <= 1) {
- $r = $mergeRows[0] ?? [];
- if (!is_array($r)) {
- return '';
- }
- $gymc = trim((string)($r['CGYMC'] ?? ''));
- $dw = trim((string)($r['CDW'] ?? ''));
- $gzl = trim((string)($r['NGZL'] ?? ''));
- $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
- $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
- if ($dw !== '') {
- $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
- }
- if ($gzl !== '') {
- $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
- }
- if ($qty !== '') {
- $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
- }
- return $html;
- }
- $rows = '';
- $i = 1;
- foreach ($mergeRows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
- $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
- $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
- $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
- $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
- . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
- . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
- . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
- . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
- $i++;
- }
- if ($rows === '') {
- return '';
- }
- return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
- . '<thead><tr style="background:#f5f5f5;">'
- . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
- . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
- . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
- . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
- . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
- . '</tr></thead><tbody>' . $rows . '</tbody></table>';
- }
- protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
- {
- $sysRq = trim($sysRq);
- if ($sysRq === '') {
- if ($required) {
- $this->error('请选择截止时间');
- }
- return '';
- }
- $ts = strtotime($sysRq);
- if ($ts === false || $ts <= 0) {
- $this->error('截止时间格式无效');
- }
- return date('Y-m-d H:i:s', $ts);
- }
- protected function formatProcuremenSysRqForInput($sysRq): string
- {
- $sr = trim((string)$sysRq);
- if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
- return '';
- }
- $ts = strtotime($sr);
- return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
- }
- protected function formatProcuremenSysRqForDisplay($sysRq): string
- {
- $sr = $this->formatProcuremenSysRqForInput($sysRq);
- if ($sr === '') {
- return '—';
- }
- $ts = strtotime($sr);
- return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
- }
- /**
- * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
- * @return array{ccydh?:string,pos:array,merge_rows:array}
- */
- protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
- {
- $sysRqPost = trim($sysRqPost);
- if ($sysRqPost === '') {
- return $bundle;
- }
- $sysRqDb = $this->parseProcuremenSysRqInput($sysRqPost, true);
- $pos = $bundle['pos'] ?? [];
- foreach ($pos as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- Db::table('purchase_order')->where('scydgy_id', $sid)->update(['sys_rq' => $sysRqDb]);
- }
- foreach ($pos as $i => $poRow) {
- if (is_array($pos[$i])) {
- $pos[$i]['sys_rq'] = $sysRqDb;
- }
- }
- $bundle['pos'] = $pos;
- return $bundle;
- }
- /**
- * 写入/更新 purchase_order(单道工序行)
- */
- protected function upsertPurchaseOrderFromRow(
- array $row,
- string $sysRqDb,
- $wflowStatus = null,
- ?string $pickTime = null,
- ?array $exists = null
- ): void {
- $ids = $this->extractScydgyRowId($row);
- if (!$this->isValidScydgyRowId($ids)) {
- throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
- }
- if ($exists === null) {
- $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- }
- $data = [
- 'scydgy_id' => $ids,
- 'CCYDH' => $row['CCYDH'] ?? null,
- 'CYJMC' => $row['CYJMC'] ?? null,
- 'CCLBMMC' => $row['CCLBMMC'] ?? null,
- 'CDXMC' => $row['CDXMC'] ?? null,
- 'CGYBH' => $row['CGYBH'] ?? null,
- 'CGYMC' => $row['CGYMC'] ?? null,
- 'CDW' => $row['CDW'] ?? null,
- 'NGZL' => $row['NGZL'] ?? null,
- 'CDF' => $row['CDF'] ?? null,
- 'cGzzxMc' => $row['cGzzxMc'] ?? null,
- 'MBZ' => $row['MBZ'] ?? null,
- 'bwjg' => $row['bwjg'] ?? null,
- 'iStatus' => $row['iStatus'] ?? null,
- 'dStamp' => $row['dStamp'] ?? null,
- 'dputrecord' => $row['dputrecord'] ?? null,
- 'cywyxm' => $row['cywyxm'] ?? null,
- 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
- 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
- 'status' => ProcuremenStatus::PO_IN_PROGRESS,
- 'sys_rq' => $sysRqDb,
- ];
- if ($wflowStatus !== null && $wflowStatus !== '') {
- $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
- }
- if ($pickTime !== null && $pickTime !== '') {
- $data['pick_time'] = $pickTime;
- $data['pick_company_name'] = '';
- }
- if ($exists) {
- $upd = $data;
- unset($upd['scydgy_id']);
- Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
- } else {
- $data['createtime'] = date('Y-m-d H:i:s');
- Db::table('purchase_order')->insert($data);
- }
- }
- /**
- * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
- *
- * @return array<int, array{detail_id:int, cgymc:string, url:string}>
- */
- protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
- {
- $toDb = function ($value) {
- if ($value === null) {
- return null;
- }
- if (is_scalar($value)) {
- return $value;
- }
- return json_encode($value, JSON_UNESCAPED_UNICODE);
- };
- $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
- $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
- $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
- $username = isset($c['username']) ? trim((string)$c['username']) : '';
- if ($username === '') {
- $username = $this->resolveCustomerContactName($phone, $companyName);
- }
- if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
- throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
- }
- if ($phone === '') {
- throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
- }
- $detailLinks = [];
- foreach ($mergeRows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($row);
- $detailId = 0;
- if ($skipExisting) {
- try {
- $existsQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', $sid)
- ->where('company_name', $companyName);
- $this->applyActivePurchaseOrderDetailWhere($existsQuery);
- $exists = $existsQuery->find();
- } catch (\Throwable $e) {
- $exists = null;
- }
- if (is_array($exists)) {
- $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
- }
- }
- if ($detailId <= 0) {
- $one = [
- 'scydgy_id' => $toDb($sid),
- 'CCYDH' => $toDb($row['CCYDH'] ?? null),
- 'CYJMC' => $toDb($row['CYJMC'] ?? null),
- 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
- 'username' => $username !== '' ? $username : null,
- 'email' => isset($c['email']) ? (string)$c['email'] : null,
- 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
- 'createtime' => date('Y-m-d H:i:s'),
- 'status' => ProcuremenStatus::POD_UNPICKED,
- 'status_name' => '未提交',
- ];
- Db::table('purchase_order_detail')->insert($one);
- $detailId = (int)Db::getLastInsID();
- }
- $mprocUrl = '';
- if ($buildMobileLinks && $detailId > 0) {
- $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
- }
- $detailLinks[] = [
- 'detail_id' => $detailId,
- 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
- 'url' => $mprocUrl,
- ];
- }
- return $detailLinks;
- }
- /**
- * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
- * @return array<string, mixed>
- */
- protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
- {
- $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
- $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
- $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
- $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
- $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
- $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
- $isMerge = !empty($ctx['is_merge']);
- $contactName = trim((string)($c['username'] ?? ''));
- if ($contactName === '') {
- $contactName = $this->resolveCustomerContactName($phone, $companyName);
- }
- $notifyVars = [
- 'company_name' => $companyName,
- 'contact_name' => $contactName,
- 'phone' => $phone,
- 'email' => $toEmail,
- 'ccydh' => (string)($ctx['ccydh'] ?? ''),
- 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
- 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
- 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
- 'deadline' => (string)($ctx['deadline'] ?? ''),
- 'process_lines' => (string)($ctx['process_plain'] ?? ''),
- 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
- 'platform_url' => $platformUrl,
- 'platform_links' => $platformLinksPlain,
- 'platform_links_html' => $platformLinksHtml,
- ];
- $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
- $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
- $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
- return [
- 'company_name' => $companyName,
- 'phone' => $phone,
- 'email' => $toEmail,
- 'sms_content' => $smsContent,
- 'mail_plain' => $mailPlain,
- 'mail_body' => $mailBody,
- 'notify_vars' => $notifyVars,
- 'detail_links' => $detailLinks,
- ];
- }
- /**
- * @param array<string, mixed> $chosen
- * @param array<int, array<string, mixed>> $mergeRows
- * @param array{ccydh:string, pos:array} $bundle
- */
- protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail): void
- {
- if (!$sendSms && !$sendEmail) {
- return;
- }
- $companyName = trim((string)($chosen['name'] ?? ''));
- $phone = trim((string)($chosen['phone'] ?? ''));
- $toEmail = trim((string)($chosen['email'] ?? ''));
- if ($companyName === '') {
- throw new \Exception('供应商名称无效');
- }
- if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
- throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
- }
- if ($sendSms && $phone === '') {
- throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
- }
- $sids = [];
- foreach ($mergeRows as $mr) {
- if (!is_array($mr)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($mr);
- if ($this->isValidScydgyRowId($sid)) {
- $sids[$sid] = true;
- }
- }
- if ($sids === []) {
- throw new \Exception('未找到工序行,无法发送通知');
- }
- $sysRqNotify = '';
- $pos = $bundle['pos'] ?? [];
- if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
- $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
- if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
- $ts = strtotime($sr);
- $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
- }
- }
- try {
- $detailsQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->where('company_name', $companyName);
- $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
- $details = $detailsQuery->order('id', 'asc')->select();
- } catch (\Throwable $e) {
- $details = [];
- }
- if (!is_array($details) || $details === []) {
- $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
- try {
- $detailsQuery = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->where('company_name', $companyName);
- $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
- $details = $detailsQuery->order('id', 'asc')->select();
- } catch (\Throwable $e) {
- $details = [];
- }
- }
- if (!is_array($details) || $details === []) {
- throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
- }
- $detailLinks = [];
- foreach ($details as $d) {
- if (!is_array($d)) {
- continue;
- }
- $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
- if ($detailId <= 0) {
- continue;
- }
- $sid = (int)($d['scydgy_id'] ?? 0);
- $gymc = '';
- foreach ($mergeRows as $mr) {
- if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
- $gymc = trim((string)($mr['CGYMC'] ?? ''));
- break;
- }
- }
- $detailLinks[] = [
- 'detail_id' => $detailId,
- 'cgymc' => $gymc,
- 'url' => $this->buildMprocMobileOrderUrl($detailId),
- ];
- }
- if ($detailLinks === []) {
- throw new \Exception('未找到有效的手机端链接,无法发送通知');
- }
- $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
- $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
- if ($sendEmail) {
- $mailTplRow = $this->loadNotifyTemplateRow('review_email');
- if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
- throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
- }
- $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
- $mailConfig = $this->loadMailerConfig();
- if (!$this->isProcuremenNotifyDryRun()) {
- if (empty($mailConfig['host'])) {
- throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
- }
- if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
- throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
- }
- }
- $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
- }
- if ($sendSms) {
- $this->issueSendSupplierSms($notifyBundle);
- }
- }
- /**
- * @param array<int, array<string, mixed>> $quoteGroups
- * @return array<int, array<string, mixed>>
- */
- protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
- {
- $names = [];
- if (is_string($companiesJson) && $companiesJson !== '') {
- $decoded = json_decode($companiesJson, true);
- if (is_array($decoded)) {
- foreach ($decoded as $nm) {
- $nm = trim((string)$nm);
- if ($nm !== '') {
- $names[] = $nm;
- }
- }
- }
- }
- $names = array_values(array_unique($names));
- if ($names === [] && $selectedCompany !== '') {
- $names = [$selectedCompany];
- }
- if ($names === []) {
- return $quoteGroups;
- }
- $targets = [];
- foreach ($quoteGroups as $g) {
- if (!is_array($g)) {
- continue;
- }
- $cn = trim((string)($g['name'] ?? ''));
- if ($cn !== '' && in_array($cn, $names, true)) {
- $targets[] = $g;
- }
- }
- return $targets;
- }
- /**
- * @return array{pos:array, merge_rows:array, bundle:array}
- */
- protected function loadAuditResendBundle(string $scydgyId): array
- {
- $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
- $pos = $bundle['pos'];
- $mergeRows = $bundle['merge_rows'];
- if ($pos === [] || $mergeRows === []) {
- $this->error('该订单不在待确认供应商状态');
- }
- $sysRqDb = '';
- if (isset($pos[0]) && is_array($pos[0])) {
- $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
- }
- foreach ($pos as $i => $poRow) {
- if (is_array($pos[$i]) && $sysRqDb !== '') {
- $pos[$i]['sys_rq'] = $sysRqDb;
- }
- }
- $bundle['pos'] = $pos;
- return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
- }
- /**
- * @param array<int, array<string, mixed>> $targets
- */
- protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
- {
- if ($targets === []) {
- $this->error('未找到可通知的供应商');
- }
- $notifyErrors = [];
- try {
- $this->notifyDryRunPreview = [];
- foreach ($targets as $g) {
- if (!is_array($g)) {
- continue;
- }
- $cname = trim((string)($g['name'] ?? ''));
- if ($cname === '') {
- continue;
- }
- $chosen = [
- 'name' => $cname,
- 'company_name' => $cname,
- 'email' => trim((string)($g['email'] ?? '')),
- 'phone' => trim((string)($g['phone'] ?? '')),
- 'username' => trim((string)($g['username'] ?? '')),
- ];
- try {
- $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail);
- } catch (\Throwable $e) {
- $notifyErrors[] = $cname . ':' . $e->getMessage();
- }
- }
- } catch (\Throwable $e) {
- $this->error('通知发送失败:' . $e->getMessage());
- }
- if ($notifyErrors !== []) {
- $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
- }
- if ($this->isProcuremenNotifyDryRun()) {
- $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
- 'notify_dry_run' => true,
- 'notify_preview' => $this->notifyDryRunPreview,
- ]);
- }
- $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
- }
- /**
- * 协助下发 — 发送短信(一家供应商)
- *
- * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
- */
- protected function issueSendSupplierSms(array $bundle): void
- {
- $companyName = (string)($bundle['company_name'] ?? '');
- $phone = (string)($bundle['phone'] ?? '');
- $smsContent = (string)($bundle['sms_content'] ?? '');
- $this->logIssueNotifyDebug('短信', [
- 'company' => $companyName,
- 'phone' => $phone,
- 'sms_content' => $smsContent,
- ]);
- if ($this->isProcuremenNotifyDryRun()) {
- $this->recordNotifyDryRunPreview([
- 'scene' => 'issue_sms',
- 'company_name' => $companyName,
- 'phone' => $phone,
- 'sms_content' => $smsContent,
- ]);
- return;
- }
- $this->smsbao($phone, $smsContent);
- }
- /**
- * 协助下发 — 发送邮件(一家供应商)
- *
- * @param array<string, mixed> $bundle
- * @param array<string, mixed> $mailConfig
- */
- protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
- {
- $companyName = (string)($bundle['company_name'] ?? '');
- $toEmail = (string)($bundle['email'] ?? '');
- $mailPlain = (string)($bundle['mail_plain'] ?? '');
- $mailBody = (string)($bundle['mail_body'] ?? '');
- $this->logIssueNotifyDebug('邮件', [
- 'company' => $companyName,
- 'email' => $toEmail,
- 'mail_subject' => $mailSubject,
- 'mail_body' => $mailPlain,
- ]);
- if ($this->isProcuremenNotifyDryRun()) {
- $this->recordNotifyDryRunPreview([
- 'scene' => 'issue_email',
- 'company_name' => $companyName,
- 'email' => $toEmail,
- 'mail_subject' => $mailSubject,
- 'mail_body' => $mailPlain,
- 'sms_content' => (string)($bundle['sms_content'] ?? ''),
- 'notify_vars' => $bundle['notify_vars'] ?? [],
- 'detail_links' => $bundle['detail_links'] ?? [],
- ]);
- return;
- }
- $mail = new PHPMailer(true);
- $mail->isSMTP();
- $mail->Host = $mailConfig['host'];
- $mail->SMTPAuth = true;
- $mail->Username = $mailConfig['addr'];
- $mail->Password = $mailConfig['pass'];
- $mail->SMTPSecure = $mailConfig['security'];
- $mail->Port = $mailConfig['port'];
- $mail->CharSet = $mailConfig['charset'];
- $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
- $mail->addAddress($toEmail, $companyName);
- $mail->isHTML(true);
- $mail->Subject = $mailSubject;
- $mail->Body = $mailBody;
- $mail->send();
- }
- /**
- * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
- *
- * @param array<int, array<string, mixed>> $mergeRows
- * @return array<string, mixed>
- */
- protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
- {
- $head = $mergeRows[0] ?? [];
- $isMerge = count($mergeRows) > 1;
- return [
- 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
- 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
- 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
- 'is_merge' => $isMerge,
- 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
- 'process_html' => $this->buildProcessLinesHtml($mergeRows),
- 'deadline' => $sysRqNotify,
- ];
- }
- /**
- * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
- *
- * @param array<string, mixed> $data
- */
- protected function logIssueNotifyDebug(string $type, array $data): void
- {
- if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
- return;
- }
- Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
- }
- /**
- * 协助下发弹窗(选多家供应商并通知)
- */
- public function pickReview()
- {
- if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
- $this->error(__('You have no permission'));
- }
- if ($this->request->isPost()) {
- $this->error('请使用弹窗内「确认下发」提交');
- }
- $this->view->assign('pickMode', 1);
- return $this->view->fetch('procuremen/review');
- }
- /**
- * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
- */
- public function add()
- {
- if ($this->request->isPost()) {
- $params = $this->request->post('row/a');
- if (!is_array($params)) {
- $this->error(__('Parameter %s can not be empty', ''));
- }
- [, $adminName] = $this->GetUseName();
- $params['cywyxm'] = $adminName;
- try {
- $sid = $this->saveManualPickOrder($params);
- } catch (\InvalidArgumentException $e) {
- $this->error($e->getMessage());
- } catch (\Throwable $e) {
- $this->error($e->getMessage());
- }
- $this->success('新增成功', '', ['scydgy_id' => $sid]);
- }
- [, $adminName] = $this->GetUseName();
- $this->view->assign('adminNickname', $adminName);
- $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
- return $this->view->fetch();
- }
- /**
- * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
- */
- public function rfqlist()
- {
- $this->relationSearch = false;
- $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
- $this->request->filter(['strip_tags', 'trim']);
- if ($this->request->isAjax()) {
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $limit = max(10, min(500, (int)$limit));
- $applyFilters = function ($query) use ($where) {
- $query->where('scydgy_id', '<', 0);
- $query->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%\')'
- );
- if (!$this->auth->isSuperAdmin()) {
- [, $adminName] = $this->GetUseName();
- $query->where('cywyxm', $adminName);
- }
- if (!empty($where)) {
- $query->where($where);
- }
- };
- $countQuery = Db::table('purchase_order');
- $applyFilters($countQuery);
- $total = (int)$countQuery->count();
- $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
- $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
- $listQuery = Db::table('purchase_order');
- $applyFilters($listQuery);
- $rows = $listQuery
- ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
- ->order($sortField, $orderDir)
- ->limit($offset, $limit)
- ->select();
- if (!is_array($rows)) {
- $rows = [];
- }
- $out = [];
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- if ($sid >= 0) {
- continue;
- }
- $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
- if ($createdText === '') {
- $createdText = trim((string)($r['dStamp'] ?? ''));
- }
- $out[] = [
- 'id' => (int)($r['id'] ?? 0),
- 'scydgy_id' => $sid,
- 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
- 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
- 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
- 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
- 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
- 'progress_text' => $this->formatProcuremenRfqProgressText($r),
- 'createtime' => $r['createtime'] ?? null,
- 'createtime_text' => $createdText,
- ];
- }
- return json(['total' => $total, 'rows' => $out]);
- }
- [, $adminName] = $this->GetUseName();
- $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
- $this->view->assign('adminNickname', $adminName);
- return $this->view->fetch('procuremen/rfqlist');
- }
- /**
- * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
- */
- public function rfqlistDetails()
- {
- return $this->details();
- }
- /**
- * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
- */
- protected function assertManualOrderDetailsViewable(int $scydgyId): void
- {
- if ($scydgyId >= 0) {
- return;
- }
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- if (!is_array($po)) {
- $this->error('订单不存在');
- }
- $modRq = trim((string)($po['mod_rq'] ?? ''));
- if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
- $this->error('订单不存在');
- }
- if ($this->auth->isSuperAdmin()) {
- return;
- }
- [, $adminName] = $this->GetUseName();
- $cywy = trim((string)($po['cywyxm'] ?? ''));
- if ($cywy !== '' && $cywy === $adminName) {
- return;
- }
- foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
- try {
- if ($this->auth->check($rule)) {
- return;
- }
- } catch (\Throwable $e) {
- }
- }
- $this->error('无权查看该订单');
- }
- /**
- * 手工新增协助工序进度文案
- */
- protected function formatProcuremenRfqProgressText(array $row): string
- {
- if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
- return ProcuremenStatus::PO_COMPLETED;
- }
- if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
- return '待采购确认';
- }
- if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
- return '待确认供应商';
- }
- $sid = (int)($row['scydgy_id'] ?? 0);
- if ($sid < 0) {
- try {
- $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
- $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
- $detCnt = (int)$detCntQuery->count();
- if ($detCnt > 0) {
- return '已下发待确认';
- }
- } catch (\Throwable $e) {
- }
- }
- return '待协助下发';
- }
- /**
- * 协助初选列表 — 批量软删除
- */
- public function pickDelete()
- {
- if (!$this->request->isPost() || !$this->request->isAjax()) {
- $this->error(__('Invalid parameters'));
- }
- if (!$this->procuremenCanPickDelete()) {
- $this->error(__('You have no permission'));
- }
- $rowsRaw = $this->request->post('rows_json', '[]');
- $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
- if (!is_array($rows) || $rows === []) {
- $this->error('请至少勾选一条工序');
- }
- $done = 0;
- Db::startTrans();
- try {
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $this->softDeleteProcuremenPickRow($row);
- $done++;
- }
- if ($done < 1) {
- throw new \Exception('没有可删除的工序');
- }
- Db::commit();
- } catch (\InvalidArgumentException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->pickHiddenScydgySetCache = null;
- $this->success('已删除 ' . $done . ' 条工序');
- }
- /**
- * 下发 — 手工新增工序(弹窗)
- */
- public function pickAdd()
- {
- if ($this->request->isPost()) {
- $params = $this->request->post('row/a');
- if (!is_array($params)) {
- $this->error(__('Parameter %s can not be empty', ''));
- }
- try {
- $sid = $this->saveManualPickOrder($params);
- } catch (\InvalidArgumentException $e) {
- $this->error($e->getMessage());
- } catch (\Throwable $e) {
- $this->error($e->getMessage());
- }
- $this->success('新增成功', '', ['scydgy_id' => $sid]);
- }
- return $this->view->fetch('procuremen/pick_add');
- }
- /**
- * 下发提交 — 通知供应商 → POST procuremen/picksubmit
- */
- public function pickSubmit()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- // ---------- 接口订单数据 ----------
- $rowJson = $this->request->post('row_json', '');
- $mergeRowsJson = $this->request->post('merge_rows_json', '');
- $companiesJson = $this->request->post('companies_json', '[]');
- $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
- $companies = json_decode($companiesJson, true);
- if (!is_array($companies)) {
- $this->error('供应商数据无效');
- }
- $issueCompanies = $this->normalizePickCompanies($companies);
- if ($issueCompanies === []) {
- $this->error('请至少选择一家合作供应商');
- }
- $issueNameLabels = [];
- foreach ($issueCompanies as $pc) {
- $issueNameLabels[] = $pc['name'];
- }
- $issueNamesSummary = implode('、', $issueNameLabels);
- $sysRq = trim((string)$this->request->post('sys_rq', ''));
- if ($sysRq === '') {
- $this->error('请选择截止时间');
- }
- $sysRqTs = strtotime($sysRq);
- if ($sysRqTs === false || $sysRqTs <= 0) {
- $this->error('截止时间格式无效');
- }
- $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
- $isMerge = count($mergeRows) > 1;
- $ccydhLog = '';
- foreach ($mergeRows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
- if ($ccydhLog !== '') {
- break;
- }
- }
- $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
- $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
- $logMsg = '下发' . $orderPart . $procPart
- . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
- $issueTime = date('Y-m-d H:i:s');
- $logSidList = [];
- foreach ($mergeRows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($row);
- if ($this->isValidScydgyRowId($sid)) {
- $logSidList[$sid] = true;
- }
- }
- $existingBySid = [];
- if ($logSidList !== []) {
- try {
- $existingRows = Db::table('purchase_order')
- ->where('scydgy_id', 'in', array_keys($logSidList))
- ->select();
- if (is_array($existingRows)) {
- foreach ($existingRows as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $existingBySid[$sid] = $poRow;
- }
- }
- }
- } catch (\Throwable $e) {
- $existingBySid = [];
- }
- }
- Db::startTrans();
- try {
- // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
- foreach ($mergeRows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $sid = $this->extractScydgyRowId($row);
- $this->upsertPurchaseOrderFromRow(
- $row,
- $sysRqDb,
- ProcuremenStatus::WFLOW_PENDING_CONFIRM,
- $issueTime,
- $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
- );
- }
- foreach ($issueCompanies as $c) {
- $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $poIdBySid = [];
- if ($logSidList !== []) {
- try {
- $poIdBySid = Db::table('purchase_order')
- ->where('scydgy_id', 'in', array_keys($logSidList))
- ->column('id', 'scydgy_id');
- } catch (\Throwable $e) {
- $poIdBySid = [];
- }
- }
- // ---------- 操作日志记录(批量写入,减少提交等待) ----------
- if ($logSidList !== []) {
- list($adminId, $adminName) = $this->GetUseName();
- $cut = function ($s, $max) {
- if (function_exists('mb_substr')) {
- return mb_substr($s, 0, $max, 'UTF-8');
- }
- return strlen($s) <= $max ? $s : substr($s, 0, $max);
- };
- $logRows = [];
- $seenLogSid = [];
- foreach ($mergeRows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $ids = $this->extractScydgyRowId($row);
- if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
- continue;
- }
- $seenLogSid[$ids] = true;
- $poIdLog = null;
- if (isset($poIdBySid[$ids])) {
- $tid = (int)$poIdBySid[$ids];
- $poIdLog = $tid > 0 ? $tid : null;
- }
- $logRows[] = [
- 'scydgy_id' => $ids,
- 'purchase_order_id' => $poIdLog,
- 'admin_id' => $adminId,
- 'admin_name' => $cut($adminName, 64),
- 'action' => $cut('issue_submit', 64),
- 'content' => $cut($logMsg, 1000),
- 'createtime' => ProcuremenTime::nowDateTime(),
- ];
- }
- if ($logRows !== []) {
- try {
- Db::table('purchase_order_oper_log')->insertAll($logRows);
- } catch (\Throwable $e) {
- Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
- }
- }
- }
- $notifyErrors = [];
- $posNotify = [];
- if ($logSidList !== []) {
- try {
- $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
- } catch (\Throwable $e) {
- $posNotify = [];
- }
- }
- if (!is_array($posNotify)) {
- $posNotify = [];
- }
- foreach ($posNotify as $i => $prow) {
- if (is_array($posNotify[$i])) {
- $posNotify[$i]['sys_rq'] = $sysRqDb;
- }
- }
- $ccydhPick = '';
- foreach ($mergeRows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
- if ($ccydhPick !== '') {
- break;
- }
- }
- $notifyBundleBase = [
- 'ccydh' => $ccydhPick,
- 'pos' => $posNotify,
- 'merge_rows' => $mergeRows,
- ];
- try {
- $this->notifyDryRunPreview = [];
- foreach ($issueCompanies as $c) {
- if (!is_array($c)) {
- continue;
- }
- $cname = trim((string)($c['name'] ?? ''));
- if ($cname === '') {
- continue;
- }
- try {
- $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
- } catch (\Throwable $e) {
- $notifyErrors[] = $cname . ':' . $e->getMessage();
- }
- }
- } catch (\Throwable $e) {
- $this->error('通知发送失败:' . $e->getMessage());
- }
- if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
- $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
- }
- if ($this->isProcuremenNotifyDryRun()) {
- $this->success('【演练模式】已保存并生成通知预览', '', [
- 'notify_dry_run' => true,
- 'notify_preview' => $this->notifyDryRunPreview,
- ]);
- }
- $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
- }
- /**
- * 确认供应商弹窗
- */
- public function auditIssue()
- {
- $ids = $this->request->param('ids', $this->request->param('id', ''));
- if (is_array($ids)) {
- $ids = isset($ids[0]) ? $ids[0] : '';
- }
- $ids = trim((string)$ids);
- if ($ids === '') {
- $this->error(__('Invalid parameters'));
- }
- if ($this->request->isPost()) {
- $this->error('请使用弹窗内「确认」提交');
- }
- $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
- $pos = $bundle['pos'];
- if ($pos === []) {
- $this->error('该订单不在待确认供应商状态');
- }
- $po = $pos[0];
- $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
- if ($quoteGroups === []) {
- $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
- }
- $pickedName = '';
- foreach ($pos as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $pn = trim((string)($poRow['pick_company_name'] ?? ''));
- if ($pn !== '') {
- $pickedName = $pn;
- break;
- }
- }
- $this->view->assign('po', $po);
- $this->view->assign('scydgyId', $ids);
- $this->view->assign('orderCcydh', $bundle['ccydh']);
- $mergeRows = $bundle['merge_rows'];
- $this->view->assign('processRows', $mergeRows);
- $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
- $this->view->assign('processCount', count($mergeRows));
- $this->view->assign('quoteGroups', $quoteGroups);
- $this->view->assign('quoteGroupsJson', json_encode($quoteGroups, JSON_UNESCAPED_UNICODE));
- $this->view->assign('pickedCompanyName', $pickedName);
- $this->view->assign('sysRq', $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null));
- $this->view->assign('quoteDeadlineReached', $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0);
- return $this->view->fetch('procuremen/audit_issue');
- }
- /**
- * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
- */
- public function auditSubmit()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
- if ($scydgyId === '') {
- $this->error('参数无效');
- }
- $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
- $pos = $bundle['pos'];
- $mergeRows = $bundle['merge_rows'];
- if ($pos === [] || $mergeRows === []) {
- $this->error('该订单不在待确认供应商状态');
- }
- $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
- if ($quoteGroups === []) {
- $this->error('暂无供应商报价,请确认已完成协助初选通知');
- }
- $companyName = trim((string)$this->request->post('selected_company', ''));
- if ($companyName === '') {
- $this->error('请选择一家供应商');
- }
- $matched = null;
- foreach ($quoteGroups as $g) {
- if (!is_array($g)) {
- continue;
- }
- if (trim((string)($g['name'] ?? '')) === $companyName) {
- $matched = $g;
- break;
- }
- }
- if ($matched === null) {
- $this->error('所选供应商不在本单报价列表中');
- }
- $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
- if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
- $this->error('报价截止时间未到,暂不能确认供应商');
- }
- $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
- $procCnt = count($mergeRows);
- $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
- $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
- $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
- Db::startTrans();
- try {
- foreach ($pos as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- Db::table('purchase_order')->where('scydgy_id', $sid)->update([
- 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
- 'status' => ProcuremenStatus::PO_IN_PROGRESS,
- 'pick_company_name' => $companyName,
- 'sys_rq' => $sysRqDb,
- ]);
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- foreach ($pos as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
- $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
- }
- $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
- }
- /**
- * 确认供应商 — 二次发送短信(可选单家/批量/全部)
- */
- public function auditResendSms()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
- if ($scydgyId === '') {
- $this->error('参数无效');
- }
- $loaded = $this->loadAuditResendBundle($scydgyId);
- $mergeRows = $loaded['merge_rows'];
- $bundle = $loaded['bundle'];
- $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
- $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
- if ($quoteGroups === []) {
- $this->error('暂无可通知的供应商');
- }
- $selectedCompany = trim((string)$this->request->post('selected_company', ''));
- $companiesJson = (string)$this->request->post('companies_json', '');
- $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
- $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
- }
- /**
- * 确认供应商 — 二次发送邮件(可选单家/批量)
- */
- public function auditResendEmail()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
- if ($scydgyId === '') {
- $this->error('参数无效');
- }
- $loaded = $this->loadAuditResendBundle($scydgyId);
- $mergeRows = $loaded['merge_rows'];
- $bundle = $loaded['bundle'];
- $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
- $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
- if ($quoteGroups === []) {
- $this->error('暂无可通知的供应商');
- }
- $companiesJson = (string)$this->request->post('companies_json', '');
- $selectedCompany = trim((string)$this->request->post('selected_company', ''));
- $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
- if ($companiesJson === '' && $selectedCompany === '') {
- $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
- }
- $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
- }
- /**
- * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
- *
- * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
- * @return array<int, true> 已处理的 scydgy_id 集合
- */
- protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
- {
- $pos = $bundle['pos'] ?? [];
- if (!is_array($pos) || $pos === []) {
- return [];
- }
- $sids = [];
- foreach ($pos as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if ($this->isValidScydgyRowId($sid)) {
- $sids[$sid] = true;
- }
- }
- if ($sids === []) {
- return [];
- }
- $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
- $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
- $suffix = trim((string)$logSuffix, ',, ');
- if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
- $logMsg .= ':从历史存证退回协助初选';
- } else {
- $logMsg .= ':退回协助初选';
- }
- Db::table('purchase_order')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->update([
- 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
- 'status' => ProcuremenStatus::PO_IN_PROGRESS,
- 'pick_company_name' => '',
- 'pick_time' => null,
- 'sys_rq' => null,
- 'mod_rq' => null,
- ]);
- $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
- foreach (array_keys($sids) as $sid) {
- $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
- }
- return $sids;
- }
- /**
- * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
- *
- * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
- */
- protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
- {
- $scydgyId = trim($scydgyId);
- $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
- if ($scydgyId === '') {
- return $empty;
- }
- try {
- $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
- } catch (\Throwable $e) {
- $anchor = null;
- }
- if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
- return $empty;
- }
- $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
- if ($ccydh === '') {
- return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
- }
- try {
- $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
- $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
- $pos = $query->order('scydgy_id', 'asc')->select();
- } catch (\Throwable $e) {
- $pos = [$anchor];
- }
- if (!is_array($pos) || $pos === []) {
- $pos = [$anchor];
- }
- return [
- 'ccydh' => $ccydh,
- 'pos' => $pos,
- 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
- ];
- }
- protected function purchaseOrderRowIsCompleted(array $po): bool
- {
- $st = $po['status'] ?? null;
- if ($st === 1 || $st === '1') {
- return true;
- }
- if (is_string($st) && trim($st) === '1') {
- return true;
- }
- return is_numeric($st) && (int)$st === 1;
- }
- /**
- * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
- */
- public function auditAbandon()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- $anchorIds = [];
- $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
- if ($batchRaw !== '') {
- $decoded = json_decode($batchRaw, true);
- if (is_array($decoded)) {
- foreach ($decoded as $id) {
- $s = trim((string)$id);
- if ($s !== '') {
- $anchorIds[] = $s;
- }
- }
- }
- }
- if ($anchorIds === []) {
- $single = trim((string)$this->request->post('scydgy_id', ''));
- if ($single !== '') {
- $anchorIds[] = $single;
- }
- }
- if ($anchorIds === []) {
- $this->error('请至少选择一条订单');
- }
- $processedCcydh = [];
- $doneOrders = 0;
- $allSids = [];
- Db::startTrans();
- try {
- foreach ($anchorIds as $anchorId) {
- $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
- if (($bundle['pos'] ?? []) === []) {
- continue;
- }
- $ccydh = trim((string)($bundle['ccydh'] ?? ''));
- $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
- if (isset($processedCcydh[$dedupeKey])) {
- continue;
- }
- $processedCcydh[$dedupeKey] = true;
- $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
- if ($sids === []) {
- continue;
- }
- $doneOrders++;
- foreach (array_keys($sids) as $sid) {
- $allSids[(int)$sid] = true;
- }
- }
- if ($doneOrders < 1) {
- throw new \Exception('所选订单均不在待确认供应商状态');
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->pickHiddenScydgySetCache = null;
- $msg = $doneOrders > 1
- ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
- : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
- $this->success($msg);
- }
- /**
- * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
- */
- public function archiveAbandon()
- {
- if (!$this->request->isPost()) {
- $this->error(__('Invalid parameters'));
- }
- $anchorIds = [];
- $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
- if ($batchRaw !== '') {
- $decoded = json_decode($batchRaw, true);
- if (is_array($decoded)) {
- foreach ($decoded as $id) {
- $s = trim((string)$id);
- if ($s !== '') {
- $anchorIds[] = $s;
- }
- }
- }
- }
- if ($anchorIds === []) {
- $single = trim((string)$this->request->post('scydgy_id', ''));
- if ($single !== '') {
- $anchorIds[] = $single;
- }
- }
- if ($anchorIds === []) {
- $this->error('请至少选择一条订单');
- }
- $processedCcydh = [];
- $doneOrders = 0;
- Db::startTrans();
- try {
- foreach ($anchorIds as $anchorId) {
- $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
- if (($bundle['pos'] ?? []) === []) {
- continue;
- }
- $ccydh = trim((string)($bundle['ccydh'] ?? ''));
- $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
- if (isset($processedCcydh[$dedupeKey])) {
- continue;
- }
- $processedCcydh[$dedupeKey] = true;
- $sids = $this->abandonOrderBundleToPick(
- $bundle,
- 'archive_abandon',
- ',从历史存证退回协助初选'
- );
- if ($sids === []) {
- continue;
- }
- $doneOrders++;
- }
- if ($doneOrders < 1) {
- throw new \Exception('所选订单均不是已完结状态');
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->pickHiddenScydgySetCache = null;
- $msg = $doneOrders > 1
- ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
- : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
- $this->success($msg);
- }
- /**
- * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
- */
- public function purchaseApprovalReject()
- {
- if (!$this->request->isPost() || !$this->request->isAjax()) {
- $this->error(__('Invalid parameters'));
- }
- if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
- $this->error(__('You have no permission'));
- }
- $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
- $decoded = json_decode($batchRaw, true);
- if (!is_array($decoded) || $decoded === []) {
- $this->error('提交数据无效');
- }
- $done = 0;
- Db::startTrans();
- try {
- foreach ($decoded as $item) {
- if (!is_array($item)) {
- continue;
- }
- $sid = (int)($item['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- $this->runPurchaseApprovalRejectForSid($sid);
- $done++;
- }
- if ($done < 1) {
- throw new \Exception('所选订单均不在待审批状态');
- }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
- }
- $this->pickHiddenScydgySetCache = null;
- $this->success('已驳回并退回「协助审批下发」');
- }
- /**
- * @throws \Exception
- */
- protected function runPurchaseApprovalRejectForSid(int $sid): void
- {
- $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
- ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
- ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
- $allIds = $this->purchaseOrderDetail($sid);
- if ($allIds === []) {
- throw new \Exception('未找到下发明细');
- }
- Db::table('purchase_order')->where('scydgy_id', $sid)->update([
- 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
- 'status' => ProcuremenStatus::PO_IN_PROGRESS,
- 'pick_company_name' => '',
- ]);
- Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
- $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
- $poId = 0;
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- if (is_array($po)) {
- $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
- }
- } catch (\Throwable $e) {
- }
- $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
- }
- /**
- * 审核弹窗(旧入口,POST 已关闭)
- */
- public function review()
- {
- if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
- $this->error(__('You have no permission'));
- }
- if ($this->request->isPost()) {
- $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
- }
- $this->view->assign('pickMode', 0);
- return $this->view->fetch('procuremen/review');
- }
- /**
- * 审核弹窗获取公司列表
- */
- public function reviewCompanies()
- {
- if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review'])) {
- $this->error(__('You have no permission'));
- }
- if (!$this->request->isAjax()) {
- $this->error(__('Invalid parameters'));
- }
- $list = [];
- try {
- // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
- $rows = Db::table('customer')
- ->where(function ($q) {
- $q->where('status', 1)
- ->whereOr('status', '1')
- ->whereOr('status', '')
- ->whereNull('status');
- })
- ->order('id', 'desc')
- ->select();
- } catch (\Throwable $e) {
- $this->success('', '', []);
- return;
- }
- if (!is_array($rows)) {
- $this->success('', '', []);
- return;
- }
- $detailColCandidates = [
- 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
- 'company_detail', 'company_desc', 'address',
- ];
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $norm = [];
- foreach ($row as $k => $v) {
- $norm[is_string($k) ? strtolower($k) : $k] = $v;
- }
- $row = $norm;
- $st = $row['status'] ?? '';
- if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
- continue;
- }
- $id = isset($row['id']) ? (string)$row['id'] : '';
- $companyName = '';
- foreach (['company_name', 'name'] as $nk) {
- if (!empty($row[$nk])) {
- $companyName = trim((string)$row[$nk]);
- break;
- }
- }
- $username = '';
- foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
- if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
- $username = trim((string)$row[$uk]);
- break;
- }
- }
- $email = isset($row['email']) ? trim((string)$row['email']) : '';
- $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
- if ($phone === '' && isset($row['account'])) {
- $phone = trim((string)$row['account']);
- }
- if ($phone === '' && isset($row['mobile'])) {
- $phone = trim((string)$row['mobile']);
- }
- /* 邮箱、手机号均为空则无法发短信/邮件,不在下发弹窗展示 */
- if ($email === '' && $phone === '') {
- continue;
- }
- $category = '';
- foreach (['company_type', 'category', 'type_name'] as $ck) {
- if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
- $category = trim((string)$row[$ck]);
- break;
- }
- }
- $detail = '';
- foreach ($detailColCandidates as $dk) {
- if (!isset($row[$dk])) {
- continue;
- }
- $dv = trim((string)$row[$dk]);
- if ($dv !== '') {
- $detail = $dv;
- break;
- }
- }
- $list[] = [
- 'id' => $id,
- 'name' => $companyName,
- 'company_name' => $companyName,
- 'username' => $username,
- 'email' => $email,
- 'phone' => $phone,
- 'category' => $category,
- 'company_type' => $category,
- 'detail' => $detail,
- ];
- }
- $this->success('', '', $list);
- }
- /**
- * 采购确认-下发明细弹窗:
- * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
- */
- public function outward_detail()
- {
- $ids = $this->request->param('ids', $this->request->param('id', ''));
- if (is_array($ids)) {
- $ids = isset($ids[0]) ? $ids[0] : '';
- }
- $ids = trim((string)$ids);
- if ($ids === '') {
- $this->error(__('Invalid parameters'));
- }
- $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
- if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
- $wffTab = 'all';
- }
- $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
- $purchaseOrderId = 0;
- $po = null;
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
- if (is_array($po)) {
- $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
- }
- } catch (\Throwable $e) {
- $purchaseOrderId = 0;
- $po = null;
- }
- if (!$isPurchaseConfirm && is_array($po)) {
- $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
- if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
- $isPurchaseConfirm = true;
- }
- }
- $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
- $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
- $confirmProcessCount = 1;
- $confirmPickGroups = [];
- $processDisplayRows = [];
- $allDetailsBySid = [];
- $requiredSidList = [];
- $sidList = [$ids];
- if ($isPurchaseConfirm) {
- $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
- $mergeRows = $confirmBundle['merge_rows'] ?? [];
- if ($mergeRows !== []) {
- $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
- }
- $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
- if ($confirmBundle['pos'] !== []) {
- $sidList = [];
- foreach ($confirmBundle['pos'] as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $sid = (int)($poRow['scydgy_id'] ?? 0);
- if (!$this->isValidScydgyRowId($sid)) {
- continue;
- }
- $sidList[] = (string)$sid;
- $requiredSidList[] = $sid;
- }
- }
- if ($sidList === []) {
- $sidList = [$ids];
- $requiredSidList = [(int)$ids];
- }
- $confirmProcessCount = max(1, count($requiredSidList));
- if (is_array($po) && $purchaseOrderId <= 0) {
- $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
- }
- }
- $rows = [];
- try {
- if (count($sidList) === 1) {
- $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
- } else {
- $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
- }
- } catch (\Throwable $e) {
- $rows = [];
- }
- if ($isPurchaseConfirm) {
- $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
- }
- foreach ($rows as &$r) {
- if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
- $r['id'] = $r['ID'];
- }
- if (isset($r['createtime'])) {
- if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
- $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
- } else {
- $r['createtime_text'] = (string)$r['createtime'];
- }
- } else {
- $r['createtime_text'] = '';
- }
- }
- unset($r);
- $pickedCompanyName = '';
- if ($isPurchaseConfirm) {
- foreach ($confirmBundle['pos'] ?? [] as $poRow) {
- if (!is_array($poRow)) {
- continue;
- }
- $pn = trim((string)($poRow['pick_company_name'] ?? ''));
- if ($pn !== '') {
- $pickedCompanyName = $pn;
- break;
- }
- }
- }
- $this->view->assign('rows', $rows ?: []);
- $this->view->assign('rowCount', count($rows ?: []));
- $this->view->assign('scydgyId', $ids);
- $this->view->assign('purchaseOrderId', $purchaseOrderId);
- $this->view->assign('headTitle', $headTitle);
- $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
- $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
- $this->view->assign('confirmProcessCount', $confirmProcessCount);
- $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
- $this->view->assign('processDisplayRows', $processDisplayRows);
- $this->view->assign('confirmPickGroups', $confirmPickGroups);
- $this->view->assign('confirmPickCount', count($confirmPickGroups));
- $this->view->assign('pickedCompanyName', $pickedCompanyName);
- $sysRqDisplay = '—';
- if ($isPurchaseConfirm) {
- $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
- $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
- );
- }
- $this->view->assign('sysRqDisplay', $sysRqDisplay);
- $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
- $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
- /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
- if ($isPurchaseConfirm) {
- return $this->view->fetch();
- }
- $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
- $this->view->engine->layout(false);
- try {
- $bodyHtml = $this->view->fetch('procuremen/outward_detail');
- $this->view->assign('dialogBody', $bodyHtml);
- return $this->view->fetch('procuremen/outward_detail_lite_shell');
- } finally {
- if ($restoreLayout) {
- $this->view->engine->layout($restoreLayout);
- }
- }
- }
- /**
- * 月度导出记录表(不存在时自动创建)
- */
- protected function ensurePurchaseMonthExportLogTable(): void
- {
- try {
- Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
- } catch (\Throwable $e) {
- Db::execute(
- "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
- `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
- `admin_name` varchar(64) NOT NULL DEFAULT '',
- `row_count` int(10) unsigned NOT NULL DEFAULT 0,
- `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
- `createtime` int(10) unsigned DEFAULT NULL,
- PRIMARY KEY (`id`),
- KEY `idx_ym` (`ym`),
- KEY `idx_ct` (`createtime`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
- );
- }
- }
- /**
- * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
- * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
- */
- public function export_month_outward()
- {
- if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
- $this->error(__('You have no permission'));
- }
- $this->request->filter(['strip_tags', 'trim']);
- $ym = trim((string)$this->request->get('ym', date('Y-m')));
- if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
- $ym = date('Y-m');
- }
- $dbRows = [];
- try {
- $query = Db::table('purchase_order');
- $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
- $dbRows = $query->select();
- } catch (\Throwable $e) {
- $dbRows = [];
- }
- if (!is_array($dbRows)) {
- $dbRows = [];
- }
- $completeTsMap = [];
- $sidList = [];
- foreach ($dbRows as $dbRow) {
- if (!is_array($dbRow)) {
- continue;
- }
- $sid = (int)($dbRow['scydgy_id'] ?? 0);
- if ($sid > 0) {
- $sidList[$sid] = true;
- }
- }
- if ($sidList !== []) {
- $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
- }
- $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
- if (!is_array($dbRow)) {
- return false;
- }
- $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
- return $done['ts'] > 0 && date('Y-m', $done['ts']) === $ym;
- }));
- $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
- $filtered = $pool;
- $mainBySid = [];
- foreach ($filtered as $rw) {
- if (!is_array($rw)) {
- continue;
- }
- $rid = (int)($rw['ID'] ?? 0);
- if ($rid > 0) {
- $mainBySid[$rid] = $rw;
- }
- }
- if ($mainBySid === []) {
- $detailRows = [];
- } else {
- try {
- $detailRows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($mainBySid))
- ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
- ->order('status', 'desc')
- ->order('CCYDH', 'asc')
- ->order('company_name', 'asc')
- ->order('id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- try {
- $detailRows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', array_keys($mainBySid))
- ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
- ->order('status', 'desc')
- ->order('CCYDH', 'asc')
- ->order('company_name', 'asc')
- ->order('ID', 'asc')
- ->select();
- } catch (\Throwable $e2) {
- $detailRows = [];
- }
- }
- }
- if (!is_array($detailRows)) {
- $detailRows = [];
- }
- $exportLines = [];
- $detailSidSeen = [];
- foreach ($detailRows as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
- if ($sid <= 0 || !isset($mainBySid[$sid])) {
- continue;
- }
- if (isset($detailSidSeen[$sid])) {
- continue;
- }
- if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
- continue;
- }
- $detailSidSeen[$sid] = true;
- $m = $mainBySid[$sid];
- $exportLines[] = [
- 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
- 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
- 'company_name' => (string)($dr['company_name'] ?? ''),
- 'CDF' => (string)($m['CDF'] ?? ''),
- 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
- 'gx' => $this->procuremenExportGxText($m),
- 'detail' => $dr,
- ];
- }
- foreach ($detailRows as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
- if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
- continue;
- }
- $detailSidSeen[$sid] = true;
- $m = $mainBySid[$sid];
- $exportLines[] = [
- 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
- 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
- 'company_name' => (string)($dr['company_name'] ?? ''),
- 'CDF' => (string)($m['CDF'] ?? ''),
- 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
- 'gx' => $this->procuremenExportGxText($m),
- 'detail' => $dr,
- ];
- }
- foreach ($mainBySid as $sid => $m) {
- if (isset($detailSidSeen[$sid])) {
- continue;
- }
- $company = trim((string)($m['pick_company_name'] ?? ''));
- $exportLines[] = [
- 'CCYDH' => (string)($m['CCYDH'] ?? ''),
- 'CYJMC' => (string)($m['CYJMC'] ?? ''),
- 'company_name' => $company,
- 'CDF' => (string)($m['CDF'] ?? ''),
- 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
- 'gx' => $this->procuremenExportGxText($m),
- 'detail' => [],
- ];
- }
- $groups = [];
- foreach ($exportLines as $line) {
- $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
- if (!isset($groups[$k])) {
- $groups[$k] = [];
- }
- $groups[$k][] = $line;
- }
- ksort($groups, SORT_STRING);
- $spreadsheet = new Spreadsheet();
- $sheet = $spreadsheet->getActiveSheet();
- $sheet->setTitle('协助明细');
- $mon = (int)substr($ym, 5, 2);
- $sheet->mergeCells('A1:H1');
- $sheet->setCellValue('A1', $mon . '月协助明细');
- $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
- $sheet->getStyle('A1')->getAlignment()
- ->setHorizontal(Alignment::HORIZONTAL_CENTER)
- ->setVertical(Alignment::VERTICAL_CENTER);
- $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
- $col = 'A';
- foreach ($headers as $h) {
- $sheet->setCellValue($col . '2', $h);
- $col++;
- }
- $sheet->getStyle('A2:H2')->getFont()->setBold(true);
- $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
- $rowNum = 3;
- $sumSubtotalCounts = 0;
- $grandAmount = 0.0;
- if ($groups === []) {
- $sheet->mergeCells('A3:H3');
- $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
- $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
- $rowNum = 4;
- } else {
- foreach ($groups as $items) {
- if ($items === []) {
- continue;
- }
- $groupLineCount = count($items);
- $subAmount = 0.0;
- $i = 0;
- foreach ($items as $line) {
- $i++;
- $dr = $line['detail'];
- $amt = $this->procuremenExportAmount($dr);
- $subAmount += $amt;
- $sheet->setCellValue('A' . $rowNum, $i);
- $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
- $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
- $sheet->setCellValue('D' . $rowNum, $line['company_name']);
- $sheet->setCellValue('E' . $rowNum, $line['CDF']);
- $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
- $sheet->setCellValue('G' . $rowNum, $line['gx']);
- $sheet->setCellValue('H' . $rowNum, $amt);
- $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
- $rowNum++;
- }
- $sumSubtotalCounts += $groupLineCount;
- $grandAmount += $subAmount;
- $sheet->setCellValue('A' . $rowNum, $groupLineCount);
- $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
- $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
- $sheet->getStyle('G' . $rowNum)->getAlignment()
- ->setHorizontal(Alignment::HORIZONTAL_RIGHT)
- ->setVertical(Alignment::VERTICAL_CENTER);
- $rowNum++;
- }
- }
- $sheet->setCellValue('A' . $rowNum, '总计');
- $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
- $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
- $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
- $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
- $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
- $lastRow = $rowNum;
- $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
- 'borders' => [
- 'allBorders' => [
- 'borderStyle' => Border::BORDER_THIN,
- 'color' => ['rgb' => '000000'],
- ],
- ],
- ]);
- $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
- if ($lastRow >= 3) {
- $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
- $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
- $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
- $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
- }
- $sheet->getColumnDimension('A')->setWidth(7);
- $sheet->getColumnDimension('B')->setWidth(16);
- $sheet->getColumnDimension('C')->setWidth(52);
- $sheet->getColumnDimension('D')->setWidth(32);
- $sheet->getColumnDimension('E')->setWidth(12);
- $sheet->getColumnDimension('F')->setWidth(44);
- $sheet->getColumnDimension('G')->setWidth(26);
- $sheet->getColumnDimension('H')->setWidth(13);
- $sheet->getRowDimension(1)->setRowHeight(28);
- $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
- $quoteStartRow = $lastRow + 3;
- $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
- if ($quoteLastRow >= $quoteStartRow) {
- $sheet->getColumnDimension('E')->setWidth(28);
- }
- $fileBase = '协助明细_' . str_replace('-', '', $ym);
- $filename = $fileBase . '.xlsx';
- try {
- $this->ensurePurchaseMonthExportLogTable();
- list($adminId, $adminName) = $this->GetUseName();
- Db::table('purchase_month_export_log')->insert([
- 'ym' => $ym,
- 'admin_id' => (int)$adminId,
- 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
- 'row_count' => count($exportLines),
- 'total_amount' => round($grandAmount, 2),
- 'createtime' => time(),
- ]);
- } catch (\Throwable $e) {
- Log::write('month export log: ' . $e->getMessage(), 'error');
- }
- if (ob_get_length()) {
- ob_end_clean();
- }
- $asciiName = 'outward_' . str_replace('-', '', $ym) . '.xlsx';
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
- header('Cache-Control: max-age=0');
- $writer = new Xlsx($spreadsheet);
- $writer->save('php://output');
- $spreadsheet->disconnectWorksheets();
- unset($spreadsheet);
- exit;
- }
- /**
- * 导出用:工序列文案
- */
- protected function procuremenExportGxText(array $r)
- {
- $a = trim((string)($r['CDXMC'] ?? ''));
- $b = trim((string)($r['CGYMC'] ?? ''));
- if ($a !== '' && $b !== '') {
- return $a . ':' . $b;
- }
- return $a !== '' ? $a : $b;
- }
- /**
- * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
- */
- protected function procuremenExportAmount(array $r)
- {
- foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
- if (!array_key_exists($k, $r)) {
- continue;
- }
- $v = $r[$k];
- if ($v === null || $v === '') {
- continue;
- }
- if (is_numeric($v)) {
- return (float)$v;
- }
- $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
- if ($v !== '' && is_numeric($v)) {
- return (float)$v;
- }
- }
- return 0.0;
- }
- /**
- * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
- *
- * @param array<int, array<string, mixed>> $detailRows
- * @param array<int, array<string, mixed>> $mainBySid
- * @return array<int, array<string, mixed>>
- */
- protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
- {
- $lines = [];
- foreach ($detailRows as $dr) {
- if (!is_array($dr)) {
- continue;
- }
- $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
- if ($sid <= 0 || !isset($mainBySid[$sid])) {
- continue;
- }
- if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
- continue;
- }
- $cn = trim((string)($dr['company_name'] ?? ''));
- if ($cn === '') {
- continue;
- }
- $m = $mainBySid[$sid];
- $am = trim((string)($dr['amount'] ?? ''));
- $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
- $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
- $amountText = $amountFilled
- ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
- : '未填写';
- $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
- $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
- if ($deliveryShow === '' && $deliveryRaw !== '') {
- $deliveryShow = $deliveryRaw;
- }
- $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
- ? $deliveryShow
- : '未填写';
- $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
- $lines[] = [
- 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
- 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
- 'gx' => $this->procuremenExportGxText($m),
- 'company_name' => $cn,
- 'amount_text' => $amountText,
- 'amount_num' => $amountFilled ? $amountNum : null,
- 'delivery_text' => $deliveryText,
- 'picked_text' => $picked ? '中标' : '未中标',
- 'picked' => $picked,
- ];
- }
- usort($lines, function ($a, $b) {
- $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
- if ($c !== 0) {
- return $c;
- }
- $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
- if ($c !== 0) {
- return $c;
- }
- if (!empty($a['picked']) !== !empty($b['picked'])) {
- return !empty($a['picked']) ? -1 : 1;
- }
- return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
- });
- return $lines;
- }
- /**
- * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
- *
- * @param array<int, array<string, mixed>> $quoteLines
- */
- protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
- {
- $mon = (int)substr($ym, 5, 2);
- $titleRow = $startRow;
- $headerRow = $startRow + 1;
- $dataStartRow = $startRow + 2;
- $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
- $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
- $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
- $sheet->getStyle('A' . $titleRow)->getAlignment()
- ->setHorizontal(Alignment::HORIZONTAL_CENTER)
- ->setVertical(Alignment::VERTICAL_CENTER);
- $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
- $col = 'A';
- foreach ($headers as $h) {
- $sheet->setCellValue($col . $headerRow, $h);
- $col++;
- }
- $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
- $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
- $rowNum = $dataStartRow;
- if ($quoteLines === []) {
- $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
- $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
- $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
- $rowNum = $dataStartRow + 1;
- } else {
- $i = 0;
- foreach ($quoteLines as $line) {
- $i++;
- $sheet->setCellValue('A' . $rowNum, $i);
- $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
- $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
- $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
- $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
- if ($line['amount_num'] !== null) {
- $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
- $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
- } else {
- $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
- }
- $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
- $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
- if (!empty($line['picked'])) {
- $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
- }
- $rowNum++;
- }
- }
- $lastRow = $rowNum - 1;
- if ($lastRow >= $headerRow) {
- $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
- 'borders' => [
- 'allBorders' => [
- 'borderStyle' => Border::BORDER_THIN,
- 'color' => ['rgb' => '000000'],
- ],
- ],
- ]);
- $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
- $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
- $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
- $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
- $sheet->getRowDimension($titleRow)->setRowHeight(28);
- }
- return $lastRow;
- }
- /**
- * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
- */
- protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
- {
- $s = trim($ccydh);
- if ($s === '') {
- return 'ORDER';
- }
- $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
- $s = trim($s, '._-');
- if ($s === '') {
- return 'ORDER';
- }
- if (function_exists('mb_substr')) {
- return mb_substr($s, 0, 80, 'UTF-8');
- }
- return strlen($s) <= 80 ? $s : substr($s, 0, 80);
- }
- /**
- * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
- * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
- *
- * @return array{objectKey: string, webPath: string}
- */
- protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
- {
- $sid = (int)$scydgyId;
- $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
- $y = date('Y');
- $m = date('m');
- $d = date('d');
- $basename = $safeOrder . '_' . $sid . '.pdf';
- $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
- return [
- 'objectKey' => $objectKey,
- 'webPath' => '/' . $objectKey,
- ];
- }
- /**
- * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
- * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
- * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
- *
- * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
- */
- protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
- {
- if (!$this->isValidScydgyRowId($scydgyId)) {
- return '';
- }
- $ids = trim((string)$scydgyId);
- $prep = $this->prepareProcuremenDetailsView($ids);
- if (!$prep['ok']) {
- return '';
- }
- $ccydh = $prep['ccydh'];
- $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
- $objectKey = $paths['objectKey'];
- $webPath = $paths['webPath'];
- $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
- $this->view->assign([
- 'pdf_export' => 1,
- 'pdfMetaLine' => $meta,
- ]);
- // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
- $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
- $this->view->engine->layout(false);
- try {
- $html = $this->view->fetch('procuremen/details_pdf_shell');
- } catch (\Throwable $e) {
- if ($restoreLayout) {
- $this->view->engine->layout($restoreLayout);
- }
- Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
- $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
- return '';
- }
- if ($restoreLayout) {
- $this->view->engine->layout($restoreLayout);
- }
- $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
- $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
- if (!is_dir($tempDir)) {
- @mkdir($tempDir, 0755, true);
- }
- $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
- try {
- $mpdf = new \Mpdf\Mpdf([
- 'mode' => 'utf-8',
- 'format' => 'A4',
- 'margin_left' => 12,
- 'margin_right' => 12,
- 'margin_top' => 14,
- 'margin_bottom' => 14,
- 'tempDir' => $tempDir,
- 'autoScriptToLang' => true,
- 'autoLangToFont' => true,
- ]);
- // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
- // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
- $mpdf->SetBasePath('http://127.0.0.1/');
- $mpdf->WriteHTML($html);
- $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
- } catch (\Throwable $e) {
- Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
- if (is_file($tempPdf)) {
- @unlink($tempPdf);
- }
- return '';
- }
- $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
- if ($ossUrl !== '') {
- @unlink($tempPdf);
- $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
- return $ossUrl;
- }
- $pi = pathinfo($objectKey);
- $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
- $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
- if ($baseFile === '') {
- @unlink($tempPdf);
- return '';
- }
- $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
- if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
- Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
- @unlink($tempPdf);
- return '';
- }
- $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
- if (!@copy($tempPdf, $fullPath)) {
- Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
- @unlink($tempPdf);
- return '';
- }
- @unlink($tempPdf);
- $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
- return $webPath;
- }
- /**
- * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
- */
- protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
- {
- if ($scydgyId <= 0 || $webPath === '') {
- return;
- }
- try {
- Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
- } catch (\Throwable $e) {
- Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
- }
- }
- /**
- * 整理短信变量:去空格;联系人姓名为空时用公司名称
- *
- * @param array<string, string> $vars
- * @return array<string, string>
- */
- protected function normalizeSmsTemplateVars(array $vars): array
- {
- $out = [];
- foreach ($vars as $k => $v) {
- $out[(string)$k] = trim((string)$v);
- }
- if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
- $out['contact_name'] = $out['company_name'];
- }
- return $out;
- }
- /**
- * 按手机号或公司名称查 customer 表联系人姓名
- */
- protected function resolveCustomerContactName(string $phone, string $companyName): string
- {
- $phone = trim($phone);
- $companyName = trim($companyName);
- try {
- if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
- $row = Db::table('customer')
- ->where(function ($q) use ($phone) {
- $q->where('phone', $phone)->whereOr('account', $phone);
- })
- ->order('id', 'asc')
- ->find();
- if (is_array($row)) {
- $nm = trim((string)($row['username'] ?? ''));
- if ($nm !== '') {
- return $nm;
- }
- }
- }
- if ($companyName !== '') {
- $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
- if (is_array($row)) {
- return trim((string)($row['username'] ?? ''));
- }
- }
- } catch (\Throwable $e) {
- }
- return '';
- }
- /**
- * 模版纯文本转邮件 HTML:换行转 <br>,保留已替换进的 <a> 等标签
- */
- protected function plainTextToHtmlEmailBody(string $text): string
- {
- $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
- $parts = explode("\n", $text);
- $out = [];
- foreach ($parts as $line) {
- if (preg_match('/<a\s+[^>]*href=/i', $line)) {
- $out[] = $line;
- } else {
- $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
- }
- }
- return implode("<br>\n", $out);
- }
- /**
- * 短信场景:去掉链接类变量,避免误填 URL
- *
- * @param array<string, string> $vars
- * @return array<string, string>
- */
- protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
- {
- if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
- return $vars;
- }
- foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
- $vars[$k] = '';
- }
- return $vars;
- }
- /**
- * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
- *
- * @param array<string, string> $vars
- */
- protected function renderNotifyTemplate(string $scene, array $vars): string
- {
- $vars = $this->normalizeSmsTemplateVars($vars);
- $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
- $row = $this->loadNotifyTemplateRow($scene);
- if ($row === null) {
- throw new \Exception($this->notifyTemplateMissingMessage($scene));
- }
- $tpl = trim((string)($row['content'] ?? ''));
- if ($tpl === '') {
- throw new \Exception($this->notifyTemplateMissingMessage($scene));
- }
- foreach ($vars as $k => $v) {
- $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
- }
- // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
- $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
- return $tpl;
- }
- protected function resolveProcuremenEmailSubject(string $scene): string
- {
- $map = [
- 'review_email' => '您有新的协助加工订单',
- ];
- $subject = trim((string)($map[$scene] ?? ''));
- if ($subject === '') {
- $this->error('未配置邮件主题:' . $scene);
- }
- return $subject;
- }
- protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
- {
- $map = [
- 'review_email' => '协助下发-邮箱',
- 'review_sms' => '协助下发-短信',
- 'confirm_ok' => '采购确认-通过',
- 'confirm_fail' => '采购确认-未通过',
- ];
- $label = $map[$scene] ?? $scene;
- if ($titleRequired) {
- return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
- }
- return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
- }
- /**
- * 是否开启协助通知演练(不发真实短信/邮件)
- */
- protected function isProcuremenNotifyDryRun(): bool
- {
- return (bool)Config::get('procuremen_notify_dry_run');
- }
- /**
- * @param array<string, mixed> $payload
- */
- protected function recordNotifyDryRunPreview(array $payload): void
- {
- $this->notifyDryRunPreview[] = $payload;
- Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
- }
- /**
- * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
- * @throws \Exception
- */
- protected function smsbao($phone, $content)
- {
- if ($this->isProcuremenNotifyDryRun()) {
- $this->recordNotifyDryRunPreview([
- 'scene' => 'sms_only',
- 'phone' => $phone,
- 'sms_content' => $content,
- ]);
- return;
- }
- $statusStr = [
- '0' => '短信发送成功',
- '-1' => '参数不全',
- '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
- '30' => '密码错误',
- '40' => '账号不存在',
- '41' => '余额不足',
- '42' => '帐户已过期',
- '43' => 'IP地址限制',
- '50' => '内容含有敏感词',
- ];
- $smsapi = 'http://api.smsbao.com/';
- $user = 'zhuwei123';
- $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
- $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
- $result = @file_get_contents($sendurl);
- if ($result === false) {
- \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
- throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
- }
- $result = trim((string)$result);
- if ($result !== '0') {
- $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
- \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
- throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
- }
- }
- }
|