Procuremen.php 303 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenStatus;
  8. use app\common\library\ProcuremenTime;
  9. use PHPMailer\PHPMailer\PHPMailer;
  10. use think\Config;
  11. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  12. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  13. use PhpOffice\PhpSpreadsheet\Style\Border;
  14. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  15. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  16. use think\Db;
  17. use think\Log;
  18. class Procuremen extends Backend
  19. {
  20. /**
  21. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  22. */
  23. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  24. /**
  25. * Procuremen模型对象
  26. * @var \app\admin\model\Procuremen
  27. */
  28. protected $model = null;
  29. /**
  30. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  31. */
  32. protected $notifyDryRunPreview = [];
  33. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  34. protected $procuremenRedisCache = null;
  35. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  36. protected $pickHiddenScydgySetCache = null;
  37. /**
  38. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  39. * @var array
  40. */
  41. protected $noNeedRight = [
  42. 'pickreview', 'review', 'reviewcompanies',
  43. ];
  44. public function _initialize()
  45. {
  46. parent::_initialize();
  47. $this->model = new \app\admin\model\Procuremen;
  48. $this->maybeMigrateLegacyWflowStatusText();
  49. $this->assignProcuremenAuthConfig();
  50. }
  51. /**
  52. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  53. */
  54. protected function maybeMigrateLegacyWflowStatusText(): void
  55. {
  56. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  57. if (is_file($flagFile)) {
  58. return;
  59. }
  60. $map = [
  61. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  62. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  63. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  64. '3' => ProcuremenStatus::WFLOW_APPROVED,
  65. ];
  66. try {
  67. foreach ($map as $num => $text) {
  68. Db::table('purchase_order')
  69. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  70. ->update(['wflow_status' => $text]);
  71. }
  72. @file_put_contents($flagFile, date('c'));
  73. } catch (\Throwable $e) {
  74. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  75. }
  76. }
  77. /**
  78. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  79. *
  80. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  81. */
  82. protected function hasProcuremenPerm(array $actions): bool
  83. {
  84. foreach ($actions as $action) {
  85. $action = strtolower(trim((string)$action));
  86. if ($action === '') {
  87. continue;
  88. }
  89. if (strpos($action, 'procuremen/') !== 0) {
  90. $action = 'procuremen/' . $action;
  91. }
  92. if ($this->auth->check($action)) {
  93. return true;
  94. }
  95. }
  96. $suffixes = [];
  97. foreach ($actions as $action) {
  98. $action = strtolower(trim((string)$action));
  99. $action = preg_replace('#^procuremen/#', '', $action);
  100. if ($action !== '') {
  101. $suffixes[$action] = true;
  102. }
  103. }
  104. if ($suffixes === []) {
  105. return false;
  106. }
  107. try {
  108. foreach ($this->auth->getRuleList() as $rule) {
  109. $rule = strtolower((string)$rule);
  110. if (strpos($rule, 'procuremen/') !== 0) {
  111. continue;
  112. }
  113. foreach (array_keys($suffixes) as $suffix) {
  114. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  115. return true;
  116. }
  117. }
  118. }
  119. } catch (\Throwable $e) {
  120. }
  121. return false;
  122. }
  123. /**
  124. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  125. *
  126. * @param string[] $actions
  127. */
  128. protected function hasProcuremenPermStrict(array $actions): bool
  129. {
  130. foreach ($actions as $action) {
  131. $action = strtolower(trim((string)$action));
  132. if ($action === '') {
  133. continue;
  134. }
  135. if (strpos($action, 'procuremen/') !== 0) {
  136. $action = 'procuremen/' . $action;
  137. }
  138. if ($this->auth->check($action)) {
  139. return true;
  140. }
  141. }
  142. return false;
  143. }
  144. /**
  145. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  146. *
  147. * @param string[] $titles
  148. */
  149. protected function authHasAssignedRuleTitle(array $titles): bool
  150. {
  151. $titles = array_values(array_filter(array_map('trim', $titles)));
  152. if ($titles === []) {
  153. return false;
  154. }
  155. try {
  156. $ids = $this->auth->getRuleIds();
  157. if (in_array('*', $ids, true)) {
  158. return true;
  159. }
  160. if ($ids === []) {
  161. return false;
  162. }
  163. $rows = Db::name('auth_rule')
  164. ->where('status', 'normal')
  165. ->whereIn('id', $ids)
  166. ->column('title');
  167. foreach ($rows as $title) {
  168. $t = trim((string)$title);
  169. if ($t !== '' && in_array($t, $titles, true)) {
  170. return true;
  171. }
  172. }
  173. } catch (\Throwable $e) {
  174. }
  175. return false;
  176. }
  177. protected function procuremenCanPickDelete(): bool
  178. {
  179. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  180. return true;
  181. }
  182. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  183. }
  184. protected function procuremenCanComplete(): bool
  185. {
  186. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  187. return true;
  188. }
  189. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  190. }
  191. protected function procuremenCanDispatch(): bool
  192. {
  193. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  194. }
  195. /**
  196. * 前端按钮显隐(Config.procuremenAuth)
  197. */
  198. protected function assignProcuremenAuthConfig(): void
  199. {
  200. $authMap = [
  201. 'pickreview' => $this->procuremenCanDispatch(),
  202. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  203. 'pickdelete' => $this->procuremenCanPickDelete(),
  204. 'completedirectly' => $this->procuremenCanComplete(),
  205. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  206. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  207. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  208. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  209. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  210. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  211. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  212. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  213. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  214. 'details' => $this->hasProcuremenPerm(['details']),
  215. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  216. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  217. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  218. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  219. 'add' => $this->hasProcuremenPerm(['add']),
  220. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  221. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  222. ];
  223. $this->assignconfig('procuremenAuth', $authMap);
  224. }
  225. /**
  226. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  227. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  228. *
  229. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  230. */
  231. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  232. {
  233. static $mprocCfgLoaded = false;
  234. if (!$mprocCfgLoaded) {
  235. $mprocCfgLoaded = true;
  236. if (is_file(APP_PATH . 'extra/mproc.php')) {
  237. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  238. }
  239. }
  240. $eid = (int)$purchaseOrderDetailId;
  241. $base = $this->resolveMprocMobilePublicBaseUrl();
  242. if ($base === '') {
  243. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  244. }
  245. $path = trim((string)Config::get('mproc.mobile_index_path'));
  246. if ($path === '') {
  247. $path = '/index.php/index/index/index';
  248. } else {
  249. $path = '/' . ltrim($path, '/');
  250. }
  251. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  252. if ($eid > 0) {
  253. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  254. }
  255. return $base . $path . '?main_tab=orders';
  256. }
  257. /**
  258. * 邮件/短信外链:须为带点的公网域名
  259. */
  260. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  261. {
  262. $u = trim((string)$baseUrl);
  263. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  264. return false;
  265. }
  266. $host = parse_url($u, PHP_URL_HOST);
  267. if (!is_string($host) || $host === '') {
  268. return false;
  269. }
  270. if (strcasecmp($host, 'localhost') === 0) {
  271. return false;
  272. }
  273. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  274. return false;
  275. }
  276. if (strpos($host, '.') === false) {
  277. return false;
  278. }
  279. return true;
  280. }
  281. /**
  282. * 解析用于协助邮件/短信的手机端站点根
  283. */
  284. protected function resolveMprocMobilePublicBaseUrl()
  285. {
  286. $candidates = [];
  287. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  288. $candidates[] = trim((string)Config::get('site.indexurl'));
  289. $cdn = trim((string)Config::get('site.cdnurl'));
  290. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  291. $candidates[] = rtrim($cdn, '/');
  292. }
  293. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  294. $candidates[] = $reqBase;
  295. foreach ($candidates as $c) {
  296. if ($c === '') {
  297. continue;
  298. }
  299. $c = rtrim($c, '/');
  300. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  301. return $c;
  302. }
  303. }
  304. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  305. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  306. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  307. return $reqBase;
  308. }
  309. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  310. return '';
  311. }
  312. /**
  313. * 获取 Redis 中 procuremen_redis
  314. */
  315. protected function ProcuremenRedis(): array
  316. {
  317. if ($this->procuremenRedisCache !== null) {
  318. return $this->procuremenRedisCache;
  319. }
  320. try {
  321. $redis = redis();
  322. $raw = $redis->get('procuremen_redis');
  323. if ($raw === false || $raw === '') {
  324. $this->procuremenRedisCache = [];
  325. return $this->procuremenRedisCache;
  326. }
  327. $decoded = json_decode($raw, true);
  328. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  329. $this->procuremenRedisCache = [];
  330. return $this->procuremenRedisCache;
  331. }
  332. $this->procuremenRedisCache = $decoded['data'];
  333. return $this->procuremenRedisCache;
  334. } catch (\Throwable $e) {
  335. $this->procuremenRedisCache = [];
  336. return $this->procuremenRedisCache;
  337. }
  338. }
  339. /**
  340. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  341. *
  342. * @return array<int, array<string, mixed>>
  343. */
  344. protected function procuremenFetchErpPoolFromDb(): array
  345. {
  346. try {
  347. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  348. $endTime = date('Y-m-d 23:59:59');
  349. $list = Db::table('scydgy')
  350. ->alias('a')
  351. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  352. ->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')
  353. ->where([
  354. 'a.bwjg' => 1,
  355. 'a.iEndBz' => 0,
  356. 'a.iType' => 0,
  357. 'a.iStatus' => 10,
  358. ])
  359. ->where('a.dStamp', '>=', $startTime)
  360. ->where('a.dStamp', '<=', $endTime)
  361. ->order('a.dStamp', 'desc')
  362. ->select();
  363. if (!is_array($list)) {
  364. return [];
  365. }
  366. try {
  367. $redis = redis();
  368. $payload = [
  369. 'code' => 200,
  370. 'msg' => 'success',
  371. 'data' => $list,
  372. ];
  373. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  374. $this->procuremenRedisCache = $list;
  375. } catch (\Throwable $e) {
  376. }
  377. return $list;
  378. } catch (\Throwable $e) {
  379. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  380. return [];
  381. }
  382. }
  383. /**
  384. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  385. *
  386. * @return array<int, array<string, mixed>>
  387. */
  388. protected function procuremenEnsureRedisPool(): array
  389. {
  390. $pool = $this->ProcuremenRedis();
  391. if (is_array($pool) && $pool !== []) {
  392. return $pool;
  393. }
  394. static $warmed = false;
  395. if ($warmed) {
  396. return is_array($pool) ? $pool : [];
  397. }
  398. $warmed = true;
  399. return $this->procuremenFetchErpPoolFromDb();
  400. }
  401. /**
  402. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  403. *
  404. * @param array<string, mixed> $row
  405. */
  406. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  407. {
  408. $t = $this->procuremenRowListSortTime($row, $primary);
  409. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  410. return null;
  411. }
  412. $mo = (int)$m[2];
  413. if ($mo < 1 || $mo > 12) {
  414. return null;
  415. }
  416. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  417. }
  418. /**
  419. * @param array<int, array{year:string, months:array}> $sidebar
  420. * @return array<int, array{year:string, months:array}>
  421. */
  422. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  423. {
  424. $ym = trim($ym);
  425. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  426. return $sidebar;
  427. }
  428. foreach ($sidebar as $block) {
  429. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  430. continue;
  431. }
  432. foreach ($block['months'] as $item) {
  433. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  434. return $sidebar;
  435. }
  436. }
  437. }
  438. $y = substr($ym, 0, 4);
  439. $mo = (int)substr($ym, 5, 2);
  440. $sidebar[] = [
  441. 'year' => $y,
  442. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  443. ];
  444. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  445. }
  446. /**
  447. * @param array<int, array{year:string, months:array}> $sidebar
  448. * @return string[]
  449. */
  450. protected function flattenProcuremenSidebarYms(array $sidebar): array
  451. {
  452. $yms = [];
  453. foreach ($sidebar as $block) {
  454. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  455. continue;
  456. }
  457. foreach ($block['months'] as $item) {
  458. if (!is_array($item)) {
  459. continue;
  460. }
  461. $ym = trim((string)($item['ym'] ?? ''));
  462. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  463. $yms[$ym] = true;
  464. }
  465. }
  466. }
  467. return array_keys($yms);
  468. }
  469. /**
  470. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  471. */
  472. protected function GetIndexYearMonths()
  473. {
  474. $ymSet = [];
  475. $pool = $this->procuremenEnsureRedisPool();
  476. foreach ($pool as $r) {
  477. if (!is_array($r)) {
  478. continue;
  479. }
  480. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  481. if ($ym !== null) {
  482. $ymSet[$ym] = true;
  483. }
  484. }
  485. foreach ($this->loadPickManualOrderRows() as $r) {
  486. if (!is_array($r)) {
  487. continue;
  488. }
  489. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  490. if ($ym !== null) {
  491. $ymSet[$ym] = true;
  492. }
  493. }
  494. $ymList = array_keys($ymSet);
  495. if ($ymList === []) {
  496. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  497. }
  498. return $this->buildYearMonthSidebar($ymList);
  499. }
  500. /**
  501. * @param string[] $ymList 形如 2026-06
  502. * @return array<int, array{year:string, months:array}>
  503. */
  504. protected function buildYearMonthSidebar(array $ymList): array
  505. {
  506. rsort($ymList, SORT_STRING);
  507. $byYear = [];
  508. foreach ($ymList as $ym) {
  509. $y = substr($ym, 0, 4);
  510. $mo = (int)substr($ym, 5, 2);
  511. if (!isset($byYear[$y])) {
  512. $byYear[$y] = [];
  513. }
  514. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  515. }
  516. krsort($byYear, SORT_NUMERIC);
  517. foreach ($byYear as $y => $items) {
  518. usort($byYear[$y], function ($a, $b) {
  519. return strcmp($b['ym'], $a['ym']);
  520. });
  521. }
  522. $sidebar = [];
  523. foreach ($byYear as $y => $months) {
  524. $sidebar[] = ['year' => $y, 'months' => $months];
  525. }
  526. return $sidebar;
  527. }
  528. /**
  529. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  530. */
  531. protected function GetIssuedOrderYearMonths(string $stage): array
  532. {
  533. $ymSet = [];
  534. try {
  535. $query = Db::table('purchase_order');
  536. $this->applyPurchaseOrderNotDeletedWhere($query);
  537. if ($stage === 'audit') {
  538. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  539. } elseif ($stage === 'confirm') {
  540. $this->applyPurchaseOrderConfirmStageWhere($query);
  541. } else {
  542. return $this->GetIndexYearMonths();
  543. }
  544. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  545. if (is_array($rows)) {
  546. foreach ($rows as $r) {
  547. if (!is_array($r)) {
  548. continue;
  549. }
  550. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  551. if ($ym !== null) {
  552. $ymSet[$ym] = true;
  553. }
  554. }
  555. }
  556. } catch (\Throwable $e) {
  557. $ymSet = [];
  558. }
  559. $ymList = array_keys($ymSet);
  560. if ($ymList === []) {
  561. $def = $this->resolveProcuremenDefaultYm($stage);
  562. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  563. }
  564. return $this->buildYearMonthSidebar($ymList);
  565. }
  566. /**
  567. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  568. */
  569. protected function resolveProcuremenDefaultYm(string $stage): string
  570. {
  571. if ($stage === 'pick') {
  572. return date('Y-m');
  573. }
  574. try {
  575. $query = Db::table('purchase_order');
  576. $this->applyPurchaseOrderNotDeletedWhere($query);
  577. if ($stage === 'audit') {
  578. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  579. } elseif ($stage === 'confirm') {
  580. $this->applyPurchaseOrderConfirmStageWhere($query);
  581. } else {
  582. return date('Y-m');
  583. }
  584. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  585. if ($latest === null || $latest === '') {
  586. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  587. }
  588. $t = $this->formatProcuremenDetailTime($latest);
  589. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  590. return $m[1] . '-' . $m[2];
  591. }
  592. } catch (\Throwable $e) {
  593. }
  594. return date('Y-m');
  595. }
  596. protected function applyPurchaseOrderNotDeletedWhere($query): void
  597. {
  598. $query->whereRaw(
  599. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  600. );
  601. }
  602. /**
  603. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  604. */
  605. protected function applyPurchaseOrderConfirmStageWhere($query): void
  606. {
  607. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  608. $quoted = [];
  609. foreach ($vals as $v) {
  610. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  611. }
  612. if ($quoted === []) {
  613. $query->whereRaw('1 = 0');
  614. return;
  615. }
  616. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  617. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  618. }
  619. /**
  620. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  621. *
  622. * @param array<string, mixed> $row
  623. * @return array<string, mixed>
  624. */
  625. protected function normalizePurchaseOrderListTimeRow(array $row): array
  626. {
  627. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  628. $pick = trim((string)($row['pick_time'] ?? ''));
  629. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  630. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  631. $t = trim((string)($row[$key] ?? ''));
  632. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  633. $row['pick_time'] = $t;
  634. break;
  635. }
  636. }
  637. }
  638. return $row;
  639. }
  640. /**
  641. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  642. */
  643. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  644. {
  645. if (!in_array($stage, ['audit', 'confirm'], true)) {
  646. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  647. }
  648. if ($pool === []) {
  649. $def = $this->resolveProcuremenDefaultYm($stage);
  650. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  651. }
  652. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  653. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  654. return false;
  655. }
  656. $monthStart = $ym . '-01 00:00:00';
  657. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  658. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  659. return $probe !== [];
  660. };
  661. if ($tryYm($requestedYm)) {
  662. return $requestedYm;
  663. }
  664. $fallback = $this->resolveProcuremenDefaultYm($stage);
  665. if ($tryYm($fallback)) {
  666. return $fallback;
  667. }
  668. $bestYm = '';
  669. $bestTime = '';
  670. foreach ($pool as $row) {
  671. if (!is_array($row)) {
  672. continue;
  673. }
  674. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  675. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  676. continue;
  677. }
  678. $ymRow = $m[1];
  679. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  680. $bestTime = $t;
  681. $bestYm = $ymRow;
  682. }
  683. }
  684. if ($bestYm !== '') {
  685. return $bestYm;
  686. }
  687. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  688. }
  689. protected function isPurchaseOrderDetailVoid(array $row): bool
  690. {
  691. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  692. return true;
  693. }
  694. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  695. }
  696. /**
  697. * 仅当前有效下发明细(排除废弃归档)
  698. */
  699. protected function applyActivePurchaseOrderDetailWhere($query): void
  700. {
  701. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  702. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  703. }
  704. /**
  705. * @param array<string, mixed> $detailRow
  706. */
  707. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  708. {
  709. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  710. return false;
  711. }
  712. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  713. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  714. }
  715. /**
  716. * 废弃退回初选:下发明细标记归档,不物理删除
  717. *
  718. * @param array<int, int|string> $scydgyIds
  719. */
  720. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  721. {
  722. $ids = [];
  723. foreach ($scydgyIds as $sid) {
  724. $n = (int)$sid;
  725. if ($this->isValidScydgyRowId($n) || $n < 0) {
  726. $ids[$n] = true;
  727. }
  728. }
  729. if ($ids === []) {
  730. return;
  731. }
  732. $void = ProcuremenStatus::POD_VOID;
  733. Db::table('purchase_order_detail')
  734. ->where('scydgy_id', 'in', array_keys($ids))
  735. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  736. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  737. ->update([
  738. 'status' => $void,
  739. 'status_name' => $void,
  740. ]);
  741. }
  742. /**
  743. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  744. */
  745. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  746. {
  747. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  748. $norm = function (string $col) use ($p): string {
  749. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  750. };
  751. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  752. $parts = [];
  753. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  754. if ($key === 'createtime') {
  755. $parts[] = $createtime;
  756. } else {
  757. $parts[] = $norm($key);
  758. }
  759. }
  760. return 'COALESCE(' . implode(', ', $parts) . ')';
  761. }
  762. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  763. {
  764. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  765. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  766. }
  767. /**
  768. * @return array<int, array<string, mixed>>
  769. */
  770. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  771. {
  772. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  773. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  774. try {
  775. $query = Db::table('purchase_order')->field($fields);
  776. $this->applyPurchaseOrderNotDeletedWhere($query);
  777. if ($stage === 'audit') {
  778. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  779. } elseif ($stage === 'confirm') {
  780. $this->applyPurchaseOrderConfirmStageWhere($query);
  781. } else {
  782. return [];
  783. }
  784. $query->order('pick_time', 'desc')->order('id', 'desc');
  785. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  786. $monthStart = $ym . '-01 00:00:00';
  787. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  788. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  789. }
  790. $rows = $query->select();
  791. } catch (\Throwable $e) {
  792. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  793. $rows = [];
  794. }
  795. return is_array($rows) ? $rows : [];
  796. }
  797. /**
  798. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  799. */
  800. protected function resolveProcuremenListStage(): string
  801. {
  802. $tab = trim((string)$this->request->request('wff_tab', ''));
  803. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  804. return $tab;
  805. }
  806. $action = strtolower((string)$this->request->action());
  807. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  808. return $action;
  809. }
  810. return 'pick';
  811. }
  812. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  813. {
  814. $rootTrue = rtrim((string)$this->request->root(true), '/');
  815. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  816. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  817. $indexPhpRoot = $rootTrue . '/index.php';
  818. }
  819. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  820. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  821. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  822. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  823. $this->view->assign('defaultYm', $defaultYm);
  824. $this->view->assign('sidebarYearMonths', $sidebar);
  825. $this->view->assign('procuremenStage', $stage);
  826. $this->view->assign('procuremenPageTitle', $pageTitle);
  827. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  828. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  829. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  830. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  831. }
  832. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  833. public function pick()
  834. {
  835. $this->request->filter(['strip_tags', 'trim']);
  836. if (!$this->request->isAjax()) {
  837. $this->assignProcuremenListPage('pick', '协助下发');
  838. return $this->view->fetch('procuremen/index');
  839. }
  840. return $this->index();
  841. }
  842. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  843. public function audit()
  844. {
  845. $this->request->filter(['strip_tags', 'trim']);
  846. if (!$this->request->isAjax()) {
  847. $this->assignProcuremenListPage('audit', '确认供应商');
  848. return $this->view->fetch('procuremen/index');
  849. }
  850. return $this->index();
  851. }
  852. /** 采购确认(定标) */
  853. public function confirm()
  854. {
  855. $this->request->filter(['strip_tags', 'trim']);
  856. if (!$this->request->isAjax()) {
  857. $this->assignProcuremenListPage('confirm', '采购确认');
  858. return $this->view->fetch('procuremen/index');
  859. }
  860. return $this->index();
  861. }
  862. /**
  863. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  864. */
  865. public function index()
  866. {
  867. $this->request->filter(['strip_tags', 'trim']);
  868. if (!$this->request->isAjax()) {
  869. $this->assignProcuremenListPage('pick', '协助下发');
  870. return $this->view->fetch('procuremen/index');
  871. }
  872. if ($this->request->request('keyField')) {
  873. return $this->selectpage();
  874. }
  875. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  876. $limit = max(10, min(500, (int)$limit));
  877. $ym = $this->request->request('ym', '');
  878. $ym = is_string($ym) ? trim($ym) : '';
  879. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  880. $wffTab = $this->resolveProcuremenListStage();
  881. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  882. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  883. ? $this->resolveProcuremenDefaultYm($wffTab)
  884. : date('Y-m');
  885. }
  886. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  887. $ym = date('Y-m');
  888. }
  889. $monthStart = $ym . '-01 00:00:00';
  890. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  891. $search = trim((string)$this->request->get('search', ''));
  892. $hasActiveSearch = ($search !== '');
  893. if (!$hasActiveSearch) {
  894. $filterStr = $this->request->get('filter', '');
  895. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  896. $arr = json_decode($filterStr, true);
  897. if (is_array($arr) && count($arr) > 0) {
  898. foreach ($arr as $v) {
  899. if (is_array($v)) {
  900. if (array_filter($v, function ($x) {
  901. return $x !== '' && $x !== null;
  902. })) {
  903. $hasActiveSearch = true;
  904. break;
  905. }
  906. } elseif ($v !== '' && $v !== null) {
  907. $hasActiveSearch = true;
  908. break;
  909. }
  910. }
  911. }
  912. }
  913. }
  914. $applyMonthRange = !$hasActiveSearch;
  915. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  916. $opArr = (array)json_decode($this->request->get('op', ''), true);
  917. try {
  918. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  919. if ($wffTab === 'audit') {
  920. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  921. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  922. );
  923. } elseif ($wffTab === 'confirm') {
  924. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  925. if ($dbRows === []) {
  926. try {
  927. $dbRows = Db::table('purchase_order')
  928. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  929. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  930. ->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%\')')
  931. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  932. ->order('pick_time', 'desc')->order('id', 'desc')
  933. ->select();
  934. } catch (\Throwable $e) {
  935. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  936. $dbRows = [];
  937. }
  938. }
  939. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  940. if ($pool === []) {
  941. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  942. }
  943. } else {
  944. $pool = $this->procuremenEnsureRedisPool();
  945. if (!is_array($pool)) {
  946. $pool = [];
  947. }
  948. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  949. $hideSet = $this->loadPickHiddenScydgySet();
  950. if ($pool !== [] && $hideSet !== []) {
  951. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  952. if (!is_array($r)) {
  953. return false;
  954. }
  955. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  956. return $id <= 0 || !isset($hideSet[$id]);
  957. }));
  958. }
  959. $manualPool = $this->loadPickManualOrderRows();
  960. if ($manualPool !== []) {
  961. $pool = array_merge($pool, $manualPool);
  962. }
  963. if ($pool === []) {
  964. return json([
  965. 'total' => 0,
  966. 'rows' => [],
  967. ]);
  968. }
  969. }
  970. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  971. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  972. $monthStart = $ym . '-01 00:00:00';
  973. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  974. }
  975. $filtered = $this->filterProcuremenIndexPool(
  976. $pool,
  977. $monthStart,
  978. $monthEnd,
  979. $applyMonthRange,
  980. $search,
  981. $filterArr,
  982. $opArr,
  983. $listTimePrimary
  984. );
  985. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  986. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  987. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  988. }
  989. $sortField = 'ID';
  990. if (is_string($sort) && $sort !== '') {
  991. $parts = explode(',', $sort);
  992. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  993. if ($sortField === '') {
  994. $sortField = 'ID';
  995. }
  996. }
  997. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  998. $nFiltered = count($filtered);
  999. if ($nFiltered > 1) {
  1000. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1001. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1002. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1003. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1004. if ($ta === $tb) {
  1005. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1006. }
  1007. if ($ta === '') {
  1008. return 1;
  1009. }
  1010. if ($tb === '') {
  1011. return -1;
  1012. }
  1013. return strcmp($ta, $tb) * $ord;
  1014. });
  1015. } elseif ($sortField === 'ID') {
  1016. $sortKeys = [];
  1017. foreach ($filtered as $i => $row) {
  1018. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1019. }
  1020. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1021. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1022. } elseif ($sortField === 'CCYDH') {
  1023. usort($filtered, function ($a, $b) use ($ord) {
  1024. $sa = trim((string)($a['CCYDH'] ?? ''));
  1025. $sb = trim((string)($b['CCYDH'] ?? ''));
  1026. if ($sa === $sb) {
  1027. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1028. }
  1029. if ($sa === '') {
  1030. return 1;
  1031. }
  1032. if ($sb === '') {
  1033. return -1;
  1034. }
  1035. return strcmp($sa, $sb) * $ord;
  1036. });
  1037. } else {
  1038. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1039. $va = $a[$sortField] ?? null;
  1040. $vb = $b[$sortField] ?? null;
  1041. $sa = (string)$va;
  1042. $sb = (string)$vb;
  1043. if ($sa === $sb) {
  1044. return 0;
  1045. }
  1046. return strcmp($sa, $sb) * $ord;
  1047. });
  1048. }
  1049. }
  1050. $offset = max(0, (int)$offset);
  1051. $limit = max(1, (int)$limit);
  1052. $rows = array_slice($filtered, $offset, $limit);
  1053. foreach ($rows as &$rw) {
  1054. if (!is_array($rw)) {
  1055. continue;
  1056. }
  1057. $rid = (int)($rw['ID'] ?? 0);
  1058. $rw['_iss_out'] = ($wffTab !== 'pick');
  1059. }
  1060. unset($rw);
  1061. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1062. $idList = [];
  1063. foreach ($rows as $rw) {
  1064. if (!is_array($rw)) {
  1065. continue;
  1066. }
  1067. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1068. foreach ($rw['_order_merge_rows'] as $mr) {
  1069. $mid = (int)($mr['ID'] ?? 0);
  1070. if ($this->isValidScydgyRowId($mid)) {
  1071. $idList[$mid] = true;
  1072. }
  1073. }
  1074. }
  1075. $id = (int)($rw['ID'] ?? 0);
  1076. if ($this->isValidScydgyRowId($id)) {
  1077. $idList[$id] = true;
  1078. }
  1079. }
  1080. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1081. foreach ($rows as &$rw) {
  1082. if (!is_array($rw)) {
  1083. continue;
  1084. }
  1085. $mergeIds = [];
  1086. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1087. foreach ($rw['_order_merge_rows'] as $mr) {
  1088. $mid = (int)($mr['ID'] ?? 0);
  1089. if ($this->isValidScydgyRowId($mid)) {
  1090. $mergeIds[$mid] = true;
  1091. }
  1092. }
  1093. }
  1094. $rid = (int)($rw['ID'] ?? 0);
  1095. if ($this->isValidScydgyRowId($rid)) {
  1096. $mergeIds[$rid] = true;
  1097. }
  1098. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1099. $rw['po_detail_count'] = $s['cnt'];
  1100. $rw['po_amount_fill_cnt'] = $s['amt'];
  1101. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1102. }
  1103. unset($rw);
  1104. }
  1105. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1106. $idList = [];
  1107. foreach ($rows as $rw) {
  1108. if (!is_array($rw)) {
  1109. continue;
  1110. }
  1111. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1112. foreach ($rw['_order_merge_rows'] as $mr) {
  1113. $mid = (int)($mr['ID'] ?? 0);
  1114. if ($this->isValidScydgyRowId($mid)) {
  1115. $idList[$mid] = true;
  1116. }
  1117. }
  1118. }
  1119. $id = (int)($rw['ID'] ?? 0);
  1120. if ($this->isValidScydgyRowId($id)) {
  1121. $idList[$id] = true;
  1122. }
  1123. }
  1124. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1125. foreach ($rows as &$rw) {
  1126. if (!is_array($rw)) {
  1127. continue;
  1128. }
  1129. $mergeIds = [];
  1130. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1131. foreach ($rw['_order_merge_rows'] as $mr) {
  1132. $mid = (int)($mr['ID'] ?? 0);
  1133. if ($this->isValidScydgyRowId($mid)) {
  1134. $mergeIds[$mid] = true;
  1135. }
  1136. }
  1137. }
  1138. $rid = (int)($rw['ID'] ?? 0);
  1139. if ($this->isValidScydgyRowId($rid)) {
  1140. $mergeIds[$rid] = true;
  1141. }
  1142. $buckets = [];
  1143. foreach (array_keys($mergeIds) as $mid) {
  1144. if (isset($quoteBucket[$mid])) {
  1145. $buckets[] = $quoteBucket[$mid];
  1146. }
  1147. }
  1148. $supplierText = $buckets !== []
  1149. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1150. : '';
  1151. if ($wffTab === 'confirm') {
  1152. $rw['picked_supplier_name'] = $supplierText;
  1153. } else {
  1154. $rw['notify_supplier_text'] = $supplierText;
  1155. }
  1156. }
  1157. unset($rw);
  1158. }
  1159. if ($wffTab === 'all' && count($rows) > 0) {
  1160. $this->mergePurchaseOrder($rows);
  1161. }
  1162. if ($wffTab === 'pick' && count($rows) > 0) {
  1163. $this->mergePurchaseOrder($rows);
  1164. }
  1165. foreach ($rows as &$rwClean) {
  1166. if (is_array($rwClean)) {
  1167. unset($rwClean['_order_merge_rows']);
  1168. if (array_key_exists('NGZL', $rwClean)) {
  1169. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1170. }
  1171. }
  1172. }
  1173. unset($rwClean);
  1174. return json([
  1175. 'total' => count($filtered),
  1176. 'rows' => $rows,
  1177. 'activeYm' => $ym,
  1178. ]);
  1179. } catch (\Throwable $e) {
  1180. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1181. return json([
  1182. 'total' => 0,
  1183. 'rows' => [],
  1184. ]);
  1185. }
  1186. }
  1187. /**
  1188. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1189. *
  1190. * @return array<int, true>
  1191. */
  1192. protected function loadPickHiddenScydgySet(): array
  1193. {
  1194. if ($this->pickHiddenScydgySetCache !== null) {
  1195. return $this->pickHiddenScydgySetCache;
  1196. }
  1197. $hideSet = [];
  1198. try {
  1199. $poIds = Db::table('purchase_order')
  1200. ->where(function ($q) {
  1201. $q->whereIn('wflow_status', array_merge(
  1202. ProcuremenStatus::wflowPendingConfirmValues(),
  1203. ProcuremenStatus::wflowPendingApprovalValues()
  1204. ))
  1205. ->whereOr(function ($q1) {
  1206. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1207. })
  1208. ->whereOr(function ($q2) {
  1209. $q2->whereNotNull('pick_time')
  1210. ->where('pick_time', '<>', '')
  1211. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1212. })
  1213. ->whereOr(function ($q3) {
  1214. $q3->whereNotNull('mod_rq')
  1215. ->where('mod_rq', '<>', '')
  1216. ->where('mod_rq', 'not like', '0000-00-00%');
  1217. });
  1218. })
  1219. ->column('scydgy_id');
  1220. if (is_array($poIds)) {
  1221. foreach ($poIds as $pid) {
  1222. $k = (int)$pid;
  1223. if ($k !== 0) {
  1224. $hideSet[$k] = true;
  1225. }
  1226. }
  1227. }
  1228. } catch (\Throwable $e) {
  1229. }
  1230. try {
  1231. $detIdsQuery = Db::table('purchase_order_detail');
  1232. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1233. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1234. if (is_array($detIds)) {
  1235. foreach ($detIds as $pid) {
  1236. $k = (int)$pid;
  1237. if ($this->isValidScydgyRowId($k)) {
  1238. $hideSet[$k] = true;
  1239. }
  1240. }
  1241. }
  1242. } catch (\Throwable $e) {
  1243. }
  1244. $this->pickHiddenScydgySetCache = $hideSet;
  1245. return $hideSet;
  1246. }
  1247. /**
  1248. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1249. *
  1250. * @return array<int, array<string, mixed>>
  1251. */
  1252. protected function loadPickManualOrderRows(): array
  1253. {
  1254. try {
  1255. $dbRows = Db::table('purchase_order')
  1256. ->where('scydgy_id', '<', 0)
  1257. ->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%\')')
  1258. ->order('scydgy_id', 'asc')
  1259. ->select();
  1260. } catch (\Throwable $e) {
  1261. try {
  1262. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1263. } catch (\Throwable $e2) {
  1264. return [];
  1265. }
  1266. }
  1267. if (!is_array($dbRows) || $dbRows === []) {
  1268. return [];
  1269. }
  1270. $detailSidSet = [];
  1271. try {
  1272. $negIds = [];
  1273. foreach ($dbRows as $dbRow) {
  1274. if (!is_array($dbRow)) {
  1275. continue;
  1276. }
  1277. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1278. if ($sid < 0) {
  1279. $negIds[$sid] = true;
  1280. }
  1281. }
  1282. if ($negIds !== []) {
  1283. $detQuery = Db::table('purchase_order_detail')
  1284. ->where('scydgy_id', 'in', array_keys($negIds));
  1285. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1286. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1287. if (is_array($detRows)) {
  1288. foreach ($detRows as $did) {
  1289. $detailSidSet[(int)$did] = true;
  1290. }
  1291. }
  1292. }
  1293. } catch (\Throwable $e) {
  1294. }
  1295. $pool = [];
  1296. foreach ($dbRows as $dbRow) {
  1297. if (!is_array($dbRow)) {
  1298. continue;
  1299. }
  1300. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1301. if ($sid >= 0) {
  1302. continue;
  1303. }
  1304. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1305. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1306. continue;
  1307. }
  1308. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1309. if ($st === ProcuremenStatus::PO_COMPLETED || $st === ProcuremenStatus::PO_IN_PROGRESS) {
  1310. continue;
  1311. }
  1312. if (isset($detailSidSet[$sid])) {
  1313. continue;
  1314. }
  1315. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1316. $r['_is_manual'] = 1;
  1317. $pool[] = $r;
  1318. }
  1319. return $pool;
  1320. }
  1321. /**
  1322. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1323. */
  1324. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1325. {
  1326. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1327. foreach ($keys as $k) {
  1328. $t = trim((string)($row[$k] ?? ''));
  1329. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1330. return $t;
  1331. }
  1332. }
  1333. return '';
  1334. }
  1335. /**
  1336. * 分配手工新增工序行 ID(负数递减)
  1337. */
  1338. protected function allocateManualScydgyId(): int
  1339. {
  1340. try {
  1341. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1342. $min = (int)$min;
  1343. return $min < 0 ? $min - 1 : -1;
  1344. } catch (\Throwable $e) {
  1345. return -1;
  1346. }
  1347. }
  1348. /**
  1349. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1350. */
  1351. protected function allocateManualOrderCcydh(): string
  1352. {
  1353. $prefix = 'YW' . date('Ymd');
  1354. $maxSeq = 0;
  1355. try {
  1356. $rows = Db::table('purchase_order')
  1357. ->where('CCYDH', 'like', $prefix . '%')
  1358. ->column('CCYDH');
  1359. if (is_array($rows)) {
  1360. foreach ($rows as $ccydh) {
  1361. $ccydh = trim((string)$ccydh);
  1362. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1363. $maxSeq = max($maxSeq, (int)$m[1]);
  1364. }
  1365. }
  1366. }
  1367. } catch (\Throwable $e) {
  1368. }
  1369. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1370. }
  1371. /**
  1372. * purchase_order.mod_rq 是否有有效软删除时间
  1373. */
  1374. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1375. {
  1376. $t = trim((string)$modRq);
  1377. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1378. }
  1379. /**
  1380. * 列表行 → purchase_order 写入字段
  1381. *
  1382. * @return array<string, mixed>
  1383. */
  1384. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1385. {
  1386. return [
  1387. 'scydgy_id' => $scydgyId,
  1388. 'CCYDH' => $row['CCYDH'] ?? null,
  1389. 'CYJMC' => $row['CYJMC'] ?? null,
  1390. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1391. 'CDXMC' => $row['CDXMC'] ?? null,
  1392. 'CGYBH' => $row['CGYBH'] ?? null,
  1393. 'CGYMC' => $row['CGYMC'] ?? null,
  1394. 'CDW' => $row['CDW'] ?? null,
  1395. 'NGZL' => $row['NGZL'] ?? null,
  1396. 'CDF' => $row['CDF'] ?? null,
  1397. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1398. 'MBZ' => $row['MBZ'] ?? null,
  1399. 'bwjg' => $row['bwjg'] ?? null,
  1400. 'iStatus' => $row['iStatus'] ?? null,
  1401. 'dStamp' => $row['dStamp'] ?? null,
  1402. 'dputrecord' => $row['dputrecord'] ?? null,
  1403. 'cywyxm' => $row['cywyxm'] ?? null,
  1404. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1405. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1406. ];
  1407. }
  1408. /**
  1409. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1410. *
  1411. * @return array{po:?array<string,mixed>, hidden:bool}
  1412. */
  1413. protected function resolvePickRowPoContext(int $sid): array
  1414. {
  1415. $po = null;
  1416. try {
  1417. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1418. if (is_array($found)) {
  1419. $po = $found;
  1420. }
  1421. } catch (\Throwable $e) {
  1422. }
  1423. $hideSet = $this->loadPickHiddenScydgySet();
  1424. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1425. }
  1426. /**
  1427. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1428. */
  1429. protected function assertPickRowCanDelete(int $sid, array $row): void
  1430. {
  1431. $ctx = $this->resolvePickRowPoContext($sid);
  1432. $po = $ctx['po'];
  1433. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1434. return;
  1435. }
  1436. if (is_array($po)) {
  1437. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1438. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1439. }
  1440. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1441. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1442. }
  1443. }
  1444. if ($ctx['hidden']) {
  1445. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1446. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1447. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1448. }
  1449. }
  1450. /**
  1451. * 初选直接完结前校验
  1452. */
  1453. protected function assertPickRowCanComplete(int $sid, array $row): void
  1454. {
  1455. $ctx = $this->resolvePickRowPoContext($sid);
  1456. $po = $ctx['po'];
  1457. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1458. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1459. }
  1460. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1461. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1462. }
  1463. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1464. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1465. }
  1466. }
  1467. /**
  1468. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1469. */
  1470. protected function softDeleteProcuremenPickRow(array $row): void
  1471. {
  1472. $sid = $this->extractScydgyRowId($row);
  1473. if (!$this->isValidScydgyRowId($sid)) {
  1474. throw new \InvalidArgumentException('无效的行主键');
  1475. }
  1476. $this->assertPickRowCanDelete($sid, $row);
  1477. $po = $this->resolvePickRowPoContext($sid)['po'];
  1478. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1479. return;
  1480. }
  1481. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1482. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1483. }
  1484. $now = date('Y-m-d H:i:s');
  1485. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1486. if (is_array($exists)) {
  1487. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1488. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1489. } else {
  1490. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1491. $data['mod_rq'] = $now;
  1492. $data['createtime'] = $now;
  1493. Db::table('purchase_order')->insert($data);
  1494. $poIdLog = (int)Db::getLastInsID();
  1495. }
  1496. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1497. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1498. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1499. if ($gymcLog !== '') {
  1500. $logTail .= ' / ' . $gymcLog;
  1501. }
  1502. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1503. }
  1504. /**
  1505. * 手工新增协助工序(写入 purchase_order)
  1506. *
  1507. * @param array<string, mixed> $params
  1508. * @return int scydgy_id
  1509. */
  1510. protected function saveManualPickOrder(array $params): int
  1511. {
  1512. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1513. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1514. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1515. if ($ccydh === '') {
  1516. $ccydh = $this->allocateManualOrderCcydh();
  1517. }
  1518. $now = date('Y-m-d H:i:s');
  1519. $sid = $this->allocateManualScydgyId();
  1520. $data = [
  1521. 'scydgy_id' => $sid,
  1522. 'CCYDH' => $ccydh,
  1523. 'CYJMC' => $cyjmc,
  1524. 'CGYMC' => $cgymc,
  1525. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1526. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1527. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1528. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1529. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1530. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1531. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1532. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1533. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1534. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1535. 'createtime' => $now,
  1536. 'dStamp' => $now,
  1537. 'dputrecord' => $now,
  1538. ];
  1539. Db::table('purchase_order')->insert($data);
  1540. $poId = (int)Db::getLastInsID();
  1541. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1542. return $sid;
  1543. }
  1544. protected function formatProcuremenRowLabel(array $row): string
  1545. {
  1546. $dh = trim((string)($row['CCYDH'] ?? ''));
  1547. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1548. if ($dh !== '' && $gymc !== '') {
  1549. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1550. }
  1551. if ($dh !== '') {
  1552. return '订单「' . $dh . '」';
  1553. }
  1554. if ($gymc !== '') {
  1555. return '工序「' . $gymc . '」';
  1556. }
  1557. $id = $this->extractScydgyRowId($row);
  1558. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1559. }
  1560. /**
  1561. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1562. */
  1563. protected function extractScydgyRowId(array $row): int
  1564. {
  1565. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1566. }
  1567. protected function isValidScydgyRowId(int $id): bool
  1568. {
  1569. return ProcuremenGuard::isValidScydgyId($id);
  1570. }
  1571. protected function isManualScydgyRowId(int $id): bool
  1572. {
  1573. return $id < 0;
  1574. }
  1575. /**
  1576. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1577. *
  1578. * @param int[] $scydgyIds
  1579. * @return array<int, string[]>
  1580. */
  1581. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1582. {
  1583. $out = [];
  1584. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1585. if ($scydgyIds === []) {
  1586. return $out;
  1587. }
  1588. try {
  1589. $rows = Db::table('purchase_order_detail')
  1590. ->where('scydgy_id', 'in', $scydgyIds)
  1591. ->field('scydgy_id,company_name')
  1592. ->order('company_name', 'asc')
  1593. ->select();
  1594. } catch (\Throwable $e) {
  1595. $rows = [];
  1596. }
  1597. if (!is_array($rows)) {
  1598. return $out;
  1599. }
  1600. foreach ($rows as $r) {
  1601. if (!is_array($r)) {
  1602. continue;
  1603. }
  1604. $sid = (int)($r['scydgy_id'] ?? 0);
  1605. $cn = trim((string)($r['company_name'] ?? ''));
  1606. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1607. continue;
  1608. }
  1609. if (!isset($out[$sid])) {
  1610. $out[$sid] = [];
  1611. }
  1612. if (!in_array($cn, $out[$sid], true)) {
  1613. $out[$sid][] = $cn;
  1614. }
  1615. }
  1616. return $out;
  1617. }
  1618. /**
  1619. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1620. *
  1621. * @param string[] $names
  1622. */
  1623. protected function formatNotifySupplierDisplay(array $names): string
  1624. {
  1625. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1626. return trim((string)$n);
  1627. }, $names))));
  1628. if ($names === []) {
  1629. return '';
  1630. }
  1631. sort($names, SORT_STRING);
  1632. return implode("\n", $names);
  1633. }
  1634. /**
  1635. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1636. *
  1637. * @param int[] $scydgyIds
  1638. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1639. */
  1640. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1641. {
  1642. $out = [];
  1643. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1644. if ($scydgyIds === []) {
  1645. return $out;
  1646. }
  1647. try {
  1648. $rows = Db::table('purchase_order_detail')
  1649. ->where('scydgy_id', 'in', $scydgyIds)
  1650. ->field('scydgy_id,company_name,amount')
  1651. ->select();
  1652. } catch (\Throwable $e) {
  1653. $rows = [];
  1654. }
  1655. if (!is_array($rows)) {
  1656. return $out;
  1657. }
  1658. foreach ($rows as $r) {
  1659. if (!is_array($r)) {
  1660. continue;
  1661. }
  1662. $sid = (int)($r['scydgy_id'] ?? 0);
  1663. $cn = trim((string)($r['company_name'] ?? ''));
  1664. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1665. continue;
  1666. }
  1667. if (!isset($out[$sid])) {
  1668. $out[$sid] = ['all' => [], 'quoted' => []];
  1669. }
  1670. $out[$sid]['all'][$cn] = true;
  1671. $am = trim((string)($r['amount'] ?? ''));
  1672. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1673. $out[$sid]['quoted'][$cn] = true;
  1674. }
  1675. }
  1676. return $out;
  1677. }
  1678. /**
  1679. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1680. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1681. */
  1682. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1683. {
  1684. $merged = ['all' => [], 'quoted' => []];
  1685. foreach ($buckets as $b) {
  1686. if (!is_array($b)) {
  1687. continue;
  1688. }
  1689. foreach ($b['all'] ?? [] as $cn => $_) {
  1690. $merged['all'][$cn] = true;
  1691. }
  1692. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1693. $merged['quoted'][$cn] = true;
  1694. }
  1695. }
  1696. return $merged;
  1697. }
  1698. /**
  1699. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1700. */
  1701. protected function formatQuotedSupplierLines(array $bucket): string
  1702. {
  1703. $all = array_keys($bucket['all'] ?? []);
  1704. if ($all === []) {
  1705. return '';
  1706. }
  1707. sort($all, SORT_STRING);
  1708. $lines = [];
  1709. foreach ($all as $cn) {
  1710. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1711. $lines[] = $cn . '(' . $status . ')';
  1712. }
  1713. return implode("\n", $lines);
  1714. }
  1715. /**
  1716. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1717. */
  1718. protected function resolveBundleSysRq(array $bundle): string
  1719. {
  1720. foreach ($bundle['pos'] ?? [] as $po) {
  1721. if (!is_array($po)) {
  1722. continue;
  1723. }
  1724. $sr = trim((string)($po['sys_rq'] ?? ''));
  1725. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1726. return $sr;
  1727. }
  1728. }
  1729. return '';
  1730. }
  1731. /**
  1732. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1733. */
  1734. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1735. {
  1736. $raw = trim((string)$sysRq);
  1737. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1738. return true;
  1739. }
  1740. $ts = strtotime(str_replace('T', ' ', $raw));
  1741. if ($ts === false || $ts <= 0) {
  1742. return true;
  1743. }
  1744. return time() >= $ts;
  1745. }
  1746. /**
  1747. * 截止时间前:隐藏单价/交期真实值,统一展示文案
  1748. *
  1749. * @param array<string, mixed> $line
  1750. */
  1751. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  1752. {
  1753. $amountFilled = !empty($line['amount_filled']);
  1754. $deliveryFilled = !empty($line['delivery_filled']);
  1755. $line['unit_price_text'] = $amountFilled ? '未到截止时间' : '未填写';
  1756. $line['amount_show'] = '';
  1757. if (array_key_exists('amount_text', $line)) {
  1758. $line['amount_text'] = $line['unit_price_text'];
  1759. }
  1760. $deliveryText = $deliveryFilled ? '未到截止时间' : '未填写';
  1761. $line['delivery_show'] = $deliveryText;
  1762. if (array_key_exists('delivery_text', $line)) {
  1763. $line['delivery_text'] = $deliveryText;
  1764. }
  1765. $line['delivery_ymd'] = '';
  1766. $line['subtotal_text'] = $amountFilled ? '未到截止时间' : '';
  1767. $line['subtotal_num'] = null;
  1768. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  1769. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  1770. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled) ? 1 : 0;
  1771. $line['amount_filled'] = false;
  1772. $line['delivery_filled'] = false;
  1773. $line['is_quoted'] = false;
  1774. if (array_key_exists('quote_label', $line)) {
  1775. $line['quote_label'] = ($amountFilled || $deliveryFilled) ? '未到截止时间' : '未报价';
  1776. }
  1777. }
  1778. /**
  1779. * 报价行展示字段默认值(模板安全访问)
  1780. *
  1781. * @param array<string, mixed> $line
  1782. * @return array<string, mixed>
  1783. */
  1784. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  1785. {
  1786. if (!array_key_exists('amount_quote_pending', $line)) {
  1787. $line['amount_quote_pending'] = 0;
  1788. }
  1789. if (!array_key_exists('delivery_quote_pending', $line)) {
  1790. $line['delivery_quote_pending'] = 0;
  1791. }
  1792. if (!array_key_exists('quote_before_deadline', $line)) {
  1793. $line['quote_before_deadline'] = 0;
  1794. }
  1795. if (!array_key_exists('amount_filled', $line)) {
  1796. $line['amount_filled'] = 0;
  1797. }
  1798. if (!array_key_exists('delivery_filled', $line)) {
  1799. $line['delivery_filled'] = 0;
  1800. }
  1801. return $line;
  1802. }
  1803. /**
  1804. * 审核弹窗:按供应商汇总报价明细
  1805. *
  1806. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1807. * @return array<int, array<string, mixed>>
  1808. */
  1809. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  1810. {
  1811. $sids = [];
  1812. foreach ($bundle['pos'] ?? [] as $po) {
  1813. if (!is_array($po)) {
  1814. continue;
  1815. }
  1816. $sid = (int)($po['scydgy_id'] ?? 0);
  1817. if ($this->isValidScydgyRowId($sid)) {
  1818. $sids[$sid] = true;
  1819. }
  1820. }
  1821. if ($sids === []) {
  1822. return [];
  1823. }
  1824. $deadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle));
  1825. $gymcMap = [];
  1826. $qtyBySid = [];
  1827. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1828. if (!is_array($mr)) {
  1829. continue;
  1830. }
  1831. $gid = $this->extractScydgyRowId($mr);
  1832. if ($this->isValidScydgyRowId($gid)) {
  1833. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1834. $qty = trim((string)($mr['This_quantity'] ?? ''));
  1835. if ($qty === '') {
  1836. $qty = trim((string)($mr['NGZL'] ?? ''));
  1837. }
  1838. $qtyBySid[$gid] = $qty;
  1839. }
  1840. }
  1841. foreach ($bundle['pos'] ?? [] as $po) {
  1842. if (!is_array($po)) {
  1843. continue;
  1844. }
  1845. $gid = (int)($po['scydgy_id'] ?? 0);
  1846. if ($this->isValidScydgyRowId($gid)) {
  1847. $nm = trim((string)($po['CGYMC'] ?? ''));
  1848. if ($nm !== '') {
  1849. $gymcMap[$gid] = $nm;
  1850. }
  1851. }
  1852. }
  1853. try {
  1854. $detailsQuery = Db::table('purchase_order_detail')
  1855. ->where('scydgy_id', 'in', array_keys($sids));
  1856. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1857. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  1858. } catch (\Throwable $e) {
  1859. try {
  1860. $detailsQuery = Db::table('purchase_order_detail')
  1861. ->where('scydgy_id', 'in', array_keys($sids));
  1862. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1863. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  1864. } catch (\Throwable $e2) {
  1865. $details = [];
  1866. }
  1867. }
  1868. if (!is_array($details)) {
  1869. $details = [];
  1870. }
  1871. $byCompany = [];
  1872. foreach ($details as $d) {
  1873. if (!is_array($d)) {
  1874. continue;
  1875. }
  1876. $cn = trim((string)($d['company_name'] ?? ''));
  1877. if ($cn === '') {
  1878. continue;
  1879. }
  1880. if (!isset($byCompany[$cn])) {
  1881. $ph = trim((string)($d['phone'] ?? ''));
  1882. $username = trim((string)($d['username'] ?? ''));
  1883. if ($username === '') {
  1884. $username = $this->resolveCustomerContactName($ph, $cn);
  1885. }
  1886. $byCompany[$cn] = [
  1887. 'name' => $cn,
  1888. 'email' => trim((string)($d['email'] ?? '')),
  1889. 'phone' => $ph,
  1890. 'username' => $username,
  1891. 'has_quote' => false,
  1892. 'lines' => [],
  1893. ];
  1894. }
  1895. $sid = (int)($d['scydgy_id'] ?? 0);
  1896. $am = trim((string)($d['amount'] ?? ''));
  1897. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  1898. if ($gymc === '') {
  1899. $gymc = '工序';
  1900. }
  1901. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  1902. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  1903. if ($deliveryShow === '' && $deliveryRaw !== '') {
  1904. $deliveryShow = $deliveryRaw;
  1905. }
  1906. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  1907. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  1908. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  1909. $subtotal = null;
  1910. if ($amountNum !== null) {
  1911. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  1912. }
  1913. $unitPriceText = $amountFilled
  1914. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  1915. : '未填写';
  1916. $lineRow = [
  1917. 'cgymc' => $gymc,
  1918. 'amount' => $am,
  1919. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  1920. 'amount_filled' => $amountFilled,
  1921. 'unit_price_text' => $unitPriceText,
  1922. 'delivery' => $deliveryRaw,
  1923. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  1924. 'delivery_filled' => $deliveryFilled,
  1925. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  1926. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  1927. 'subtotal_num' => $subtotal,
  1928. 'status_name' => trim((string)($d['status_name'] ?? '')),
  1929. 'is_quoted' => $amountFilled,
  1930. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  1931. ];
  1932. if (!$deadlineReached) {
  1933. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  1934. }
  1935. $byCompany[$cn]['lines'][] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  1936. }
  1937. foreach ($byCompany as $cn => $g) {
  1938. $total = count($g['lines']);
  1939. $quoted = 0;
  1940. $groupTotal = 0.0;
  1941. $groupHasTotal = false;
  1942. if ($deadlineReached) {
  1943. foreach ($g['lines'] as $ln) {
  1944. $am = trim((string)($ln['amount'] ?? ''));
  1945. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1946. $quoted++;
  1947. }
  1948. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  1949. $groupTotal += (float)$ln['subtotal_num'];
  1950. $groupHasTotal = true;
  1951. }
  1952. }
  1953. }
  1954. $byCompany[$cn]['has_quote'] = $deadlineReached && $total > 0 && $quoted === $total;
  1955. $byCompany[$cn]['line_count'] = $total;
  1956. $byCompany[$cn]['has_total'] = $total > 0;
  1957. $byCompany[$cn]['total_text'] = ($deadlineReached && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  1958. $byCompany[$cn]['display_rowspan'] = $total + ($total > 0 ? 1 : 0);
  1959. }
  1960. return array_values($byCompany);
  1961. }
  1962. /**
  1963. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  1964. *
  1965. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1966. * @return array<int, array<string, mixed>>
  1967. */
  1968. protected function loadConfirmSupplierPickGroups(array $bundle): array
  1969. {
  1970. $sids = [];
  1971. $poIdMap = [];
  1972. foreach ($bundle['pos'] ?? [] as $po) {
  1973. if (!is_array($po)) {
  1974. continue;
  1975. }
  1976. $sid = (int)($po['scydgy_id'] ?? 0);
  1977. if ($this->isValidScydgyRowId($sid)) {
  1978. $sids[$sid] = true;
  1979. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  1980. }
  1981. }
  1982. if ($sids === []) {
  1983. return [];
  1984. }
  1985. $deadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle));
  1986. $gymcMap = [];
  1987. $qtyBySid = [];
  1988. $orderedSids = [];
  1989. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1990. if (!is_array($mr)) {
  1991. continue;
  1992. }
  1993. $gid = $this->extractScydgyRowId($mr);
  1994. if ($this->isValidScydgyRowId($gid)) {
  1995. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1996. $orderedSids[] = $gid;
  1997. $qty = trim((string)($mr['This_quantity'] ?? ''));
  1998. if ($qty === '') {
  1999. $qty = trim((string)($mr['NGZL'] ?? ''));
  2000. }
  2001. $qtyBySid[$gid] = $qty;
  2002. }
  2003. }
  2004. foreach ($bundle['pos'] ?? [] as $po) {
  2005. if (!is_array($po)) {
  2006. continue;
  2007. }
  2008. $gid = (int)($po['scydgy_id'] ?? 0);
  2009. if ($this->isValidScydgyRowId($gid)) {
  2010. $nm = trim((string)($po['CGYMC'] ?? ''));
  2011. if ($nm !== '') {
  2012. $gymcMap[$gid] = $nm;
  2013. }
  2014. }
  2015. }
  2016. try {
  2017. $details = Db::table('purchase_order_detail')
  2018. ->where('scydgy_id', 'in', array_keys($sids))
  2019. ->order('company_name', 'asc')
  2020. ->order('id', 'asc')
  2021. ->select();
  2022. } catch (\Throwable $e) {
  2023. try {
  2024. $details = Db::table('purchase_order_detail')
  2025. ->where('scydgy_id', 'in', array_keys($sids))
  2026. ->order('company_name', 'asc')
  2027. ->order('ID', 'asc')
  2028. ->select();
  2029. } catch (\Throwable $e2) {
  2030. $details = [];
  2031. }
  2032. }
  2033. if (!is_array($details)) {
  2034. $details = [];
  2035. }
  2036. $byCompany = [];
  2037. foreach ($details as $d) {
  2038. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2039. continue;
  2040. }
  2041. $cn = trim((string)($d['company_name'] ?? ''));
  2042. if ($cn === '') {
  2043. continue;
  2044. }
  2045. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2046. $sid = (int)($d['scydgy_id'] ?? 0);
  2047. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2048. continue;
  2049. }
  2050. if (!isset($byCompany[$cn])) {
  2051. $ph = trim((string)($d['phone'] ?? ''));
  2052. $username = trim((string)($d['username'] ?? ''));
  2053. if ($username === '') {
  2054. $username = $this->resolveCustomerContactName($ph, $cn);
  2055. }
  2056. $byCompany[$cn] = [
  2057. 'name' => $cn,
  2058. 'email' => trim((string)($d['email'] ?? '')),
  2059. 'phone' => $ph,
  2060. 'username' => $username,
  2061. 'pick_lines' => [],
  2062. 'detail_picks' => [],
  2063. ];
  2064. }
  2065. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2066. if ($gymc === '') {
  2067. $gymc = '工序';
  2068. }
  2069. $am = trim((string)($d['amount'] ?? ''));
  2070. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2071. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2072. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2073. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2074. $deliveryShow = $deliveryRaw;
  2075. }
  2076. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2077. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2078. $subtotal = null;
  2079. if ($amountNum !== null) {
  2080. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2081. }
  2082. $unitPriceText = $amountFilled
  2083. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2084. : '未填写';
  2085. $pickLine = [
  2086. 'cgymc' => $gymc,
  2087. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2088. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2089. 'amount_filled' => $amountFilled,
  2090. 'delivery_filled' => $deliveryFilled,
  2091. 'unit_price_text' => $unitPriceText,
  2092. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2093. 'subtotal_num' => $subtotal,
  2094. 'is_quoted' => $amountFilled,
  2095. ];
  2096. if (!$deadlineReached) {
  2097. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2098. }
  2099. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2100. $byCompany[$cn]['detail_picks'][$sid] = [
  2101. 'scydgy_id' => $sid,
  2102. 'detail_id' => $detailId,
  2103. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2104. 'cgymc' => $gymc,
  2105. ];
  2106. }
  2107. $out = [];
  2108. foreach ($byCompany as $g) {
  2109. $pickLinesMap = $g['pick_lines'] ?? [];
  2110. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2111. continue;
  2112. }
  2113. $pickLines = [];
  2114. $usedLineSids = [];
  2115. foreach ($orderedSids as $sid) {
  2116. if (!isset($pickLinesMap[$sid])) {
  2117. continue;
  2118. }
  2119. $pickLines[] = $pickLinesMap[$sid];
  2120. $usedLineSids[$sid] = true;
  2121. }
  2122. foreach ($pickLinesMap as $sid => $ln) {
  2123. if (isset($usedLineSids[$sid])) {
  2124. continue;
  2125. }
  2126. $pickLines[] = $ln;
  2127. }
  2128. $groupTotal = 0.0;
  2129. $groupHasTotal = false;
  2130. if ($deadlineReached) {
  2131. foreach ($pickLines as $ln) {
  2132. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2133. $groupTotal += (float)$ln['subtotal_num'];
  2134. $groupHasTotal = true;
  2135. }
  2136. }
  2137. }
  2138. $lineCount = count($pickLines);
  2139. $g['pick_lines'] = $pickLines;
  2140. $g['line_count'] = $lineCount;
  2141. $g['has_total'] = $lineCount > 0;
  2142. $g['total_text'] = ($deadlineReached && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2143. $g['display_rowspan'] = $lineCount + ($lineCount > 0 ? 1 : 0);
  2144. $detailPicks = $g['detail_picks'] ?? [];
  2145. $g['detail_picks'] = array_values(is_array($detailPicks) ? $detailPicks : []);
  2146. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2147. unset($g['detail_picks']);
  2148. $out[] = $g;
  2149. }
  2150. return $out;
  2151. }
  2152. /**
  2153. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2154. * @return array<int, int[]> scydgy_id => detail_id[]
  2155. */
  2156. protected function mapDetailIdsByScydgyId(array $details): array
  2157. {
  2158. $out = [];
  2159. foreach ($details as $d) {
  2160. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2161. continue;
  2162. }
  2163. $sid = (int)($d['scydgy_id'] ?? 0);
  2164. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2165. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2166. continue;
  2167. }
  2168. if (!isset($out[$sid])) {
  2169. $out[$sid] = [];
  2170. }
  2171. $out[$sid][] = $pk;
  2172. }
  2173. foreach ($out as $sid => $ids) {
  2174. $out[$sid] = array_values(array_unique($ids));
  2175. }
  2176. return $out;
  2177. }
  2178. /**
  2179. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2180. *
  2181. * @param array<string, mixed> $dbRow
  2182. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2183. */
  2184. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2185. {
  2186. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2187. $r = [
  2188. 'ID' => $sid,
  2189. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2190. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2191. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2192. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2193. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2194. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2195. 'CDW' => $dbRow['CDW'] ?? '',
  2196. 'NGZL' => $dbRow['NGZL'] ?? '',
  2197. 'CDF' => $dbRow['CDF'] ?? '',
  2198. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2199. 'MBZ' => $dbRow['MBZ'] ?? '',
  2200. 'bwjg' => $dbRow['bwjg'] ?? '',
  2201. 'iStatus' => $dbRow['iStatus'] ?? '',
  2202. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2203. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2204. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2205. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2206. 'dStamp' => $dbRow['dStamp'] ?? '',
  2207. 'pick_time' => $dbRow['pick_time'] ?? '',
  2208. ];
  2209. if ($sid > 0 && isset($dStampMap[$sid])) {
  2210. $t = trim((string)$dStampMap[$sid]);
  2211. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2212. $r['dStamp'] = $dStampMap[$sid];
  2213. }
  2214. }
  2215. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2216. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2217. $ct = $dbRow['createtime'];
  2218. if (is_numeric($ct) && (int)$ct > 946684800) {
  2219. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2220. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2221. $r['dStamp'] = trim($ct);
  2222. }
  2223. }
  2224. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2225. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2226. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2227. $fallback = trim((string)($r['dStamp'] ?? ''));
  2228. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2229. $r['dputrecord'] = $fallback;
  2230. }
  2231. }
  2232. if (array_key_exists('id', $dbRow)) {
  2233. $r['purchase_order_id'] = (int)$dbRow['id'];
  2234. }
  2235. if ($sid < 0) {
  2236. $r['_is_manual'] = 1;
  2237. }
  2238. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2239. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2240. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2241. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2242. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2243. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2244. $r['pick_time'] = $pickFallback;
  2245. break;
  2246. }
  2247. }
  2248. }
  2249. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2250. if ($pickNm !== '') {
  2251. $r['pick_company_name'] = $pickNm;
  2252. $r['picked_supplier_name'] = $pickNm;
  2253. }
  2254. return $r;
  2255. }
  2256. /**
  2257. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2258. *
  2259. * @return array<int, array<string, mixed>>
  2260. */
  2261. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2262. {
  2263. $pool = [];
  2264. if (!is_array($dbRows) || $dbRows === []) {
  2265. return $pool;
  2266. }
  2267. $dStampMap = [];
  2268. $sidList = [];
  2269. foreach ($dbRows as $tmpRow) {
  2270. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2271. $sid = (int)$tmpRow['scydgy_id'];
  2272. if ($sid > 0) {
  2273. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2274. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2275. $sidList[$sid] = true;
  2276. }
  2277. }
  2278. }
  2279. }
  2280. if ($sidList !== []) {
  2281. try {
  2282. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2283. } catch (\Throwable $e) {
  2284. $dStampMap = [];
  2285. }
  2286. }
  2287. foreach ($dbRows as $dbRow) {
  2288. if (!is_array($dbRow)) {
  2289. continue;
  2290. }
  2291. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2292. }
  2293. return $pool;
  2294. }
  2295. /**
  2296. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2297. *
  2298. * @param int[] $scydgyIds
  2299. * @return array<int, array<string, mixed>>
  2300. */
  2301. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2302. {
  2303. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2304. if ($scydgyIds === []) {
  2305. return [];
  2306. }
  2307. try {
  2308. $list = Db::table('purchase_order_detail')
  2309. ->where('scydgy_id', 'in', $scydgyIds)
  2310. ->field('scydgy_id,company_name,amount,delivery')
  2311. ->select();
  2312. } catch (\Throwable $e) {
  2313. $list = [];
  2314. }
  2315. return is_array($list) ? $list : [];
  2316. }
  2317. /**
  2318. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2319. *
  2320. * @param int[] $scydgyIds
  2321. * @param array<int, array<string, mixed>> $allRows
  2322. * @return array{cnt:int, amt:int, deliv:int}
  2323. */
  2324. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2325. {
  2326. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2327. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2328. if ($scydgyIds === [] || $allRows === []) {
  2329. return $out;
  2330. }
  2331. $idSet = array_flip($scydgyIds);
  2332. $all = [];
  2333. $withAmt = [];
  2334. $withDeliv = [];
  2335. foreach ($allRows as $r) {
  2336. if (!is_array($r)) {
  2337. continue;
  2338. }
  2339. $sid = (int)($r['scydgy_id'] ?? 0);
  2340. if (!isset($idSet[$sid])) {
  2341. continue;
  2342. }
  2343. $cn = trim((string)($r['company_name'] ?? ''));
  2344. if ($cn === '') {
  2345. continue;
  2346. }
  2347. $all[$cn] = true;
  2348. $am = $r['amount'] ?? null;
  2349. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2350. $withAmt[$cn] = true;
  2351. }
  2352. $dv = $r['delivery'] ?? null;
  2353. if ($dv !== null && trim((string)$dv) !== '') {
  2354. $withDeliv[$cn] = true;
  2355. }
  2356. }
  2357. return [
  2358. 'cnt' => count($all),
  2359. 'amt' => count($withAmt),
  2360. 'deliv' => count($withDeliv),
  2361. ];
  2362. }
  2363. /**
  2364. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2365. *
  2366. * @param int[] $scydgyIds
  2367. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2368. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2369. */
  2370. protected function OrderDetailSummary(array $scydgyIds)
  2371. {
  2372. $out = [];
  2373. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2374. if ($scydgyIds === []) {
  2375. return $out;
  2376. }
  2377. $list = [];
  2378. try {
  2379. $list = Db::table('purchase_order_detail')
  2380. ->where('scydgy_id', 'in', $scydgyIds)
  2381. ->field('id,scydgy_id,amount,delivery')
  2382. ->select();
  2383. } catch (\Throwable $e) {
  2384. $list = [];
  2385. }
  2386. if (!is_array($list)) {
  2387. return $out;
  2388. }
  2389. foreach ($list as $r) {
  2390. if (!is_array($r)) {
  2391. continue;
  2392. }
  2393. $ids = (int)($r['scydgy_id'] ?? 0);
  2394. if (!$this->isValidScydgyRowId($ids)) {
  2395. continue;
  2396. }
  2397. if (!isset($out[$ids])) {
  2398. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2399. }
  2400. $out[$ids]['cnt']++;
  2401. $am = $r['amount'] ?? null;
  2402. if ($am !== null && $am !== '') {
  2403. if (!(is_string($am) && trim($am) === '')) {
  2404. $out[$ids]['amt']++;
  2405. }
  2406. }
  2407. $dv = $r['delivery'] ?? null;
  2408. if ($dv !== null && trim((string)$dv) !== '') {
  2409. $out[$ids]['deliv']++;
  2410. }
  2411. }
  2412. return $out;
  2413. }
  2414. /**
  2415. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  2416. *
  2417. * @return array
  2418. */
  2419. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  2420. {
  2421. $strContains = function ($haystack, $needle) {
  2422. if ($needle === '') {
  2423. return false;
  2424. }
  2425. $haystack = (string)$haystack;
  2426. if (function_exists('mb_stripos')) {
  2427. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  2428. }
  2429. return stripos($haystack, $needle) !== false;
  2430. };
  2431. $stripAlias = function ($f) {
  2432. return preg_replace('/^[ab]\./i', '', (string)$f);
  2433. };
  2434. $searchColNames = [];
  2435. foreach (explode(',', $this->searchFields) as $colRaw) {
  2436. $c = $stripAlias(trim($colRaw));
  2437. if ($c !== '') {
  2438. $searchColNames[] = $c;
  2439. }
  2440. }
  2441. $filtered = [];
  2442. foreach ($pool as $r) {
  2443. if (!is_array($r)) {
  2444. continue;
  2445. }
  2446. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  2447. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  2448. if (!$isManual) {
  2449. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  2450. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  2451. continue;
  2452. }
  2453. if ($applyMonthRange) {
  2454. $mo = (int)$m[2];
  2455. if ($mo < 1 || $mo > 12) {
  2456. continue;
  2457. }
  2458. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2459. $rowMonthStart = $ymRow . '-01 00:00:00';
  2460. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2461. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2462. continue;
  2463. }
  2464. }
  2465. } elseif ($applyMonthRange) {
  2466. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  2467. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2468. $ds = $listTime;
  2469. }
  2470. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  2471. continue;
  2472. }
  2473. $mo = (int)$m[2];
  2474. if ($mo < 1 || $mo > 12) {
  2475. continue;
  2476. }
  2477. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2478. $rowMonthStart = $ymRow . '-01 00:00:00';
  2479. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2480. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2481. continue;
  2482. }
  2483. }
  2484. if ($search !== '') {
  2485. $hitSearch = false;
  2486. foreach ($searchColNames as $c) {
  2487. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  2488. if ($cell !== '' && $strContains($cell, $search)) {
  2489. $hitSearch = true;
  2490. break;
  2491. }
  2492. }
  2493. if (!$hitSearch) {
  2494. continue;
  2495. }
  2496. }
  2497. foreach ($filterArr as $fk => $fv) {
  2498. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  2499. continue;
  2500. }
  2501. if (is_array($fv)) {
  2502. continue;
  2503. }
  2504. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  2505. continue;
  2506. }
  2507. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  2508. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  2509. $field = $stripAlias($fk);
  2510. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  2511. $cellStr = trim((string)$cell);
  2512. switch ($sym) {
  2513. case '=':
  2514. if ((string)$cell !== (string)$fv) {
  2515. continue 3;
  2516. }
  2517. break;
  2518. case '<>':
  2519. if ((string)$cell === (string)$fv) {
  2520. continue 3;
  2521. }
  2522. break;
  2523. case 'LIKE':
  2524. case 'NOT LIKE':
  2525. $needle = trim((string)$fv);
  2526. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  2527. if ($sym === 'LIKE' && !$hit) {
  2528. continue 3;
  2529. }
  2530. if ($sym === 'NOT LIKE' && $hit) {
  2531. continue 3;
  2532. }
  2533. break;
  2534. case '>':
  2535. case '>=':
  2536. case '<':
  2537. case '<=':
  2538. if (!is_numeric($cell) && $cellStr === '') {
  2539. continue 3;
  2540. }
  2541. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  2542. $vv = (float)$fv;
  2543. if ($sym === '>' && !($cv > $vv)) {
  2544. continue 3;
  2545. }
  2546. if ($sym === '>=' && !($cv >= $vv)) {
  2547. continue 3;
  2548. }
  2549. if ($sym === '<' && !($cv < $vv)) {
  2550. continue 3;
  2551. }
  2552. if ($sym === '<=' && !($cv <= $vv)) {
  2553. continue 3;
  2554. }
  2555. break;
  2556. case 'RANGE':
  2557. case 'NOT RANGE':
  2558. case 'BETWEEN':
  2559. case 'NOT BETWEEN':
  2560. case 'BETWEEN TIME':
  2561. case 'NOT BETWEEN TIME':
  2562. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  2563. $rawR = str_replace(' - ', ',', $rawR);
  2564. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  2565. if (count($arr) < 2) {
  2566. break;
  2567. }
  2568. $lo = $arr[0];
  2569. $hi = $arr[1];
  2570. if ($lo === '' && $hi === '') {
  2571. break;
  2572. }
  2573. $isNot = (strpos($sym, 'NOT') !== false);
  2574. if ($lo === '') {
  2575. $in = ($cellStr !== '' && $cellStr <= $hi);
  2576. if ($isNot ? $in : !$in) {
  2577. continue 3;
  2578. }
  2579. break;
  2580. }
  2581. if ($hi === '') {
  2582. $in = ($cellStr !== '' && $cellStr >= $lo);
  2583. if ($isNot ? $in : !$in) {
  2584. continue 3;
  2585. }
  2586. break;
  2587. }
  2588. $in = ($cellStr >= $lo && $cellStr <= $hi);
  2589. if ($isNot ? $in : !$in) {
  2590. continue 3;
  2591. }
  2592. break;
  2593. case 'NULL':
  2594. case 'IS NULL':
  2595. if ($cell !== null && $cell !== '') {
  2596. continue 3;
  2597. }
  2598. break;
  2599. case 'NOT NULL':
  2600. case 'IS NOT NULL':
  2601. if ($cell === null || $cell === '') {
  2602. continue 3;
  2603. }
  2604. break;
  2605. default:
  2606. break;
  2607. }
  2608. }
  2609. $filtered[] = $r;
  2610. }
  2611. return $filtered;
  2612. }
  2613. /**
  2614. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  2615. */
  2616. public function snapshotToProcure()
  2617. {
  2618. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2619. $this->error(__('Invalid parameters'));
  2620. }
  2621. $row = json_decode($this->request->post('row_json', ''), true);
  2622. if (!is_array($row)) {
  2623. $this->error(__('Invalid parameters'));
  2624. }
  2625. try {
  2626. $ids = $this->extractScydgyRowId($row);
  2627. if (!$this->isValidScydgyRowId($ids)) {
  2628. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2629. }
  2630. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2631. $data = [
  2632. 'scydgy_id' => $ids,
  2633. 'CCYDH' => $row['CCYDH'] ?? null,
  2634. 'CYJMC' => $row['CYJMC'] ?? null,
  2635. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2636. 'CDXMC' => $row['CDXMC'] ?? null,
  2637. 'CGYBH' => $row['CGYBH'] ?? null,
  2638. 'CGYMC' => $row['CGYMC'] ?? null,
  2639. 'CDW' => $row['CDW'] ?? null,
  2640. 'NGZL' => $row['NGZL'] ?? null,
  2641. 'CDF' => $row['CDF'] ?? null,
  2642. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2643. 'MBZ' => $row['MBZ'] ?? null,
  2644. 'bwjg' => $row['bwjg'] ?? null,
  2645. 'iStatus' => $row['iStatus'] ?? null,
  2646. 'dStamp' => $row['dStamp'] ?? null,
  2647. 'dputrecord' => $row['dputrecord'] ?? null,
  2648. 'cywyxm' => $row['cywyxm'] ?? null,
  2649. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2650. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2651. ];
  2652. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  2653. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  2654. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  2655. $this->success('操作成功');
  2656. return;
  2657. }
  2658. if ($exists) {
  2659. $upd = $data;
  2660. unset($upd['scydgy_id'], $upd['status']);
  2661. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2662. } else {
  2663. // 新增:不写 status(空/走库默认);仅写创建时间
  2664. $data['createtime'] = date('Y-m-d H:i:s');
  2665. Db::table('purchase_order')->insert($data);
  2666. }
  2667. } catch (\Throwable $e) {
  2668. $this->error($e->getMessage());
  2669. }
  2670. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  2671. $this->success('操作成功');
  2672. }
  2673. /**
  2674. * 未发列表
  2675. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  2676. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  2677. */
  2678. public function completeDirectly()
  2679. {
  2680. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2681. $this->error(__('参数错误'));
  2682. }
  2683. if (!$this->procuremenCanComplete()) {
  2684. $this->error(__('You have no permission'));
  2685. }
  2686. $row = json_decode($this->request->post('row_json', ''), true);
  2687. if (!is_array($row)) {
  2688. $this->error(__('Invalid parameters'));
  2689. }
  2690. $finishRaw = $this->request->post('finish', '1');
  2691. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  2692. $poIdLog = null;
  2693. try {
  2694. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  2695. $ids = $this->extractScydgyRowId($row);
  2696. if (!$this->isValidScydgyRowId($ids)) {
  2697. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2698. }
  2699. if ($asComplete) {
  2700. $this->assertPickRowCanComplete($ids, $row);
  2701. }
  2702. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2703. $data = [
  2704. 'scydgy_id' => $ids,
  2705. 'CCYDH' => $row['CCYDH'] ?? null,
  2706. 'CYJMC' => $row['CYJMC'] ?? null,
  2707. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2708. 'CDXMC' => $row['CDXMC'] ?? null,
  2709. 'CGYBH' => $row['CGYBH'] ?? null,
  2710. 'CGYMC' => $row['CGYMC'] ?? null,
  2711. 'CDW' => $row['CDW'] ?? null,
  2712. 'NGZL' => $row['NGZL'] ?? null,
  2713. 'CDF' => $row['CDF'] ?? null,
  2714. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2715. 'MBZ' => $row['MBZ'] ?? null,
  2716. 'bwjg' => $row['bwjg'] ?? null,
  2717. 'iStatus' => $row['iStatus'] ?? null,
  2718. 'dStamp' => $row['dStamp'] ?? null,
  2719. 'dputrecord' => $row['dputrecord'] ?? null,
  2720. 'cywyxm' => $row['cywyxm'] ?? null,
  2721. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2722. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2723. ];
  2724. if ($asComplete) {
  2725. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  2726. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  2727. }
  2728. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  2729. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  2730. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  2731. $this->success('操作成功');
  2732. return;
  2733. }
  2734. if ($exists) {
  2735. $upd = $data;
  2736. unset($upd['scydgy_id']);
  2737. if (!$asComplete) {
  2738. unset($upd['status']);
  2739. }
  2740. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2741. } else {
  2742. // 新增:不写 status;完结时 $data 已含 status=1
  2743. $data['createtime'] = date('Y-m-d H:i:s');
  2744. Db::table('purchase_order')->insert($data);
  2745. }
  2746. } catch (\Throwable $e) {
  2747. $this->error($e->getMessage());
  2748. }
  2749. try {
  2750. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2751. if (is_array($rpo)) {
  2752. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  2753. $poIdLog = $tid > 0 ? $tid : null;
  2754. }
  2755. } catch (\Throwable $e) {
  2756. $poIdLog = null;
  2757. }
  2758. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  2759. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  2760. if ($asComplete) {
  2761. $this->addOrderLog(
  2762. $ids,
  2763. 'mark_complete',
  2764. '点击「完结」,已标记为已完结',
  2765. $poIdLog
  2766. );
  2767. try {
  2768. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  2769. if ($pdfPublicPath === '') {
  2770. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  2771. }
  2772. } catch (\Throwable $e) {
  2773. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  2774. }
  2775. } else {
  2776. $this->addOrderLog(
  2777. $ids,
  2778. 'save_qty_price',
  2779. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  2780. $poIdLog
  2781. );
  2782. }
  2783. $this->pickHiddenScydgySetCache = null;
  2784. $this->success("操作成功");
  2785. }
  2786. /**
  2787. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  2788. *
  2789. * @param array<int, array> $rows 引用传递当前页行
  2790. */
  2791. protected function mergePurchaseOrder(array &$rows)
  2792. {
  2793. if ($rows === []) {
  2794. return;
  2795. }
  2796. $ids = [];
  2797. foreach ($rows as $rw) {
  2798. if (!is_array($rw)) {
  2799. continue;
  2800. }
  2801. $id = (int)($rw['ID'] ?? 0);
  2802. if ($id > 0) {
  2803. $ids[$id] = true;
  2804. }
  2805. }
  2806. $idList = array_keys($ids);
  2807. if ($idList === []) {
  2808. return;
  2809. }
  2810. try {
  2811. $list = Db::table('purchase_order')
  2812. ->where('scydgy_id', 'in', $idList)
  2813. ->field('scydgy_id,This_quantity,ceilingPrice')
  2814. ->select();
  2815. } catch (\Throwable $e) {
  2816. return;
  2817. }
  2818. if (!is_array($list)) {
  2819. return;
  2820. }
  2821. $byId = [];
  2822. foreach ($list as $dbRow) {
  2823. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  2824. continue;
  2825. }
  2826. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  2827. }
  2828. foreach ($rows as &$rw) {
  2829. if (!is_array($rw)) {
  2830. continue;
  2831. }
  2832. $sid = (int)($rw['ID'] ?? 0);
  2833. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  2834. continue;
  2835. }
  2836. $db = $byId[$sid];
  2837. if (array_key_exists('This_quantity', $db) && $db['This_quantity'] !== null && $db['This_quantity'] !== '') {
  2838. $rw['This_quantity'] = $db['This_quantity'];
  2839. }
  2840. if (array_key_exists('ceilingPrice', $db) && $db['ceilingPrice'] !== null && $db['ceilingPrice'] !== '') {
  2841. $rw['ceilingPrice'] = $db['ceilingPrice'];
  2842. } elseif (array_key_exists('ceiling_price', $db) && $db['ceiling_price'] !== null && $db['ceiling_price'] !== '') {
  2843. $rw['ceilingPrice'] = $db['ceiling_price'];
  2844. }
  2845. }
  2846. unset($rw);
  2847. }
  2848. /**
  2849. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  2850. */
  2851. public function purchaseConfirmPick()
  2852. {
  2853. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2854. $this->error(__('Invalid parameters'));
  2855. }
  2856. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  2857. $this->error(__('You have no permission'));
  2858. }
  2859. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  2860. if ($batchRaw !== '') {
  2861. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  2862. return;
  2863. }
  2864. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  2865. $sid = (int)$scydgyId;
  2866. if (!$this->isValidScydgyRowId($sid)) {
  2867. $this->error('参数无效');
  2868. }
  2869. $parseIdList = function ($raw) {
  2870. if (is_array($raw)) {
  2871. $arr = $raw;
  2872. } else {
  2873. $decoded = json_decode((string)$raw, true);
  2874. $arr = is_array($decoded) ? $decoded : [];
  2875. }
  2876. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  2877. };
  2878. $selectedRaw = $this->request->post('selected_ids', null);
  2879. if ($selectedRaw === null || $selectedRaw === '') {
  2880. $legacy = (int)$this->request->post('selected_id', 0);
  2881. $selectedIds = $legacy > 0 ? [$legacy] : [];
  2882. } else {
  2883. $selectedIds = $parseIdList($selectedRaw);
  2884. }
  2885. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  2886. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  2887. try {
  2888. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  2889. } catch (\InvalidArgumentException $e) {
  2890. $this->error($e->getMessage());
  2891. } catch (\Throwable $e) {
  2892. $this->error($e->getMessage());
  2893. }
  2894. $this->pickHiddenScydgySetCache = null;
  2895. $this->success('操作成功', '', $result);
  2896. }
  2897. /**
  2898. * 整单采购确认(多道工序一次提交)
  2899. */
  2900. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  2901. {
  2902. $decoded = json_decode($batchRaw, true);
  2903. if (!is_array($decoded) || $decoded === []) {
  2904. $this->error('提交数据无效');
  2905. }
  2906. $picks = [];
  2907. foreach ($decoded as $item) {
  2908. if (!is_array($item)) {
  2909. continue;
  2910. }
  2911. $sid = (int)($item['scydgy_id'] ?? 0);
  2912. if (!$this->isValidScydgyRowId($sid)) {
  2913. continue;
  2914. }
  2915. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  2916. if (!is_array($sel)) {
  2917. $sel = [(int)$sel];
  2918. }
  2919. $unsel = $item['unselected_ids'] ?? [];
  2920. if (!is_array($unsel)) {
  2921. $unsel = json_decode((string)$unsel, true);
  2922. $unsel = is_array($unsel) ? $unsel : [];
  2923. }
  2924. $picks[] = [
  2925. 'scydgy_id' => $sid,
  2926. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  2927. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  2928. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  2929. ];
  2930. }
  2931. if ($picks === []) {
  2932. $this->error('提交数据无效');
  2933. }
  2934. Db::startTrans();
  2935. $results = [];
  2936. try {
  2937. foreach ($picks as $pick) {
  2938. $results[] = $this->runPurchaseConfirmPick(
  2939. (int)$pick['scydgy_id'],
  2940. $pick['selected_ids'],
  2941. $pick['unselected_ids'],
  2942. (int)$pick['purchase_order_id'],
  2943. false,
  2944. false
  2945. );
  2946. }
  2947. Db::commit();
  2948. } catch (\Throwable $e) {
  2949. Db::rollback();
  2950. $msg = $e->getMessage();
  2951. $this->error($msg !== '' ? $msg : '提交失败');
  2952. }
  2953. try {
  2954. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  2955. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  2956. } catch (\Throwable $e) {
  2957. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  2958. }
  2959. $this->pickHiddenScydgySetCache = null;
  2960. $this->success('操作成功', '', ['batch' => $results]);
  2961. }
  2962. /**
  2963. * @return array<string, mixed>
  2964. */
  2965. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  2966. {
  2967. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  2968. ProcuremenGuard::assertWflowPendingApproval($poRow);
  2969. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  2970. $scydgyId = (string)$sid;
  2971. if ($selectedIds === []) {
  2972. throw new \InvalidArgumentException('请至少勾选一条明细');
  2973. }
  2974. $inter = array_intersect($selectedIds, $unselectedIds);
  2975. if ($inter !== []) {
  2976. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  2977. }
  2978. $allIds = $this->purchaseOrderDetail($sid);
  2979. if ($allIds === []) {
  2980. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  2981. }
  2982. foreach ($selectedIds as $id) {
  2983. if (!in_array($id, $allIds, true)) {
  2984. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  2985. }
  2986. }
  2987. foreach ($unselectedIds as $id) {
  2988. if (!in_array($id, $allIds, true)) {
  2989. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  2990. }
  2991. }
  2992. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  2993. sort($union, SORT_NUMERIC);
  2994. $expect = $allIds;
  2995. sort($expect, SORT_NUMERIC);
  2996. if ($union !== $expect) {
  2997. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  2998. }
  2999. if ($manageTransaction) {
  3000. Db::startTrans();
  3001. }
  3002. try {
  3003. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3004. $aff = 0;
  3005. try {
  3006. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3007. } catch (\Throwable $e) {
  3008. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3009. }
  3010. if ($aff < 1) {
  3011. throw new \Exception('更新选中状态失败');
  3012. }
  3013. $poPayload = [
  3014. 'status' => ProcuremenStatus::PO_COMPLETED,
  3015. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3016. ];
  3017. if ($purchaseOrderId > 0) {
  3018. $poAff = (int)Db::table('purchase_order')
  3019. ->where('id', $purchaseOrderId)
  3020. ->where('scydgy_id', $sid)
  3021. ->update($poPayload);
  3022. if ($poAff < 1) {
  3023. throw new \Exception('主表订单不存在或与工序行不匹配');
  3024. }
  3025. } else {
  3026. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3027. if ($poAff < 1) {
  3028. throw new \Exception('未找到');
  3029. }
  3030. }
  3031. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3032. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3033. if ($manageTransaction) {
  3034. Db::commit();
  3035. }
  3036. } catch (\Throwable $e) {
  3037. if ($manageTransaction) {
  3038. Db::rollback();
  3039. }
  3040. throw $e;
  3041. }
  3042. $poIdFinal = $purchaseOrderId;
  3043. if ($poIdFinal <= 0) {
  3044. try {
  3045. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3046. if (is_array($rpo)) {
  3047. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3048. }
  3049. } catch (\Throwable $e) {
  3050. $poIdFinal = 0;
  3051. }
  3052. }
  3053. $pickNames = [];
  3054. foreach ($selectedIds as $pid) {
  3055. $dr = $this->purchaseOrderDetai($sid, $pid);
  3056. $nm = trim((string)($dr['company_name'] ?? ''));
  3057. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3058. }
  3059. $this->addOrderLog(
  3060. $sid,
  3061. 'purchase_confirm',
  3062. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3063. $poIdFinal > 0 ? $poIdFinal : null
  3064. );
  3065. if ($sendNotifications) {
  3066. try {
  3067. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3068. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3069. 'scydgy_id' => $sid,
  3070. 'selected_ids' => $selectedIds,
  3071. 'unselected_ids' => $unselectedIds,
  3072. 'purchase_order_id' => $purchaseOrderId,
  3073. ]]);
  3074. } catch (\Throwable $e) {
  3075. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3076. }
  3077. }
  3078. Log::write(sprintf(
  3079. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3080. $scydgyId,
  3081. $purchaseOrderId,
  3082. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3083. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3084. ), 'notice');
  3085. $pdfPublicPath = '';
  3086. try {
  3087. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3088. } catch (\Throwable $e) {
  3089. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3090. }
  3091. return [
  3092. 'scydgy_id' => $scydgyId,
  3093. 'purchase_order_id' => $purchaseOrderId,
  3094. 'selected_ids' => $selectedIds,
  3095. 'unselected_ids' => $unselectedIds,
  3096. 'purchase_confirm_pdf' => $pdfPublicPath,
  3097. ];
  3098. }
  3099. /**
  3100. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3101. *
  3102. * @param int[]|string[] $scydgyIds
  3103. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3104. */
  3105. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3106. {
  3107. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3108. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3109. if ($scydgyIds === []) {
  3110. return $empty;
  3111. }
  3112. $pos = [];
  3113. try {
  3114. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3115. } catch (\Throwable $e) {
  3116. $rows = [];
  3117. }
  3118. if (is_array($rows)) {
  3119. foreach ($rows as $po) {
  3120. if (is_array($po)) {
  3121. $pos[] = $po;
  3122. }
  3123. }
  3124. }
  3125. if ($pos === []) {
  3126. return $empty;
  3127. }
  3128. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3129. return [
  3130. 'ccydh' => $ccydh,
  3131. 'pos' => $pos,
  3132. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3133. ];
  3134. }
  3135. /**
  3136. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3137. *
  3138. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3139. * @param array<int, array<string, mixed>> $picks
  3140. */
  3141. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3142. {
  3143. if ($picks === []) {
  3144. return;
  3145. }
  3146. $fallbackDetailId = 0;
  3147. $winners = [];
  3148. $losers = [];
  3149. foreach ($picks as $pick) {
  3150. if (!is_array($pick)) {
  3151. continue;
  3152. }
  3153. $sid = (int)($pick['scydgy_id'] ?? 0);
  3154. if (!$this->isValidScydgyRowId($sid)) {
  3155. continue;
  3156. }
  3157. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3158. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3159. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3160. $fallbackDetailId = (int)$selectedIds[0];
  3161. }
  3162. foreach ($selectedIds as $pid) {
  3163. $dr = $this->purchaseOrderDetai($sid, $pid);
  3164. if (!is_array($dr)) {
  3165. continue;
  3166. }
  3167. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3168. }
  3169. foreach ($unselectedIds as $pid) {
  3170. $dr = $this->purchaseOrderDetai($sid, $pid);
  3171. if (!is_array($dr)) {
  3172. continue;
  3173. }
  3174. $key = $this->notifySupplierDedupeKey($dr);
  3175. if (!isset($winners[$key])) {
  3176. $losers[$key] = $dr;
  3177. }
  3178. }
  3179. }
  3180. if ($winners === [] && $losers === []) {
  3181. return;
  3182. }
  3183. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3184. $sendSmsSafe = function ($phone, $content) {
  3185. $phone = trim((string)$phone);
  3186. if ($phone === '') {
  3187. return;
  3188. }
  3189. try {
  3190. $this->smsbao($phone, $content);
  3191. } catch (\Throwable $e) {
  3192. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3193. }
  3194. };
  3195. foreach ($winners as $dr) {
  3196. $cname = trim((string)($dr['company_name'] ?? ''));
  3197. $ph = trim((string)($dr['phone'] ?? ''));
  3198. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3199. 'company_name' => $cname,
  3200. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3201. 'phone' => $ph,
  3202. ]));
  3203. $sendSmsSafe($ph, $sms);
  3204. }
  3205. foreach ($losers as $dr) {
  3206. $cname = trim((string)($dr['company_name'] ?? ''));
  3207. $ph = trim((string)($dr['phone'] ?? ''));
  3208. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3209. 'company_name' => $cname,
  3210. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3211. 'phone' => $ph,
  3212. ]));
  3213. $sendSmsSafe($ph, $sms);
  3214. }
  3215. }
  3216. /**
  3217. * 短信去重键:优先手机号,否则公司名
  3218. */
  3219. protected function notifySupplierDedupeKey(array $detailRow): string
  3220. {
  3221. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  3222. if ($ph !== '') {
  3223. return 'p:' . $ph;
  3224. }
  3225. $cn = trim((string)($detailRow['company_name'] ?? ''));
  3226. return 'c:' . $cn;
  3227. }
  3228. /**
  3229. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3230. *
  3231. * @param int[] $detailIds
  3232. */
  3233. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3234. {
  3235. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3236. if ($detailIds === []) {
  3237. return;
  3238. }
  3239. $payload = ['status_name' => $statusName];
  3240. try {
  3241. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3242. } catch (\Throwable $e) {
  3243. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3244. }
  3245. }
  3246. /**
  3247. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3248. */
  3249. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3250. {
  3251. try {
  3252. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3253. } catch (\Throwable $e) {
  3254. return;
  3255. }
  3256. if (!is_array($rows)) {
  3257. return;
  3258. }
  3259. foreach ($rows as $dr) {
  3260. if (!is_array($dr)) {
  3261. continue;
  3262. }
  3263. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3264. if ($id <= 0) {
  3265. continue;
  3266. }
  3267. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3268. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3269. try {
  3270. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3271. } catch (\Throwable $e) {
  3272. }
  3273. }
  3274. }
  3275. /**
  3276. * @param array<string, mixed> $detailRow
  3277. */
  3278. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3279. {
  3280. $am = $detailRow['amount'] ?? null;
  3281. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3282. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3283. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3284. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3285. }
  3286. /**
  3287. * @return int[]
  3288. */
  3289. protected function purchaseOrderDetail(int $scydgyId): array
  3290. {
  3291. if (!$this->isValidScydgyRowId($scydgyId)) {
  3292. return [];
  3293. }
  3294. try {
  3295. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3296. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3297. $list = $listQuery->select();
  3298. } catch (\Throwable $e) {
  3299. return [];
  3300. }
  3301. if (!is_array($list)) {
  3302. return [];
  3303. }
  3304. $ids = [];
  3305. foreach ($list as $r) {
  3306. if (!is_array($r)) {
  3307. continue;
  3308. }
  3309. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3310. if ($pk > 0) {
  3311. $ids[] = $pk;
  3312. }
  3313. }
  3314. return array_values(array_unique($ids));
  3315. }
  3316. /**
  3317. * 获取当前登录用户信息 [id, 展示名]
  3318. */
  3319. protected function GetUseName(): array
  3320. {
  3321. $id = 0;
  3322. $name = '';
  3323. try {
  3324. if ($this->auth && $this->auth->isLogin()) {
  3325. $u = $this->auth->getUserInfo();
  3326. if (is_array($u)) {
  3327. $id = (int)($u['id'] ?? 0);
  3328. $name = trim((string)($u['nickname'] ?? ''));
  3329. if ($name === '') {
  3330. $name = trim((string)($u['username'] ?? ''));
  3331. }
  3332. }
  3333. }
  3334. } catch (\Throwable $e) {
  3335. }
  3336. if ($name === '') {
  3337. $name = '未知用户';
  3338. }
  3339. return [$id, $name];
  3340. }
  3341. /**
  3342. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3343. */
  3344. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3345. {
  3346. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3347. }
  3348. /**
  3349. * 按主键取一条
  3350. */
  3351. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3352. {
  3353. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3354. return [];
  3355. }
  3356. try {
  3357. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3358. if (is_array($one)) {
  3359. return $one;
  3360. }
  3361. } catch (\Throwable $e) {
  3362. }
  3363. try {
  3364. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3365. if (is_array($one)) {
  3366. return $one;
  3367. }
  3368. } catch (\Throwable $e) {
  3369. }
  3370. return [];
  3371. }
  3372. /**
  3373. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3374. */
  3375. protected function formatProcuremenDetailTime($v): string
  3376. {
  3377. if ($v === null || $v === '') {
  3378. return '';
  3379. }
  3380. if (is_numeric($v) && (int)$v > 946684800) {
  3381. return date('Y-m-d H:i:s', (int)$v);
  3382. }
  3383. return ProcuremenTime::formatDisplayDateTime($v);
  3384. }
  3385. /**
  3386. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3387. */
  3388. protected function formatDeliveryYmd($v): string
  3389. {
  3390. if ($v === null || $v === '') {
  3391. return '';
  3392. }
  3393. $s = trim((string)$v);
  3394. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3395. return '';
  3396. }
  3397. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  3398. return $m[1];
  3399. }
  3400. $ts = strtotime($s);
  3401. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  3402. }
  3403. /**
  3404. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  3405. */
  3406. protected function detailRowSupplierOperated(array $r): bool
  3407. {
  3408. $am = $r['amount'] ?? null;
  3409. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3410. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3411. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3412. return $okAmt || $okDel;
  3413. }
  3414. /**
  3415. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  3416. */
  3417. protected function resolveDetailSupplierOperTime(array $r): string
  3418. {
  3419. if (!$this->detailRowSupplierOperated($r)) {
  3420. return '';
  3421. }
  3422. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  3423. if ($t !== '') {
  3424. return $t;
  3425. }
  3426. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  3427. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  3428. continue;
  3429. }
  3430. $t = $this->formatProcuremenDetailTime($r[$col]);
  3431. if ($t !== '') {
  3432. return $t;
  3433. }
  3434. }
  3435. return '';
  3436. }
  3437. /**
  3438. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  3439. */
  3440. protected function detailRowSupplierAccepted(array $r): bool
  3441. {
  3442. $am = $r['amount'] ?? null;
  3443. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3444. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3445. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3446. return $okAmt && $okDel;
  3447. }
  3448. /**
  3449. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  3450. */
  3451. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  3452. {
  3453. if ($detailCount > 0) {
  3454. return true;
  3455. }
  3456. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  3457. return true;
  3458. }
  3459. $pickTime = trim((string)($main['pick_time'] ?? ''));
  3460. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  3461. return true;
  3462. }
  3463. return false;
  3464. }
  3465. /**
  3466. * 下发时间:优先 pick_time,其次首条下发明细时间
  3467. */
  3468. protected function resolveProcuremenIssueTime(array $main, array $details): string
  3469. {
  3470. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  3471. if ($issueTime !== '') {
  3472. return $issueTime;
  3473. }
  3474. foreach ($details as $dr) {
  3475. if (!is_array($dr)) {
  3476. continue;
  3477. }
  3478. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3479. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  3480. $issueTime = $t;
  3481. }
  3482. }
  3483. if ($issueTime !== '') {
  3484. return $issueTime;
  3485. }
  3486. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3487. }
  3488. /**
  3489. * 直接点「完结」时间:优先操作记录 mark_complete
  3490. */
  3491. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  3492. {
  3493. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  3494. }
  3495. /**
  3496. * 操作记录时间(取指定 action 最近一条)
  3497. *
  3498. * @param string|array<int, string> $actions
  3499. */
  3500. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  3501. {
  3502. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  3503. }
  3504. /**
  3505. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  3506. *
  3507. * @param array $main purchase_order 一行
  3508. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  3509. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  3510. */
  3511. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  3512. {
  3513. $issueCnt = count($details);
  3514. $acceptCnt = 0;
  3515. $pickedName = '';
  3516. $pickedTime = '';
  3517. foreach ($details as $dr) {
  3518. if (!is_array($dr)) {
  3519. continue;
  3520. }
  3521. if ($this->detailRowSupplierAccepted($dr)) {
  3522. $acceptCnt++;
  3523. }
  3524. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3525. if ($pickedName === '') {
  3526. $pickedName = trim((string)($dr['company_name'] ?? ''));
  3527. }
  3528. if ($pickedTime === '') {
  3529. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  3530. if ($pickedTime === '') {
  3531. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3532. }
  3533. }
  3534. }
  3535. }
  3536. $hasMain = $main !== [];
  3537. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  3538. if ($poTime === '') {
  3539. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  3540. }
  3541. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  3542. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  3543. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  3544. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  3545. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  3546. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  3547. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  3548. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  3549. $supplierTime = '';
  3550. if ($acceptCnt > 0) {
  3551. foreach ($details as $dr) {
  3552. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  3553. continue;
  3554. }
  3555. $t = $this->resolveDetailSupplierOperTime($dr);
  3556. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  3557. $supplierTime = $t;
  3558. }
  3559. }
  3560. }
  3561. $directComplete = ($mainCompleted && !$issued);
  3562. $doneTime = '';
  3563. if ($mainCompleted) {
  3564. if ($directComplete) {
  3565. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  3566. }
  3567. if ($doneTime === '') {
  3568. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3569. }
  3570. if ($doneTime === '') {
  3571. foreach ($details as $dr) {
  3572. if (!is_array($dr)) {
  3573. continue;
  3574. }
  3575. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  3576. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  3577. $doneTime = $t;
  3578. }
  3579. }
  3580. }
  3581. if ($doneTime === '') {
  3582. $doneTime = $poTime;
  3583. }
  3584. if ($confirmApproveTime !== '') {
  3585. $doneTime = $confirmApproveTime;
  3586. }
  3587. }
  3588. if ($directComplete) {
  3589. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  3590. $step1Done = $hasMain;
  3591. $step2Done = false;
  3592. $step3Done = false;
  3593. $step4Done = false;
  3594. $step5Done = false;
  3595. $step6Done = true;
  3596. } else {
  3597. $step1Done = $issued;
  3598. $step2Done = $issued;
  3599. $step3Done = $acceptCnt > 0;
  3600. $step4Done = $wflowPendingApproval;
  3601. if (!$step4Done) {
  3602. foreach ($details as $dr) {
  3603. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3604. $step4Done = true;
  3605. break;
  3606. }
  3607. }
  3608. }
  3609. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  3610. $step6Done = $mainCompleted;
  3611. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  3612. if ($mainCompleted && $issued) {
  3613. $step3Done = true;
  3614. $step4Done = true;
  3615. $step5Done = true;
  3616. if ($supplierTime === '') {
  3617. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3618. if ($fillT !== '') {
  3619. $supplierTime = $fillT;
  3620. }
  3621. }
  3622. if ($pickedTime === '') {
  3623. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3624. if ($fillT !== '') {
  3625. $pickedTime = $fillT;
  3626. }
  3627. }
  3628. if ($auditSelectTime === '') {
  3629. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3630. if ($fillT !== '') {
  3631. $auditSelectTime = $fillT;
  3632. }
  3633. }
  3634. if ($confirmApproveTime === '') {
  3635. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3636. if ($fillT !== '') {
  3637. $confirmApproveTime = $fillT;
  3638. }
  3639. }
  3640. }
  3641. }
  3642. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  3643. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  3644. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  3645. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  3646. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  3647. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  3648. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  3649. $steps = [
  3650. [
  3651. 'title' => '未发',
  3652. 'subtitle' => '',
  3653. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  3654. 'done' => $step1Done,
  3655. ],
  3656. [
  3657. 'title' => '下发',
  3658. 'subtitle' => '',
  3659. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  3660. 'done' => $step2Done,
  3661. ],
  3662. [
  3663. 'title' => '供应商接单',
  3664. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  3665. 'time' => '',
  3666. 'done' => $step3Done,
  3667. ],
  3668. [
  3669. 'title' => '待确认',
  3670. 'subtitle' => $step4Done
  3671. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  3672. : ($issued ? '待选供应商' : ''),
  3673. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  3674. 'done' => $step4Done,
  3675. ],
  3676. [
  3677. 'title' => '待审批',
  3678. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  3679. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  3680. 'done' => $step5Done,
  3681. ],
  3682. [
  3683. 'title' => '已完结',
  3684. 'subtitle' => '',
  3685. 'time' => $step6Done ? $doneTime : '',
  3686. 'done' => $step6Done,
  3687. ],
  3688. ];
  3689. $currentIdx = count($steps) - 1;
  3690. if (!$directComplete) {
  3691. foreach ($steps as $i => $s) {
  3692. if (!$s['done']) {
  3693. $currentIdx = $i;
  3694. break;
  3695. }
  3696. }
  3697. }
  3698. $nSteps = count($steps);
  3699. foreach ($steps as $idx => &$s) {
  3700. $s['current'] = ($idx === $currentIdx);
  3701. if ($idx === 0) {
  3702. $s['pdf_left_bg'] = '';
  3703. } else {
  3704. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  3705. }
  3706. if ($idx >= $nSteps - 1) {
  3707. $s['pdf_right_bg'] = '';
  3708. } else {
  3709. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  3710. }
  3711. }
  3712. unset($s);
  3713. $labelMap = [
  3714. 'CCYDH' => '订单号',
  3715. 'CYJMC' => '印件名称',
  3716. 'CCLBMMC' => '承揽部门',
  3717. 'CGYMC' => '工序名称',
  3718. 'CDW' => '单位',
  3719. 'NGZL' => '工作量',
  3720. 'CDF' => '单价',
  3721. 'cGzzxMc' => '工作中心',
  3722. 'MBZ' => '备注',
  3723. 'This_quantity' => '本次数量',
  3724. 'ceilingPrice' => '最高限价',
  3725. ];
  3726. $orderSummary = [];
  3727. foreach ($labelMap as $key => $lab) {
  3728. if (!array_key_exists($key, $main)) {
  3729. continue;
  3730. }
  3731. $val = $main[$key];
  3732. if ($val === null) {
  3733. $val = '';
  3734. } elseif (!is_scalar($val)) {
  3735. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  3736. } else {
  3737. $val = (string)$val;
  3738. }
  3739. $orderSummary[] = ['label' => $lab, 'value' => $val];
  3740. }
  3741. $orderSummaryGrid = [];
  3742. $n = count($orderSummary);
  3743. for ($i = 0; $i < $n; $i += 2) {
  3744. $left = $orderSummary[$i];
  3745. $hasRight = ($i + 1) < $n;
  3746. $orderSummaryGrid[] = [
  3747. 'l1' => $left['label'],
  3748. 'v1' => $left['value'],
  3749. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  3750. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  3751. ];
  3752. }
  3753. return [
  3754. 'steps' => $steps,
  3755. 'orderSummary' => $orderSummary,
  3756. 'orderSummaryGrid' => $orderSummaryGrid,
  3757. 'detailRows' => $details,
  3758. ];
  3759. }
  3760. /**
  3761. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  3762. *
  3763. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  3764. */
  3765. protected function prepareProcuremenDetailsView(string $ids): array
  3766. {
  3767. $main = [];
  3768. try {
  3769. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3770. $main = is_array($one) ? $one : [];
  3771. } catch (\Throwable $e) {
  3772. $main = [];
  3773. }
  3774. $details = [];
  3775. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  3776. if ($mergeRows === []) {
  3777. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  3778. if ($mergeRows === [] && $main !== []) {
  3779. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  3780. }
  3781. }
  3782. $detailSidList = [];
  3783. $anchorSid = (int)$ids;
  3784. if ($anchorSid !== 0) {
  3785. $detailSidList[$anchorSid] = true;
  3786. }
  3787. foreach ($mergeRows as $mr) {
  3788. if (!is_array($mr)) {
  3789. continue;
  3790. }
  3791. $sid = $this->extractScydgyRowId($mr);
  3792. if ($sid !== 0) {
  3793. $detailSidList[$sid] = true;
  3794. }
  3795. }
  3796. try {
  3797. if ($detailSidList !== []) {
  3798. $details = Db::table('purchase_order_detail')
  3799. ->where('scydgy_id', 'in', array_keys($detailSidList))
  3800. ->order('id', 'asc')
  3801. ->select();
  3802. }
  3803. } catch (\Throwable $e) {
  3804. $details = [];
  3805. }
  3806. if (!is_array($details)) {
  3807. $details = [];
  3808. }
  3809. foreach ($details as &$r) {
  3810. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  3811. $r['id'] = $r['ID'];
  3812. }
  3813. if (isset($r['createtime'])) {
  3814. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  3815. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  3816. } else {
  3817. $r['createtime_text'] = (string)$r['createtime'];
  3818. }
  3819. } else {
  3820. $r['createtime_text'] = '';
  3821. }
  3822. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  3823. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  3824. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  3825. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  3826. }
  3827. unset($r);
  3828. $activeDetails = [];
  3829. foreach ($details as $r) {
  3830. if (is_array($r) && empty($r['is_void'])) {
  3831. $activeDetails[] = $r;
  3832. }
  3833. }
  3834. $operLogs = [];
  3835. try {
  3836. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  3837. } catch (\Throwable $e) {
  3838. $operLogs = [];
  3839. }
  3840. if (!is_array($operLogs)) {
  3841. $operLogs = [];
  3842. }
  3843. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  3844. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  3845. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  3846. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  3847. if ($ccydh === '') {
  3848. foreach ($details as $r) {
  3849. if (!is_array($r)) {
  3850. continue;
  3851. }
  3852. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  3853. if ($ccydh !== '') {
  3854. break;
  3855. }
  3856. }
  3857. }
  3858. $this->view->assign('ccydh', $ccydh);
  3859. $this->view->assign('steps', $bundle['steps']);
  3860. $this->view->assign('orderSummary', $bundle['orderSummary']);
  3861. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  3862. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  3863. $this->view->assign('processCount', count($mergeRows));
  3864. $this->view->assign('detailRows', $details);
  3865. $this->view->assign('supplierQuoteGroups', $quoteView['supplier_groups']);
  3866. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  3867. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  3868. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  3869. $this->view->assign('operLogs', $operLogs);
  3870. return [
  3871. 'ok' => $main !== [] || $details !== [],
  3872. 'ccydh' => $ccydh,
  3873. ];
  3874. }
  3875. /**
  3876. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  3877. */
  3878. public function details()
  3879. {
  3880. $ids = $this->request->param('ids', $this->request->param('id', ''));
  3881. if (is_array($ids)) {
  3882. $ids = isset($ids[0]) ? $ids[0] : '';
  3883. }
  3884. $ids = trim((string)$ids);
  3885. if ($ids === '') {
  3886. $this->error(__('Invalid parameters'));
  3887. }
  3888. $this->assertManualOrderDetailsViewable((int)$ids);
  3889. $this->prepareProcuremenDetailsView($ids);
  3890. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  3891. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  3892. $this->view->engine->layout(false);
  3893. try {
  3894. return $this->view->fetch('procuremen/details_dialog_shell');
  3895. } finally {
  3896. if ($restoreLayout) {
  3897. $this->view->engine->layout($restoreLayout);
  3898. }
  3899. }
  3900. }
  3901. /**
  3902. * 解析合并审核工序行(订单号须一致,且均未协助)
  3903. *
  3904. * @return array<int, array<string, mixed>>
  3905. */
  3906. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  3907. {
  3908. $primary = json_decode($rowJson, true);
  3909. if (!is_array($primary)) {
  3910. $this->error(__('Invalid parameters'));
  3911. }
  3912. $merge = json_decode($mergeRowsJson, true);
  3913. if (!is_array($merge) || $merge === []) {
  3914. $merge = [$primary];
  3915. }
  3916. $seen = [];
  3917. $out = [];
  3918. foreach ($merge as $r) {
  3919. if (!is_array($r)) {
  3920. continue;
  3921. }
  3922. $id = $this->extractScydgyRowId($r);
  3923. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  3924. continue;
  3925. }
  3926. $seen[$id] = true;
  3927. $out[] = $r;
  3928. }
  3929. if ($out === []) {
  3930. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  3931. }
  3932. $ccydh = null;
  3933. foreach ($out as $r) {
  3934. $dh = trim((string)($r['CCYDH'] ?? ''));
  3935. if ($ccydh === null) {
  3936. $ccydh = $dh;
  3937. } elseif ($dh !== $ccydh) {
  3938. $this->error('合并审核要求所选行的订单号一致');
  3939. }
  3940. }
  3941. $ids = [];
  3942. foreach ($out as $r) {
  3943. $id = $this->extractScydgyRowId($r);
  3944. if ($this->isValidScydgyRowId($id)) {
  3945. $ids[$id] = true;
  3946. }
  3947. }
  3948. $poBySid = [];
  3949. $detCntBySid = [];
  3950. if ($ids !== []) {
  3951. $idList = array_keys($ids);
  3952. try {
  3953. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  3954. if (is_array($poList)) {
  3955. foreach ($poList as $po) {
  3956. if (!is_array($po)) {
  3957. continue;
  3958. }
  3959. $sid = (int)($po['scydgy_id'] ?? 0);
  3960. if ($this->isValidScydgyRowId($sid)) {
  3961. $poBySid[$sid] = $po;
  3962. }
  3963. }
  3964. }
  3965. } catch (\Throwable $e) {
  3966. }
  3967. try {
  3968. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  3969. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  3970. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  3971. if (is_array($detRows)) {
  3972. foreach ($detRows as $dr) {
  3973. if (!is_array($dr)) {
  3974. continue;
  3975. }
  3976. $sid = (int)($dr['scydgy_id'] ?? 0);
  3977. if ($this->isValidScydgyRowId($sid)) {
  3978. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  3979. }
  3980. }
  3981. }
  3982. } catch (\Throwable $e) {
  3983. }
  3984. }
  3985. foreach ($out as $r) {
  3986. $id = $this->extractScydgyRowId($r);
  3987. if (!$this->isValidScydgyRowId($id)) {
  3988. continue;
  3989. }
  3990. $po = $poBySid[$id] ?? null;
  3991. if (!is_array($po)) {
  3992. continue;
  3993. }
  3994. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  3995. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3996. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  3997. }
  3998. $detCnt = (int)($detCntBySid[$id] ?? 0);
  3999. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4000. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4001. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4002. }
  4003. }
  4004. return $out;
  4005. }
  4006. /**
  4007. * 规范化下发/确认时勾选的供应商
  4008. *
  4009. * @param array<int, mixed> $companies
  4010. * @return array<int, array<string, string>>
  4011. */
  4012. protected function normalizePickCompanies(array $companies): array
  4013. {
  4014. $out = [];
  4015. foreach ($companies as $c) {
  4016. if (!is_array($c)) {
  4017. continue;
  4018. }
  4019. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  4020. if ($name === '') {
  4021. continue;
  4022. }
  4023. $out[] = [
  4024. 'name' => $name,
  4025. 'company_name' => $name,
  4026. 'username' => trim((string)($c['username'] ?? '')),
  4027. 'email' => trim((string)($c['email'] ?? '')),
  4028. 'phone' => trim((string)($c['phone'] ?? '')),
  4029. 'company_type' => trim((string)($c['company_type'] ?? $c['category'] ?? '')),
  4030. ];
  4031. }
  4032. return $out;
  4033. }
  4034. /**
  4035. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  4036. *
  4037. * @param array<int, array<string, mixed>> $pool
  4038. * @return array<int, array<string, mixed>>
  4039. */
  4040. protected function collapseProcuremenPoolByOrder(array $pool): array
  4041. {
  4042. if ($pool === []) {
  4043. return [];
  4044. }
  4045. $groups = [];
  4046. foreach ($pool as $row) {
  4047. if (!is_array($row)) {
  4048. continue;
  4049. }
  4050. $dh = trim((string)($row['CCYDH'] ?? ''));
  4051. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  4052. if (!isset($groups[$key])) {
  4053. $groups[$key] = [];
  4054. }
  4055. $groups[$key][] = $row;
  4056. }
  4057. $out = [];
  4058. foreach ($groups as $ccydh => $rows) {
  4059. if ($rows === []) {
  4060. continue;
  4061. }
  4062. usort($rows, function ($a, $b) {
  4063. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  4064. });
  4065. $head = $rows[0];
  4066. $gymcList = [];
  4067. foreach ($rows as $r) {
  4068. $g = trim((string)($r['CGYMC'] ?? ''));
  4069. if ($g !== '' && !in_array($g, $gymcList, true)) {
  4070. $gymcList[] = $g;
  4071. }
  4072. }
  4073. $merged = $head;
  4074. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  4075. $merged['process_count'] = count($rows);
  4076. $merged['_order_merge_rows'] = $rows;
  4077. if (count($rows) > 1) {
  4078. $merged['CGYMC'] = implode('、', $gymcList);
  4079. }
  4080. $mergedPickTime = '';
  4081. foreach ($rows as $r) {
  4082. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  4083. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  4084. $mergedPickTime = $t;
  4085. }
  4086. }
  4087. if ($mergedPickTime !== '') {
  4088. $merged['pick_time'] = $mergedPickTime;
  4089. }
  4090. $out[] = $merged;
  4091. }
  4092. usort($out, function ($a, $b) {
  4093. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  4094. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  4095. if ($ta === $tb) {
  4096. $ida = (int)($a['purchase_order_id'] ?? 0);
  4097. $idb = (int)($b['purchase_order_id'] ?? 0);
  4098. if ($ida !== $idb) {
  4099. return $idb <=> $ida;
  4100. }
  4101. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  4102. }
  4103. if ($ta === '') {
  4104. return 1;
  4105. }
  4106. if ($tb === '') {
  4107. return -1;
  4108. }
  4109. return strcmp($tb, $ta);
  4110. });
  4111. return $out;
  4112. }
  4113. /**
  4114. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  4115. *
  4116. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4117. */
  4118. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  4119. {
  4120. $scydgyId = trim($scydgyId);
  4121. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4122. if ($scydgyId === '') {
  4123. return $empty;
  4124. }
  4125. try {
  4126. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4127. } catch (\Throwable $e) {
  4128. $anchor = null;
  4129. }
  4130. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  4131. return $empty;
  4132. }
  4133. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4134. if ($ccydh === '') {
  4135. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4136. }
  4137. try {
  4138. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4139. } catch (\Throwable $e) {
  4140. $pos = [$anchor];
  4141. }
  4142. if (!is_array($pos) || $pos === []) {
  4143. $pos = [$anchor];
  4144. }
  4145. return [
  4146. 'ccydh' => $ccydh,
  4147. 'pos' => $pos,
  4148. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4149. ];
  4150. }
  4151. /**
  4152. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4153. */
  4154. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4155. {
  4156. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4157. return false;
  4158. }
  4159. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4160. return false;
  4161. }
  4162. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4163. return true;
  4164. }
  4165. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4166. $sid = (int)($po['scydgy_id'] ?? 0);
  4167. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4168. }
  4169. return false;
  4170. }
  4171. /**
  4172. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4173. *
  4174. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4175. */
  4176. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4177. {
  4178. $scydgyId = trim($scydgyId);
  4179. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4180. if ($scydgyId === '') {
  4181. return $empty;
  4182. }
  4183. try {
  4184. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4185. } catch (\Throwable $e) {
  4186. $anchor = null;
  4187. }
  4188. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4189. return $empty;
  4190. }
  4191. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4192. if ($ccydh === '') {
  4193. return [
  4194. 'ccydh' => '',
  4195. 'pos' => [$anchor],
  4196. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  4197. ];
  4198. }
  4199. try {
  4200. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  4201. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  4202. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  4203. } catch (\Throwable $e) {
  4204. $pos = [$anchor];
  4205. }
  4206. if (!is_array($pos) || $pos === []) {
  4207. $pos = [$anchor];
  4208. }
  4209. $pos = array_values(array_filter($pos, function ($po) {
  4210. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  4211. }));
  4212. if ($pos === []) {
  4213. $pos = [$anchor];
  4214. }
  4215. return [
  4216. 'ccydh' => $ccydh,
  4217. 'pos' => $pos,
  4218. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4219. ];
  4220. }
  4221. /**
  4222. * @param array<int, array<string, mixed>> $purchaseOrders
  4223. * @return array<int, array<string, mixed>>
  4224. */
  4225. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  4226. {
  4227. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  4228. $byId = [];
  4229. foreach ($pool as $r) {
  4230. if (!is_array($r)) {
  4231. continue;
  4232. }
  4233. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  4234. if ($this->isValidScydgyRowId($sid)) {
  4235. $byId[$sid] = $r;
  4236. }
  4237. }
  4238. $out = [];
  4239. foreach ($purchaseOrders as $po) {
  4240. if (!is_array($po)) {
  4241. continue;
  4242. }
  4243. $sid = (int)($po['scydgy_id'] ?? 0);
  4244. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  4245. $out[] = $byId[$sid];
  4246. }
  4247. }
  4248. return $out;
  4249. }
  4250. /**
  4251. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  4252. *
  4253. * @return array<int, array<string, mixed>>
  4254. */
  4255. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  4256. {
  4257. $scydgyId = trim($scydgyId);
  4258. if ($scydgyId === '') {
  4259. return [];
  4260. }
  4261. try {
  4262. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4263. } catch (\Throwable $e) {
  4264. $anchor = null;
  4265. }
  4266. if (!is_array($anchor)) {
  4267. return [];
  4268. }
  4269. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  4270. return [];
  4271. }
  4272. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4273. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  4274. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  4275. try {
  4276. $q = Db::table('purchase_order');
  4277. if ($ccydh !== '') {
  4278. $q->where('CCYDH', $ccydh);
  4279. } else {
  4280. $q->where('scydgy_id', $scydgyId);
  4281. }
  4282. if ($isValidPick) {
  4283. $q->where('pick_time', $pickTime);
  4284. }
  4285. $pos = $q->order('scydgy_id', 'asc')->select();
  4286. } catch (\Throwable $e) {
  4287. $pos = [$anchor];
  4288. }
  4289. if (!is_array($pos) || $pos === []) {
  4290. $pos = [$anchor];
  4291. }
  4292. $pos = array_values(array_filter($pos, function ($po) {
  4293. if (!is_array($po)) {
  4294. return false;
  4295. }
  4296. $mr = $po['mod_rq'] ?? null;
  4297. if ($mr === null || $mr === '') {
  4298. return true;
  4299. }
  4300. $mrs = trim((string)$mr);
  4301. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  4302. }));
  4303. if ($pos === []) {
  4304. $pos = [$anchor];
  4305. }
  4306. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  4307. if ($rows === []) {
  4308. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  4309. }
  4310. return $rows;
  4311. }
  4312. /**
  4313. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  4314. *
  4315. * @param array<int, array<string, mixed>> $mergeRows
  4316. * @return array<int, array<string, mixed>>
  4317. */
  4318. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  4319. {
  4320. $list = array_values($mergeRows);
  4321. $n = count($list);
  4322. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  4323. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  4324. $mergeSame = $n > 1 && $orderKey0 !== '';
  4325. if ($mergeSame) {
  4326. foreach ($list as $rr) {
  4327. if (!is_array($rr)) {
  4328. $mergeSame = false;
  4329. break;
  4330. }
  4331. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  4332. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  4333. $mergeSame = false;
  4334. break;
  4335. }
  4336. }
  4337. }
  4338. $out = [];
  4339. foreach ($list as $idx => $r) {
  4340. if (!is_array($r)) {
  4341. continue;
  4342. }
  4343. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  4344. if (is_scalar($qty)) {
  4345. $qty = trim((string)$qty);
  4346. } else {
  4347. $qty = '';
  4348. }
  4349. if ($qty === '') {
  4350. $gzl = $r['NGZL'] ?? '';
  4351. if (is_scalar($gzl)) {
  4352. $qty = trim((string)$gzl);
  4353. }
  4354. }
  4355. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  4356. $sid = $this->extractScydgyRowId($r);
  4357. $out[] = [
  4358. 'seq' => $idx + 1,
  4359. 'scydgy_id' => $sid,
  4360. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  4361. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  4362. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  4363. 'CDW' => trim((string)($r['CDW'] ?? '')),
  4364. 'NGZL' => $r['NGZL'] ?? '',
  4365. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  4366. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  4367. 'CDF' => trim((string)($r['CDF'] ?? '')),
  4368. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  4369. 'show_order_cells' => !$mergeSame || $idx === 0,
  4370. 'order_rowspan' => $mergeSame ? $n : 1,
  4371. ];
  4372. }
  4373. return $out;
  4374. }
  4375. /**
  4376. * 解析金额/数量(去千分位等非数字字符)
  4377. */
  4378. protected function parseProcuremenMoneyNumber($value): ?float
  4379. {
  4380. if ($value === null || $value === '') {
  4381. return null;
  4382. }
  4383. if (is_numeric($value)) {
  4384. return (float)$value;
  4385. }
  4386. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  4387. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  4388. }
  4389. protected function formatProcuremenMoneyDisplay(?float $amount): string
  4390. {
  4391. if ($amount === null) {
  4392. return '';
  4393. }
  4394. return (string)(int)round($amount);
  4395. }
  4396. /**
  4397. * 列表/详情展示:工作量为 0 时显示空
  4398. */
  4399. protected function formatProcuremenWorkloadDisplay($value): string
  4400. {
  4401. if ($value === null || $value === '') {
  4402. return '';
  4403. }
  4404. $s = trim((string)$value);
  4405. if ($s === '') {
  4406. return '';
  4407. }
  4408. if (is_numeric($s) && (float)$s == 0) {
  4409. return '';
  4410. }
  4411. return $s;
  4412. }
  4413. /**
  4414. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  4415. */
  4416. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  4417. {
  4418. foreach ($details as $d) {
  4419. if (!is_array($d)) {
  4420. continue;
  4421. }
  4422. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  4423. $cn = trim((string)($d['company_name'] ?? ''));
  4424. if ($cn !== '') {
  4425. return $cn;
  4426. }
  4427. }
  4428. }
  4429. return trim((string)($main['pick_company_name'] ?? ''));
  4430. }
  4431. /**
  4432. * 详情报价小计:单价 × 本工序本次数量
  4433. */
  4434. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  4435. {
  4436. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  4437. if ($unit === null) {
  4438. return null;
  4439. }
  4440. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  4441. if ($qty === null || $qty <= 0) {
  4442. return null;
  4443. }
  4444. return $unit * $qty;
  4445. }
  4446. /**
  4447. * 详情页:工序小计 + 供应商分组报价与总计
  4448. *
  4449. * @param array<int, array<string, mixed>> $mergeRows
  4450. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  4451. * @return array{
  4452. * process_rows: array,
  4453. * supplier_groups: array,
  4454. * order_total_text: string,
  4455. * order_total_has: bool,
  4456. * selected_company: string
  4457. * }
  4458. */
  4459. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  4460. {
  4461. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  4462. $deadlineReached = $this->isProcuremenQuoteDeadlineReached($main['sys_rq'] ?? '');
  4463. $qtyBySid = [];
  4464. $gymcBySid = [];
  4465. $orderedSids = [];
  4466. foreach ($mergeRows as $mr) {
  4467. if (!is_array($mr)) {
  4468. continue;
  4469. }
  4470. $sid = $this->extractScydgyRowId($mr);
  4471. if ($sid > 0) {
  4472. $orderedSids[] = $sid;
  4473. }
  4474. $qty = trim((string)($mr['This_quantity'] ?? ''));
  4475. if ($qty === '') {
  4476. $qty = trim((string)($mr['NGZL'] ?? ''));
  4477. }
  4478. $qtyBySid[$sid] = $qty;
  4479. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  4480. }
  4481. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  4482. $detailByCompanySid = [];
  4483. foreach ($details as $d) {
  4484. if (!is_array($d)) {
  4485. continue;
  4486. }
  4487. $cn = trim((string)($d['company_name'] ?? ''));
  4488. $sid = (int)($d['scydgy_id'] ?? 0);
  4489. if ($cn === '' || $sid === 0) {
  4490. continue;
  4491. }
  4492. if (!isset($detailByCompanySid[$cn])) {
  4493. $detailByCompanySid[$cn] = [];
  4494. }
  4495. $detailByCompanySid[$cn][$sid] = $d;
  4496. }
  4497. $supplierGroups = [];
  4498. foreach ($detailByCompanySid as $cn => $bySid) {
  4499. $lines = [];
  4500. $groupTotal = 0.0;
  4501. $groupHas = false;
  4502. $groupVoid = true;
  4503. $usedSids = [];
  4504. $appendLine = function (int $sid, array $d) use (
  4505. &$lines,
  4506. &$groupTotal,
  4507. &$groupHas,
  4508. &$groupVoid,
  4509. $qtyBySid,
  4510. $gymcBySid,
  4511. $deadlineReached
  4512. ) {
  4513. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  4514. if (!$isVoid) {
  4515. $groupVoid = false;
  4516. }
  4517. $qtyStr = $qtyBySid[$sid] ?? '';
  4518. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4519. $am = trim((string)($d['amount'] ?? ''));
  4520. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  4521. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  4522. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  4523. $sub = null;
  4524. if (!$isVoid && $amountNum !== null) {
  4525. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  4526. }
  4527. $ct = $this->resolveDetailSupplierOperTime($d);
  4528. $line = [
  4529. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  4530. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am,
  4531. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  4532. 'delivery_ymd' => $deliveryYmd,
  4533. 'amount_filled' => $amountFilled,
  4534. 'delivery_filled' => $deliveryFilled,
  4535. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  4536. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  4537. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  4538. 'is_void' => $isVoid,
  4539. 'oper_time_text' => $ct,
  4540. ];
  4541. if (!$deadlineReached && !$isVoid) {
  4542. $this->maskSupplierQuoteLineBeforeDeadline($line);
  4543. } elseif ($sub !== null) {
  4544. $groupTotal += $sub;
  4545. $groupHas = true;
  4546. }
  4547. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  4548. };
  4549. foreach ($orderedSids as $sid) {
  4550. if (!isset($bySid[$sid])) {
  4551. continue;
  4552. }
  4553. $usedSids[$sid] = true;
  4554. $appendLine($sid, $bySid[$sid]);
  4555. }
  4556. foreach ($bySid as $sid => $d) {
  4557. if (isset($usedSids[$sid])) {
  4558. continue;
  4559. }
  4560. $appendLine((int)$sid, $d);
  4561. }
  4562. $firstDetail = null;
  4563. foreach ($bySid as $d) {
  4564. if (is_array($d)) {
  4565. $firstDetail = $d;
  4566. break;
  4567. }
  4568. }
  4569. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  4570. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  4571. if ($username === '' && $ph !== '') {
  4572. $username = $this->resolveCustomerContactName($ph, $cn);
  4573. }
  4574. $lineCount = count($lines);
  4575. $supplierGroups[] = [
  4576. 'company_name' => $cn,
  4577. 'username' => $username,
  4578. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  4579. 'phone' => $ph,
  4580. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  4581. 'is_void' => $groupVoid,
  4582. 'lines' => $lines,
  4583. 'line_count' => $lineCount,
  4584. 'display_rowspan'=> $lineCount + ($lineCount > 0 ? 1 : 0),
  4585. 'total_text' => ($deadlineReached && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  4586. 'has_total' => $lineCount > 0,
  4587. ];
  4588. }
  4589. usort($supplierGroups, function ($a, $b) {
  4590. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  4591. return ($a['is_void'] ?? false) ? 1 : -1;
  4592. }
  4593. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  4594. return ($a['is_selected'] ?? false) ? -1 : 1;
  4595. }
  4596. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  4597. });
  4598. return [
  4599. 'process_rows' => $processRows,
  4600. 'supplier_groups' => $supplierGroups,
  4601. 'order_total_text' => '',
  4602. 'order_total_has' => false,
  4603. 'selected_company' => $selectedCompany,
  4604. ];
  4605. }
  4606. /**
  4607. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  4608. */
  4609. protected function buildProcessLinesPlain(array $mergeRows): string
  4610. {
  4611. $lines = [];
  4612. $i = 1;
  4613. foreach ($mergeRows as $r) {
  4614. if (!is_array($r)) {
  4615. continue;
  4616. }
  4617. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4618. $dw = trim((string)($r['CDW'] ?? ''));
  4619. $gzl = trim((string)($r['NGZL'] ?? ''));
  4620. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4621. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  4622. if ($dw !== '') {
  4623. $parts[] = '单位:' . $dw;
  4624. }
  4625. if ($gzl !== '') {
  4626. $parts[] = '工作量:' . $gzl;
  4627. }
  4628. if ($qty !== '') {
  4629. $parts[] = '本次数量:' . $qty;
  4630. }
  4631. $lines[] = implode(' ', $parts);
  4632. $i++;
  4633. }
  4634. return implode("\n", $lines);
  4635. }
  4636. /**
  4637. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  4638. *
  4639. * @return array<string, string>
  4640. */
  4641. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  4642. {
  4643. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  4644. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  4645. }
  4646. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  4647. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  4648. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  4649. $cyjmc = '';
  4650. foreach ($mergeRows as $mr) {
  4651. if (!is_array($mr)) {
  4652. continue;
  4653. }
  4654. if ($ccydh === '') {
  4655. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  4656. }
  4657. if ($cyjmc === '') {
  4658. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  4659. }
  4660. }
  4661. if ($pos !== []) {
  4662. $firstPo = $pos[0];
  4663. if (is_array($firstPo)) {
  4664. if ($ccydh === '') {
  4665. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  4666. }
  4667. if ($cyjmc === '') {
  4668. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  4669. }
  4670. }
  4671. }
  4672. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  4673. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  4674. if (is_array($any)) {
  4675. if ($ccydh === '') {
  4676. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  4677. }
  4678. if ($cyjmc === '') {
  4679. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  4680. }
  4681. }
  4682. }
  4683. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  4684. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  4685. $cgymc = '';
  4686. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  4687. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  4688. }
  4689. return [
  4690. 'ccydh' => $ccydh,
  4691. 'cyjmc' => $cyjmc,
  4692. 'cgymc' => $cgymc,
  4693. 'process_lines' => $processLines,
  4694. 'process_lines_html' => '',
  4695. ];
  4696. }
  4697. /**
  4698. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  4699. */
  4700. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  4701. {
  4702. $lines = [];
  4703. if ($ccydh !== '') {
  4704. $lines[] = '订单号:' . $ccydh;
  4705. }
  4706. if ($cyjmc !== '') {
  4707. $lines[] = '印件名称:' . $cyjmc;
  4708. }
  4709. if ($processPlain !== '') {
  4710. $lines[] = $processPlain;
  4711. }
  4712. return implode("\n", $lines);
  4713. }
  4714. /**
  4715. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  4716. *
  4717. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4718. */
  4719. protected function buildPlatformLinksPlain(array $detailLinks): string
  4720. {
  4721. $lines = [];
  4722. $i = 1;
  4723. foreach ($detailLinks as $lk) {
  4724. if (!is_array($lk)) {
  4725. continue;
  4726. }
  4727. $url = trim((string)($lk['url'] ?? ''));
  4728. if ($url === '') {
  4729. continue;
  4730. }
  4731. $label = trim((string)($lk['cgymc'] ?? ''));
  4732. if ($label === '') {
  4733. $label = '工序' . $i;
  4734. }
  4735. $lines[] = $label . ':' . $url;
  4736. $i++;
  4737. }
  4738. return implode("\n", $lines);
  4739. }
  4740. /**
  4741. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  4742. *
  4743. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4744. */
  4745. protected function buildPlatformLinksHtml(array $detailLinks): string
  4746. {
  4747. $parts = [];
  4748. $i = 1;
  4749. foreach ($detailLinks as $lk) {
  4750. if (!is_array($lk)) {
  4751. continue;
  4752. }
  4753. $url = trim((string)($lk['url'] ?? ''));
  4754. if ($url === '') {
  4755. continue;
  4756. }
  4757. $label = trim((string)($lk['cgymc'] ?? ''));
  4758. if ($label === '') {
  4759. $label = '工序' . $i;
  4760. }
  4761. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  4762. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  4763. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  4764. $i++;
  4765. }
  4766. return implode("<br>\n", $parts);
  4767. }
  4768. /**
  4769. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  4770. *
  4771. * @return array<string, mixed>
  4772. */
  4773. protected function loadMailerConfig(): array
  4774. {
  4775. try {
  4776. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  4777. } catch (\Throwable $e) {
  4778. $cfg = [];
  4779. }
  4780. return is_array($cfg) ? $cfg : [];
  4781. }
  4782. protected function loadNotifyTemplateRow(string $scene): ?array
  4783. {
  4784. try {
  4785. $row = Db::table('purchase_sms_template')
  4786. ->where('scene', $scene)
  4787. ->where(function ($q) {
  4788. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  4789. })
  4790. ->order('id', 'asc')
  4791. ->find();
  4792. } catch (\Throwable $e) {
  4793. return null;
  4794. }
  4795. if (!is_array($row) || $row === []) {
  4796. return null;
  4797. }
  4798. return [
  4799. 'title' => trim((string)($row['title'] ?? '')),
  4800. 'content' => trim((string)($row['content'] ?? '')),
  4801. ];
  4802. }
  4803. /**
  4804. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  4805. */
  4806. protected function buildProcessLinesHtml(array $mergeRows): string
  4807. {
  4808. if (count($mergeRows) <= 1) {
  4809. $r = $mergeRows[0] ?? [];
  4810. if (!is_array($r)) {
  4811. return '';
  4812. }
  4813. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4814. $dw = trim((string)($r['CDW'] ?? ''));
  4815. $gzl = trim((string)($r['NGZL'] ?? ''));
  4816. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4817. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  4818. if ($dw !== '') {
  4819. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  4820. }
  4821. if ($gzl !== '') {
  4822. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  4823. }
  4824. if ($qty !== '') {
  4825. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  4826. }
  4827. return $html;
  4828. }
  4829. $rows = '';
  4830. $i = 1;
  4831. foreach ($mergeRows as $r) {
  4832. if (!is_array($r)) {
  4833. continue;
  4834. }
  4835. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  4836. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  4837. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  4838. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  4839. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  4840. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  4841. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  4842. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  4843. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  4844. $i++;
  4845. }
  4846. if ($rows === '') {
  4847. return '';
  4848. }
  4849. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  4850. . '<thead><tr style="background:#f5f5f5;">'
  4851. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  4852. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  4853. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  4854. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  4855. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  4856. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  4857. }
  4858. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  4859. {
  4860. $sysRq = trim($sysRq);
  4861. if ($sysRq === '') {
  4862. if ($required) {
  4863. $this->error('请选择截止时间');
  4864. }
  4865. return '';
  4866. }
  4867. $ts = strtotime($sysRq);
  4868. if ($ts === false || $ts <= 0) {
  4869. $this->error('截止时间格式无效');
  4870. }
  4871. return date('Y-m-d H:i:s', $ts);
  4872. }
  4873. protected function formatProcuremenSysRqForInput($sysRq): string
  4874. {
  4875. $sr = trim((string)$sysRq);
  4876. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  4877. return '';
  4878. }
  4879. $ts = strtotime($sr);
  4880. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  4881. }
  4882. protected function formatProcuremenSysRqForDisplay($sysRq): string
  4883. {
  4884. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  4885. if ($sr === '') {
  4886. return '—';
  4887. }
  4888. $ts = strtotime($sr);
  4889. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  4890. }
  4891. /**
  4892. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  4893. * @return array{ccydh?:string,pos:array,merge_rows:array}
  4894. */
  4895. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  4896. {
  4897. $sysRqPost = trim($sysRqPost);
  4898. if ($sysRqPost === '') {
  4899. return $bundle;
  4900. }
  4901. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqPost, true);
  4902. $pos = $bundle['pos'] ?? [];
  4903. foreach ($pos as $poRow) {
  4904. if (!is_array($poRow)) {
  4905. continue;
  4906. }
  4907. $sid = (int)($poRow['scydgy_id'] ?? 0);
  4908. if (!$this->isValidScydgyRowId($sid)) {
  4909. continue;
  4910. }
  4911. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['sys_rq' => $sysRqDb]);
  4912. }
  4913. foreach ($pos as $i => $poRow) {
  4914. if (is_array($pos[$i])) {
  4915. $pos[$i]['sys_rq'] = $sysRqDb;
  4916. }
  4917. }
  4918. $bundle['pos'] = $pos;
  4919. return $bundle;
  4920. }
  4921. /**
  4922. * 写入/更新 purchase_order(单道工序行)
  4923. */
  4924. protected function upsertPurchaseOrderFromRow(
  4925. array $row,
  4926. string $sysRqDb,
  4927. $wflowStatus = null,
  4928. ?string $pickTime = null,
  4929. ?array $exists = null
  4930. ): void {
  4931. $ids = $this->extractScydgyRowId($row);
  4932. if (!$this->isValidScydgyRowId($ids)) {
  4933. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  4934. }
  4935. if ($exists === null) {
  4936. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4937. }
  4938. $data = [
  4939. 'scydgy_id' => $ids,
  4940. 'CCYDH' => $row['CCYDH'] ?? null,
  4941. 'CYJMC' => $row['CYJMC'] ?? null,
  4942. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4943. 'CDXMC' => $row['CDXMC'] ?? null,
  4944. 'CGYBH' => $row['CGYBH'] ?? null,
  4945. 'CGYMC' => $row['CGYMC'] ?? null,
  4946. 'CDW' => $row['CDW'] ?? null,
  4947. 'NGZL' => $row['NGZL'] ?? null,
  4948. 'CDF' => $row['CDF'] ?? null,
  4949. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4950. 'MBZ' => $row['MBZ'] ?? null,
  4951. 'bwjg' => $row['bwjg'] ?? null,
  4952. 'iStatus' => $row['iStatus'] ?? null,
  4953. 'dStamp' => $row['dStamp'] ?? null,
  4954. 'dputrecord' => $row['dputrecord'] ?? null,
  4955. 'cywyxm' => $row['cywyxm'] ?? null,
  4956. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4957. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4958. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4959. 'sys_rq' => $sysRqDb,
  4960. ];
  4961. if ($wflowStatus !== null && $wflowStatus !== '') {
  4962. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  4963. }
  4964. if ($pickTime !== null && $pickTime !== '') {
  4965. $data['pick_time'] = $pickTime;
  4966. $data['pick_company_name'] = '';
  4967. }
  4968. if ($exists) {
  4969. $upd = $data;
  4970. unset($upd['scydgy_id']);
  4971. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4972. } else {
  4973. $data['createtime'] = date('Y-m-d H:i:s');
  4974. Db::table('purchase_order')->insert($data);
  4975. }
  4976. }
  4977. /**
  4978. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  4979. *
  4980. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  4981. */
  4982. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  4983. {
  4984. $toDb = function ($value) {
  4985. if ($value === null) {
  4986. return null;
  4987. }
  4988. if (is_scalar($value)) {
  4989. return $value;
  4990. }
  4991. return json_encode($value, JSON_UNESCAPED_UNICODE);
  4992. };
  4993. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4994. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4995. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4996. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  4997. if ($username === '') {
  4998. $username = $this->resolveCustomerContactName($phone, $companyName);
  4999. }
  5000. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5001. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  5002. }
  5003. if ($phone === '') {
  5004. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  5005. }
  5006. $detailLinks = [];
  5007. foreach ($mergeRows as $row) {
  5008. if (!is_array($row)) {
  5009. continue;
  5010. }
  5011. $sid = $this->extractScydgyRowId($row);
  5012. $detailId = 0;
  5013. if ($skipExisting) {
  5014. try {
  5015. $existsQuery = Db::table('purchase_order_detail')
  5016. ->where('scydgy_id', $sid)
  5017. ->where('company_name', $companyName);
  5018. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  5019. $exists = $existsQuery->find();
  5020. } catch (\Throwable $e) {
  5021. $exists = null;
  5022. }
  5023. if (is_array($exists)) {
  5024. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  5025. }
  5026. }
  5027. if ($detailId <= 0) {
  5028. $one = [
  5029. 'scydgy_id' => $toDb($sid),
  5030. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  5031. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  5032. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  5033. 'username' => $username !== '' ? $username : null,
  5034. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  5035. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  5036. 'createtime' => date('Y-m-d H:i:s'),
  5037. 'status' => ProcuremenStatus::POD_UNPICKED,
  5038. 'status_name' => '未提交',
  5039. ];
  5040. Db::table('purchase_order_detail')->insert($one);
  5041. $detailId = (int)Db::getLastInsID();
  5042. }
  5043. $mprocUrl = '';
  5044. if ($buildMobileLinks && $detailId > 0) {
  5045. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  5046. }
  5047. $detailLinks[] = [
  5048. 'detail_id' => $detailId,
  5049. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  5050. 'url' => $mprocUrl,
  5051. ];
  5052. }
  5053. return $detailLinks;
  5054. }
  5055. /**
  5056. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  5057. * @return array<string, mixed>
  5058. */
  5059. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  5060. {
  5061. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5062. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5063. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5064. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  5065. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  5066. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  5067. $isMerge = !empty($ctx['is_merge']);
  5068. $contactName = trim((string)($c['username'] ?? ''));
  5069. if ($contactName === '') {
  5070. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  5071. }
  5072. $notifyVars = [
  5073. 'company_name' => $companyName,
  5074. 'contact_name' => $contactName,
  5075. 'phone' => $phone,
  5076. 'email' => $toEmail,
  5077. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  5078. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  5079. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  5080. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  5081. 'deadline' => (string)($ctx['deadline'] ?? ''),
  5082. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  5083. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  5084. 'platform_url' => $platformUrl,
  5085. 'platform_links' => $platformLinksPlain,
  5086. 'platform_links_html' => $platformLinksHtml,
  5087. ];
  5088. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  5089. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  5090. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5091. return [
  5092. 'company_name' => $companyName,
  5093. 'phone' => $phone,
  5094. 'email' => $toEmail,
  5095. 'sms_content' => $smsContent,
  5096. 'mail_plain' => $mailPlain,
  5097. 'mail_body' => $mailBody,
  5098. 'notify_vars' => $notifyVars,
  5099. 'detail_links' => $detailLinks,
  5100. ];
  5101. }
  5102. /**
  5103. * @param array<string, mixed> $chosen
  5104. * @param array<int, array<string, mixed>> $mergeRows
  5105. * @param array{ccydh:string, pos:array} $bundle
  5106. */
  5107. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail): void
  5108. {
  5109. if (!$sendSms && !$sendEmail) {
  5110. return;
  5111. }
  5112. $companyName = trim((string)($chosen['name'] ?? ''));
  5113. $phone = trim((string)($chosen['phone'] ?? ''));
  5114. $toEmail = trim((string)($chosen['email'] ?? ''));
  5115. if ($companyName === '') {
  5116. throw new \Exception('供应商名称无效');
  5117. }
  5118. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  5119. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  5120. }
  5121. if ($sendSms && $phone === '') {
  5122. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  5123. }
  5124. $sids = [];
  5125. foreach ($mergeRows as $mr) {
  5126. if (!is_array($mr)) {
  5127. continue;
  5128. }
  5129. $sid = $this->extractScydgyRowId($mr);
  5130. if ($this->isValidScydgyRowId($sid)) {
  5131. $sids[$sid] = true;
  5132. }
  5133. }
  5134. if ($sids === []) {
  5135. throw new \Exception('未找到工序行,无法发送通知');
  5136. }
  5137. $sysRqNotify = '';
  5138. $pos = $bundle['pos'] ?? [];
  5139. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5140. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  5141. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  5142. $ts = strtotime($sr);
  5143. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  5144. }
  5145. }
  5146. try {
  5147. $detailsQuery = Db::table('purchase_order_detail')
  5148. ->where('scydgy_id', 'in', array_keys($sids))
  5149. ->where('company_name', $companyName);
  5150. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5151. $details = $detailsQuery->order('id', 'asc')->select();
  5152. } catch (\Throwable $e) {
  5153. $details = [];
  5154. }
  5155. if (!is_array($details) || $details === []) {
  5156. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  5157. try {
  5158. $detailsQuery = Db::table('purchase_order_detail')
  5159. ->where('scydgy_id', 'in', array_keys($sids))
  5160. ->where('company_name', $companyName);
  5161. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5162. $details = $detailsQuery->order('id', 'asc')->select();
  5163. } catch (\Throwable $e) {
  5164. $details = [];
  5165. }
  5166. }
  5167. if (!is_array($details) || $details === []) {
  5168. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  5169. }
  5170. $detailLinks = [];
  5171. foreach ($details as $d) {
  5172. if (!is_array($d)) {
  5173. continue;
  5174. }
  5175. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  5176. if ($detailId <= 0) {
  5177. continue;
  5178. }
  5179. $sid = (int)($d['scydgy_id'] ?? 0);
  5180. $gymc = '';
  5181. foreach ($mergeRows as $mr) {
  5182. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  5183. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5184. break;
  5185. }
  5186. }
  5187. $detailLinks[] = [
  5188. 'detail_id' => $detailId,
  5189. 'cgymc' => $gymc,
  5190. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  5191. ];
  5192. }
  5193. if ($detailLinks === []) {
  5194. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  5195. }
  5196. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  5197. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  5198. if ($sendEmail) {
  5199. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  5200. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  5201. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  5202. }
  5203. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  5204. $mailConfig = $this->loadMailerConfig();
  5205. if (!$this->isProcuremenNotifyDryRun()) {
  5206. if (empty($mailConfig['host'])) {
  5207. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  5208. }
  5209. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  5210. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  5211. }
  5212. }
  5213. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  5214. }
  5215. if ($sendSms) {
  5216. $this->issueSendSupplierSms($notifyBundle);
  5217. }
  5218. }
  5219. /**
  5220. * @param array<int, array<string, mixed>> $quoteGroups
  5221. * @return array<int, array<string, mixed>>
  5222. */
  5223. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  5224. {
  5225. $names = [];
  5226. if (is_string($companiesJson) && $companiesJson !== '') {
  5227. $decoded = json_decode($companiesJson, true);
  5228. if (is_array($decoded)) {
  5229. foreach ($decoded as $nm) {
  5230. $nm = trim((string)$nm);
  5231. if ($nm !== '') {
  5232. $names[] = $nm;
  5233. }
  5234. }
  5235. }
  5236. }
  5237. $names = array_values(array_unique($names));
  5238. if ($names === [] && $selectedCompany !== '') {
  5239. $names = [$selectedCompany];
  5240. }
  5241. if ($names === []) {
  5242. return $quoteGroups;
  5243. }
  5244. $targets = [];
  5245. foreach ($quoteGroups as $g) {
  5246. if (!is_array($g)) {
  5247. continue;
  5248. }
  5249. $cn = trim((string)($g['name'] ?? ''));
  5250. if ($cn !== '' && in_array($cn, $names, true)) {
  5251. $targets[] = $g;
  5252. }
  5253. }
  5254. return $targets;
  5255. }
  5256. /**
  5257. * @return array{pos:array, merge_rows:array, bundle:array}
  5258. */
  5259. protected function loadAuditResendBundle(string $scydgyId): array
  5260. {
  5261. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5262. $pos = $bundle['pos'];
  5263. $mergeRows = $bundle['merge_rows'];
  5264. if ($pos === [] || $mergeRows === []) {
  5265. $this->error('该订单不在待确认供应商状态');
  5266. }
  5267. $sysRqDb = '';
  5268. if (isset($pos[0]) && is_array($pos[0])) {
  5269. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  5270. }
  5271. foreach ($pos as $i => $poRow) {
  5272. if (is_array($pos[$i]) && $sysRqDb !== '') {
  5273. $pos[$i]['sys_rq'] = $sysRqDb;
  5274. }
  5275. }
  5276. $bundle['pos'] = $pos;
  5277. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  5278. }
  5279. /**
  5280. * @param array<int, array<string, mixed>> $targets
  5281. */
  5282. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  5283. {
  5284. if ($targets === []) {
  5285. $this->error('未找到可通知的供应商');
  5286. }
  5287. $notifyErrors = [];
  5288. try {
  5289. $this->notifyDryRunPreview = [];
  5290. foreach ($targets as $g) {
  5291. if (!is_array($g)) {
  5292. continue;
  5293. }
  5294. $cname = trim((string)($g['name'] ?? ''));
  5295. if ($cname === '') {
  5296. continue;
  5297. }
  5298. $chosen = [
  5299. 'name' => $cname,
  5300. 'company_name' => $cname,
  5301. 'email' => trim((string)($g['email'] ?? '')),
  5302. 'phone' => trim((string)($g['phone'] ?? '')),
  5303. 'username' => trim((string)($g['username'] ?? '')),
  5304. ];
  5305. try {
  5306. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail);
  5307. } catch (\Throwable $e) {
  5308. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5309. }
  5310. }
  5311. } catch (\Throwable $e) {
  5312. $this->error('通知发送失败:' . $e->getMessage());
  5313. }
  5314. if ($notifyErrors !== []) {
  5315. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5316. }
  5317. if ($this->isProcuremenNotifyDryRun()) {
  5318. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  5319. 'notify_dry_run' => true,
  5320. 'notify_preview' => $this->notifyDryRunPreview,
  5321. ]);
  5322. }
  5323. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  5324. }
  5325. /**
  5326. * 协助下发 — 发送短信(一家供应商)
  5327. *
  5328. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  5329. */
  5330. protected function issueSendSupplierSms(array $bundle): void
  5331. {
  5332. $companyName = (string)($bundle['company_name'] ?? '');
  5333. $phone = (string)($bundle['phone'] ?? '');
  5334. $smsContent = (string)($bundle['sms_content'] ?? '');
  5335. $this->logIssueNotifyDebug('短信', [
  5336. 'company' => $companyName,
  5337. 'phone' => $phone,
  5338. 'sms_content' => $smsContent,
  5339. ]);
  5340. if ($this->isProcuremenNotifyDryRun()) {
  5341. $this->recordNotifyDryRunPreview([
  5342. 'scene' => 'issue_sms',
  5343. 'company_name' => $companyName,
  5344. 'phone' => $phone,
  5345. 'sms_content' => $smsContent,
  5346. ]);
  5347. return;
  5348. }
  5349. $this->smsbao($phone, $smsContent);
  5350. }
  5351. /**
  5352. * 协助下发 — 发送邮件(一家供应商)
  5353. *
  5354. * @param array<string, mixed> $bundle
  5355. * @param array<string, mixed> $mailConfig
  5356. */
  5357. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  5358. {
  5359. $companyName = (string)($bundle['company_name'] ?? '');
  5360. $toEmail = (string)($bundle['email'] ?? '');
  5361. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  5362. $mailBody = (string)($bundle['mail_body'] ?? '');
  5363. $this->logIssueNotifyDebug('邮件', [
  5364. 'company' => $companyName,
  5365. 'email' => $toEmail,
  5366. 'mail_subject' => $mailSubject,
  5367. 'mail_body' => $mailPlain,
  5368. ]);
  5369. if ($this->isProcuremenNotifyDryRun()) {
  5370. $this->recordNotifyDryRunPreview([
  5371. 'scene' => 'issue_email',
  5372. 'company_name' => $companyName,
  5373. 'email' => $toEmail,
  5374. 'mail_subject' => $mailSubject,
  5375. 'mail_body' => $mailPlain,
  5376. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  5377. 'notify_vars' => $bundle['notify_vars'] ?? [],
  5378. 'detail_links' => $bundle['detail_links'] ?? [],
  5379. ]);
  5380. return;
  5381. }
  5382. $mail = new PHPMailer(true);
  5383. $mail->isSMTP();
  5384. $mail->Host = $mailConfig['host'];
  5385. $mail->SMTPAuth = true;
  5386. $mail->Username = $mailConfig['addr'];
  5387. $mail->Password = $mailConfig['pass'];
  5388. $mail->SMTPSecure = $mailConfig['security'];
  5389. $mail->Port = $mailConfig['port'];
  5390. $mail->CharSet = $mailConfig['charset'];
  5391. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  5392. $mail->addAddress($toEmail, $companyName);
  5393. $mail->isHTML(true);
  5394. $mail->Subject = $mailSubject;
  5395. $mail->Body = $mailBody;
  5396. $mail->send();
  5397. }
  5398. /**
  5399. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  5400. *
  5401. * @param array<int, array<string, mixed>> $mergeRows
  5402. * @return array<string, mixed>
  5403. */
  5404. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  5405. {
  5406. $head = $mergeRows[0] ?? [];
  5407. $isMerge = count($mergeRows) > 1;
  5408. return [
  5409. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  5410. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  5411. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  5412. 'is_merge' => $isMerge,
  5413. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  5414. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  5415. 'deadline' => $sysRqNotify,
  5416. ];
  5417. }
  5418. /**
  5419. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  5420. *
  5421. * @param array<string, mixed> $data
  5422. */
  5423. protected function logIssueNotifyDebug(string $type, array $data): void
  5424. {
  5425. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  5426. return;
  5427. }
  5428. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  5429. }
  5430. /**
  5431. * 协助下发弹窗(选多家供应商并通知)
  5432. */
  5433. public function pickReview()
  5434. {
  5435. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  5436. $this->error(__('You have no permission'));
  5437. }
  5438. if ($this->request->isPost()) {
  5439. $this->error('请使用弹窗内「确认下发」提交');
  5440. }
  5441. $this->view->assign('pickMode', 1);
  5442. return $this->view->fetch('procuremen/review');
  5443. }
  5444. /**
  5445. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  5446. */
  5447. public function add()
  5448. {
  5449. if ($this->request->isPost()) {
  5450. $params = $this->request->post('row/a');
  5451. if (!is_array($params)) {
  5452. $this->error(__('Parameter %s can not be empty', ''));
  5453. }
  5454. [, $adminName] = $this->GetUseName();
  5455. $params['cywyxm'] = $adminName;
  5456. try {
  5457. $sid = $this->saveManualPickOrder($params);
  5458. } catch (\InvalidArgumentException $e) {
  5459. $this->error($e->getMessage());
  5460. } catch (\Throwable $e) {
  5461. $this->error($e->getMessage());
  5462. }
  5463. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5464. }
  5465. [, $adminName] = $this->GetUseName();
  5466. $this->view->assign('adminNickname', $adminName);
  5467. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  5468. return $this->view->fetch();
  5469. }
  5470. /**
  5471. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  5472. */
  5473. public function rfqlist()
  5474. {
  5475. $this->relationSearch = false;
  5476. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  5477. $this->request->filter(['strip_tags', 'trim']);
  5478. if ($this->request->isAjax()) {
  5479. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  5480. $limit = max(10, min(500, (int)$limit));
  5481. $applyFilters = function ($query) use ($where) {
  5482. $query->where('scydgy_id', '<', 0);
  5483. $query->whereRaw(
  5484. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  5485. );
  5486. if (!$this->auth->isSuperAdmin()) {
  5487. [, $adminName] = $this->GetUseName();
  5488. $query->where('cywyxm', $adminName);
  5489. }
  5490. if (!empty($where)) {
  5491. $query->where($where);
  5492. }
  5493. };
  5494. $countQuery = Db::table('purchase_order');
  5495. $applyFilters($countQuery);
  5496. $total = (int)$countQuery->count();
  5497. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  5498. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  5499. $listQuery = Db::table('purchase_order');
  5500. $applyFilters($listQuery);
  5501. $rows = $listQuery
  5502. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  5503. ->order($sortField, $orderDir)
  5504. ->limit($offset, $limit)
  5505. ->select();
  5506. if (!is_array($rows)) {
  5507. $rows = [];
  5508. }
  5509. $out = [];
  5510. foreach ($rows as $r) {
  5511. if (!is_array($r)) {
  5512. continue;
  5513. }
  5514. $sid = (int)($r['scydgy_id'] ?? 0);
  5515. if ($sid >= 0) {
  5516. continue;
  5517. }
  5518. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  5519. if ($createdText === '') {
  5520. $createdText = trim((string)($r['dStamp'] ?? ''));
  5521. }
  5522. $out[] = [
  5523. 'id' => (int)($r['id'] ?? 0),
  5524. 'scydgy_id' => $sid,
  5525. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5526. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5527. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  5528. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5529. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  5530. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  5531. 'createtime' => $r['createtime'] ?? null,
  5532. 'createtime_text' => $createdText,
  5533. ];
  5534. }
  5535. return json(['total' => $total, 'rows' => $out]);
  5536. }
  5537. [, $adminName] = $this->GetUseName();
  5538. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  5539. $this->view->assign('adminNickname', $adminName);
  5540. return $this->view->fetch('procuremen/rfqlist');
  5541. }
  5542. /**
  5543. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  5544. */
  5545. public function rfqlistDetails()
  5546. {
  5547. return $this->details();
  5548. }
  5549. /**
  5550. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  5551. */
  5552. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  5553. {
  5554. if ($scydgyId >= 0) {
  5555. return;
  5556. }
  5557. try {
  5558. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5559. } catch (\Throwable $e) {
  5560. $po = null;
  5561. }
  5562. if (!is_array($po)) {
  5563. $this->error('订单不存在');
  5564. }
  5565. $modRq = trim((string)($po['mod_rq'] ?? ''));
  5566. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  5567. $this->error('订单不存在');
  5568. }
  5569. if ($this->auth->isSuperAdmin()) {
  5570. return;
  5571. }
  5572. [, $adminName] = $this->GetUseName();
  5573. $cywy = trim((string)($po['cywyxm'] ?? ''));
  5574. if ($cywy !== '' && $cywy === $adminName) {
  5575. return;
  5576. }
  5577. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  5578. try {
  5579. if ($this->auth->check($rule)) {
  5580. return;
  5581. }
  5582. } catch (\Throwable $e) {
  5583. }
  5584. }
  5585. $this->error('无权查看该订单');
  5586. }
  5587. /**
  5588. * 手工新增协助工序进度文案
  5589. */
  5590. protected function formatProcuremenRfqProgressText(array $row): string
  5591. {
  5592. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  5593. return ProcuremenStatus::PO_COMPLETED;
  5594. }
  5595. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  5596. return '待采购确认';
  5597. }
  5598. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  5599. return '待确认供应商';
  5600. }
  5601. $sid = (int)($row['scydgy_id'] ?? 0);
  5602. if ($sid < 0) {
  5603. try {
  5604. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  5605. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  5606. $detCnt = (int)$detCntQuery->count();
  5607. if ($detCnt > 0) {
  5608. return '已下发待确认';
  5609. }
  5610. } catch (\Throwable $e) {
  5611. }
  5612. }
  5613. return '待协助下发';
  5614. }
  5615. /**
  5616. * 协助初选列表 — 批量软删除
  5617. */
  5618. public function pickDelete()
  5619. {
  5620. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5621. $this->error(__('Invalid parameters'));
  5622. }
  5623. if (!$this->procuremenCanPickDelete()) {
  5624. $this->error(__('You have no permission'));
  5625. }
  5626. $rowsRaw = $this->request->post('rows_json', '[]');
  5627. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  5628. if (!is_array($rows) || $rows === []) {
  5629. $this->error('请至少勾选一条工序');
  5630. }
  5631. $done = 0;
  5632. Db::startTrans();
  5633. try {
  5634. foreach ($rows as $row) {
  5635. if (!is_array($row)) {
  5636. continue;
  5637. }
  5638. $this->softDeleteProcuremenPickRow($row);
  5639. $done++;
  5640. }
  5641. if ($done < 1) {
  5642. throw new \Exception('没有可删除的工序');
  5643. }
  5644. Db::commit();
  5645. } catch (\InvalidArgumentException $e) {
  5646. Db::rollback();
  5647. $this->error($e->getMessage());
  5648. } catch (\Throwable $e) {
  5649. Db::rollback();
  5650. $this->error($e->getMessage());
  5651. }
  5652. $this->pickHiddenScydgySetCache = null;
  5653. $this->success('已删除 ' . $done . ' 条工序');
  5654. }
  5655. /**
  5656. * 下发 — 手工新增工序(弹窗)
  5657. */
  5658. public function pickAdd()
  5659. {
  5660. if ($this->request->isPost()) {
  5661. $params = $this->request->post('row/a');
  5662. if (!is_array($params)) {
  5663. $this->error(__('Parameter %s can not be empty', ''));
  5664. }
  5665. try {
  5666. $sid = $this->saveManualPickOrder($params);
  5667. } catch (\InvalidArgumentException $e) {
  5668. $this->error($e->getMessage());
  5669. } catch (\Throwable $e) {
  5670. $this->error($e->getMessage());
  5671. }
  5672. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5673. }
  5674. return $this->view->fetch('procuremen/pick_add');
  5675. }
  5676. /**
  5677. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  5678. */
  5679. public function pickSubmit()
  5680. {
  5681. if (!$this->request->isPost()) {
  5682. $this->error(__('Invalid parameters'));
  5683. }
  5684. // ---------- 接口订单数据 ----------
  5685. $rowJson = $this->request->post('row_json', '');
  5686. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  5687. $companiesJson = $this->request->post('companies_json', '[]');
  5688. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  5689. $companies = json_decode($companiesJson, true);
  5690. if (!is_array($companies)) {
  5691. $this->error('供应商数据无效');
  5692. }
  5693. $issueCompanies = $this->normalizePickCompanies($companies);
  5694. if ($issueCompanies === []) {
  5695. $this->error('请至少选择一家合作供应商');
  5696. }
  5697. $issueNameLabels = [];
  5698. foreach ($issueCompanies as $pc) {
  5699. $issueNameLabels[] = $pc['name'];
  5700. }
  5701. $issueNamesSummary = implode('、', $issueNameLabels);
  5702. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  5703. if ($sysRq === '') {
  5704. $this->error('请选择截止时间');
  5705. }
  5706. $sysRqTs = strtotime($sysRq);
  5707. if ($sysRqTs === false || $sysRqTs <= 0) {
  5708. $this->error('截止时间格式无效');
  5709. }
  5710. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  5711. $isMerge = count($mergeRows) > 1;
  5712. $ccydhLog = '';
  5713. foreach ($mergeRows as $row) {
  5714. if (!is_array($row)) {
  5715. continue;
  5716. }
  5717. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  5718. if ($ccydhLog !== '') {
  5719. break;
  5720. }
  5721. }
  5722. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  5723. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  5724. $logMsg = '下发' . $orderPart . $procPart
  5725. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  5726. $issueTime = date('Y-m-d H:i:s');
  5727. $logSidList = [];
  5728. foreach ($mergeRows as $row) {
  5729. if (!is_array($row)) {
  5730. continue;
  5731. }
  5732. $sid = $this->extractScydgyRowId($row);
  5733. if ($this->isValidScydgyRowId($sid)) {
  5734. $logSidList[$sid] = true;
  5735. }
  5736. }
  5737. $existingBySid = [];
  5738. if ($logSidList !== []) {
  5739. try {
  5740. $existingRows = Db::table('purchase_order')
  5741. ->where('scydgy_id', 'in', array_keys($logSidList))
  5742. ->select();
  5743. if (is_array($existingRows)) {
  5744. foreach ($existingRows as $poRow) {
  5745. if (!is_array($poRow)) {
  5746. continue;
  5747. }
  5748. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5749. if ($this->isValidScydgyRowId($sid)) {
  5750. $existingBySid[$sid] = $poRow;
  5751. }
  5752. }
  5753. }
  5754. } catch (\Throwable $e) {
  5755. $existingBySid = [];
  5756. }
  5757. }
  5758. Db::startTrans();
  5759. try {
  5760. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  5761. foreach ($mergeRows as $row) {
  5762. if (!is_array($row)) {
  5763. continue;
  5764. }
  5765. $sid = $this->extractScydgyRowId($row);
  5766. $this->upsertPurchaseOrderFromRow(
  5767. $row,
  5768. $sysRqDb,
  5769. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  5770. $issueTime,
  5771. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  5772. );
  5773. }
  5774. foreach ($issueCompanies as $c) {
  5775. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  5776. }
  5777. Db::commit();
  5778. } catch (\Throwable $e) {
  5779. Db::rollback();
  5780. $this->error($e->getMessage());
  5781. }
  5782. $poIdBySid = [];
  5783. if ($logSidList !== []) {
  5784. try {
  5785. $poIdBySid = Db::table('purchase_order')
  5786. ->where('scydgy_id', 'in', array_keys($logSidList))
  5787. ->column('id', 'scydgy_id');
  5788. } catch (\Throwable $e) {
  5789. $poIdBySid = [];
  5790. }
  5791. }
  5792. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  5793. if ($logSidList !== []) {
  5794. list($adminId, $adminName) = $this->GetUseName();
  5795. $cut = function ($s, $max) {
  5796. if (function_exists('mb_substr')) {
  5797. return mb_substr($s, 0, $max, 'UTF-8');
  5798. }
  5799. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  5800. };
  5801. $logRows = [];
  5802. $seenLogSid = [];
  5803. foreach ($mergeRows as $row) {
  5804. if (!is_array($row)) {
  5805. continue;
  5806. }
  5807. $ids = $this->extractScydgyRowId($row);
  5808. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  5809. continue;
  5810. }
  5811. $seenLogSid[$ids] = true;
  5812. $poIdLog = null;
  5813. if (isset($poIdBySid[$ids])) {
  5814. $tid = (int)$poIdBySid[$ids];
  5815. $poIdLog = $tid > 0 ? $tid : null;
  5816. }
  5817. $logRows[] = [
  5818. 'scydgy_id' => $ids,
  5819. 'purchase_order_id' => $poIdLog,
  5820. 'admin_id' => $adminId,
  5821. 'admin_name' => $cut($adminName, 64),
  5822. 'action' => $cut('issue_submit', 64),
  5823. 'content' => $cut($logMsg, 1000),
  5824. 'createtime' => ProcuremenTime::nowDateTime(),
  5825. ];
  5826. }
  5827. if ($logRows !== []) {
  5828. try {
  5829. Db::table('purchase_order_oper_log')->insertAll($logRows);
  5830. } catch (\Throwable $e) {
  5831. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  5832. }
  5833. }
  5834. }
  5835. $notifyErrors = [];
  5836. $posNotify = [];
  5837. if ($logSidList !== []) {
  5838. try {
  5839. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  5840. } catch (\Throwable $e) {
  5841. $posNotify = [];
  5842. }
  5843. }
  5844. if (!is_array($posNotify)) {
  5845. $posNotify = [];
  5846. }
  5847. foreach ($posNotify as $i => $prow) {
  5848. if (is_array($posNotify[$i])) {
  5849. $posNotify[$i]['sys_rq'] = $sysRqDb;
  5850. }
  5851. }
  5852. $ccydhPick = '';
  5853. foreach ($mergeRows as $row) {
  5854. if (!is_array($row)) {
  5855. continue;
  5856. }
  5857. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  5858. if ($ccydhPick !== '') {
  5859. break;
  5860. }
  5861. }
  5862. $notifyBundleBase = [
  5863. 'ccydh' => $ccydhPick,
  5864. 'pos' => $posNotify,
  5865. 'merge_rows' => $mergeRows,
  5866. ];
  5867. try {
  5868. $this->notifyDryRunPreview = [];
  5869. foreach ($issueCompanies as $c) {
  5870. if (!is_array($c)) {
  5871. continue;
  5872. }
  5873. $cname = trim((string)($c['name'] ?? ''));
  5874. if ($cname === '') {
  5875. continue;
  5876. }
  5877. try {
  5878. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  5879. } catch (\Throwable $e) {
  5880. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5881. }
  5882. }
  5883. } catch (\Throwable $e) {
  5884. $this->error('通知发送失败:' . $e->getMessage());
  5885. }
  5886. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  5887. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5888. }
  5889. if ($this->isProcuremenNotifyDryRun()) {
  5890. $this->success('【演练模式】已保存并生成通知预览', '', [
  5891. 'notify_dry_run' => true,
  5892. 'notify_preview' => $this->notifyDryRunPreview,
  5893. ]);
  5894. }
  5895. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  5896. }
  5897. /**
  5898. * 确认供应商弹窗
  5899. */
  5900. public function auditIssue()
  5901. {
  5902. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5903. if (is_array($ids)) {
  5904. $ids = isset($ids[0]) ? $ids[0] : '';
  5905. }
  5906. $ids = trim((string)$ids);
  5907. if ($ids === '') {
  5908. $this->error(__('Invalid parameters'));
  5909. }
  5910. if ($this->request->isPost()) {
  5911. $this->error('请使用弹窗内「确认」提交');
  5912. }
  5913. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  5914. $pos = $bundle['pos'];
  5915. if ($pos === []) {
  5916. $this->error('该订单不在待确认供应商状态');
  5917. }
  5918. $po = $pos[0];
  5919. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5920. if ($quoteGroups === []) {
  5921. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  5922. }
  5923. $pickedName = '';
  5924. foreach ($pos as $poRow) {
  5925. if (!is_array($poRow)) {
  5926. continue;
  5927. }
  5928. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  5929. if ($pn !== '') {
  5930. $pickedName = $pn;
  5931. break;
  5932. }
  5933. }
  5934. $this->view->assign('po', $po);
  5935. $this->view->assign('scydgyId', $ids);
  5936. $this->view->assign('orderCcydh', $bundle['ccydh']);
  5937. $mergeRows = $bundle['merge_rows'];
  5938. $this->view->assign('processRows', $mergeRows);
  5939. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  5940. $this->view->assign('processCount', count($mergeRows));
  5941. $this->view->assign('quoteGroups', $quoteGroups);
  5942. $this->view->assign('quoteGroupsJson', json_encode($quoteGroups, JSON_UNESCAPED_UNICODE));
  5943. $this->view->assign('pickedCompanyName', $pickedName);
  5944. $this->view->assign('sysRq', $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null));
  5945. $this->view->assign('quoteDeadlineReached', $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0);
  5946. return $this->view->fetch('procuremen/audit_issue');
  5947. }
  5948. /**
  5949. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  5950. */
  5951. public function auditSubmit()
  5952. {
  5953. if (!$this->request->isPost()) {
  5954. $this->error(__('Invalid parameters'));
  5955. }
  5956. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5957. if ($scydgyId === '') {
  5958. $this->error('参数无效');
  5959. }
  5960. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5961. $pos = $bundle['pos'];
  5962. $mergeRows = $bundle['merge_rows'];
  5963. if ($pos === [] || $mergeRows === []) {
  5964. $this->error('该订单不在待确认供应商状态');
  5965. }
  5966. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5967. if ($quoteGroups === []) {
  5968. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  5969. }
  5970. $companyName = trim((string)$this->request->post('selected_company', ''));
  5971. if ($companyName === '') {
  5972. $this->error('请选择一家供应商');
  5973. }
  5974. $matched = null;
  5975. foreach ($quoteGroups as $g) {
  5976. if (!is_array($g)) {
  5977. continue;
  5978. }
  5979. if (trim((string)($g['name'] ?? '')) === $companyName) {
  5980. $matched = $g;
  5981. break;
  5982. }
  5983. }
  5984. if ($matched === null) {
  5985. $this->error('所选供应商不在本单报价列表中');
  5986. }
  5987. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  5988. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  5989. $this->error('报价截止时间未到,暂不能确认供应商');
  5990. }
  5991. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5992. $procCnt = count($mergeRows);
  5993. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  5994. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  5995. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  5996. Db::startTrans();
  5997. try {
  5998. foreach ($pos as $poRow) {
  5999. if (!is_array($poRow)) {
  6000. continue;
  6001. }
  6002. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6003. if (!$this->isValidScydgyRowId($sid)) {
  6004. continue;
  6005. }
  6006. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  6007. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  6008. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6009. 'pick_company_name' => $companyName,
  6010. 'sys_rq' => $sysRqDb,
  6011. ]);
  6012. }
  6013. Db::commit();
  6014. } catch (\Throwable $e) {
  6015. Db::rollback();
  6016. $this->error($e->getMessage());
  6017. }
  6018. foreach ($pos as $poRow) {
  6019. if (!is_array($poRow)) {
  6020. continue;
  6021. }
  6022. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6023. if (!$this->isValidScydgyRowId($sid)) {
  6024. continue;
  6025. }
  6026. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6027. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6028. }
  6029. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  6030. }
  6031. /**
  6032. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  6033. */
  6034. public function auditResendSms()
  6035. {
  6036. if (!$this->request->isPost()) {
  6037. $this->error(__('Invalid parameters'));
  6038. }
  6039. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6040. if ($scydgyId === '') {
  6041. $this->error('参数无效');
  6042. }
  6043. $loaded = $this->loadAuditResendBundle($scydgyId);
  6044. $mergeRows = $loaded['merge_rows'];
  6045. $bundle = $loaded['bundle'];
  6046. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  6047. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6048. if ($quoteGroups === []) {
  6049. $this->error('暂无可通知的供应商');
  6050. }
  6051. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  6052. $companiesJson = (string)$this->request->post('companies_json', '');
  6053. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  6054. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  6055. }
  6056. /**
  6057. * 确认供应商 — 二次发送邮件(可选单家/批量)
  6058. */
  6059. public function auditResendEmail()
  6060. {
  6061. if (!$this->request->isPost()) {
  6062. $this->error(__('Invalid parameters'));
  6063. }
  6064. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6065. if ($scydgyId === '') {
  6066. $this->error('参数无效');
  6067. }
  6068. $loaded = $this->loadAuditResendBundle($scydgyId);
  6069. $mergeRows = $loaded['merge_rows'];
  6070. $bundle = $loaded['bundle'];
  6071. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  6072. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6073. if ($quoteGroups === []) {
  6074. $this->error('暂无可通知的供应商');
  6075. }
  6076. $companiesJson = (string)$this->request->post('companies_json', '');
  6077. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  6078. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  6079. if ($companiesJson === '' && $selectedCompany === '') {
  6080. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  6081. }
  6082. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  6083. }
  6084. /**
  6085. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  6086. *
  6087. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  6088. * @return array<int, true> 已处理的 scydgy_id 集合
  6089. */
  6090. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  6091. {
  6092. $pos = $bundle['pos'] ?? [];
  6093. if (!is_array($pos) || $pos === []) {
  6094. return [];
  6095. }
  6096. $sids = [];
  6097. foreach ($pos as $poRow) {
  6098. if (!is_array($poRow)) {
  6099. continue;
  6100. }
  6101. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6102. if ($this->isValidScydgyRowId($sid)) {
  6103. $sids[$sid] = true;
  6104. }
  6105. }
  6106. if ($sids === []) {
  6107. return [];
  6108. }
  6109. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  6110. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  6111. $suffix = trim((string)$logSuffix, ',, ');
  6112. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  6113. $logMsg .= ':从历史存证退回协助初选';
  6114. } else {
  6115. $logMsg .= ':退回协助初选';
  6116. }
  6117. Db::table('purchase_order')
  6118. ->where('scydgy_id', 'in', array_keys($sids))
  6119. ->update([
  6120. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  6121. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6122. 'pick_company_name' => '',
  6123. 'pick_time' => null,
  6124. 'sys_rq' => null,
  6125. 'mod_rq' => null,
  6126. ]);
  6127. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  6128. foreach (array_keys($sids) as $sid) {
  6129. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  6130. }
  6131. return $sids;
  6132. }
  6133. /**
  6134. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  6135. *
  6136. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6137. */
  6138. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  6139. {
  6140. $scydgyId = trim($scydgyId);
  6141. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6142. if ($scydgyId === '') {
  6143. return $empty;
  6144. }
  6145. try {
  6146. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6147. } catch (\Throwable $e) {
  6148. $anchor = null;
  6149. }
  6150. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  6151. return $empty;
  6152. }
  6153. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6154. if ($ccydh === '') {
  6155. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6156. }
  6157. try {
  6158. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6159. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  6160. $pos = $query->order('scydgy_id', 'asc')->select();
  6161. } catch (\Throwable $e) {
  6162. $pos = [$anchor];
  6163. }
  6164. if (!is_array($pos) || $pos === []) {
  6165. $pos = [$anchor];
  6166. }
  6167. return [
  6168. 'ccydh' => $ccydh,
  6169. 'pos' => $pos,
  6170. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6171. ];
  6172. }
  6173. protected function purchaseOrderRowIsCompleted(array $po): bool
  6174. {
  6175. $st = $po['status'] ?? null;
  6176. if ($st === 1 || $st === '1') {
  6177. return true;
  6178. }
  6179. if (is_string($st) && trim($st) === '1') {
  6180. return true;
  6181. }
  6182. return is_numeric($st) && (int)$st === 1;
  6183. }
  6184. /**
  6185. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  6186. */
  6187. public function auditAbandon()
  6188. {
  6189. if (!$this->request->isPost()) {
  6190. $this->error(__('Invalid parameters'));
  6191. }
  6192. $anchorIds = [];
  6193. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  6194. if ($batchRaw !== '') {
  6195. $decoded = json_decode($batchRaw, true);
  6196. if (is_array($decoded)) {
  6197. foreach ($decoded as $id) {
  6198. $s = trim((string)$id);
  6199. if ($s !== '') {
  6200. $anchorIds[] = $s;
  6201. }
  6202. }
  6203. }
  6204. }
  6205. if ($anchorIds === []) {
  6206. $single = trim((string)$this->request->post('scydgy_id', ''));
  6207. if ($single !== '') {
  6208. $anchorIds[] = $single;
  6209. }
  6210. }
  6211. if ($anchorIds === []) {
  6212. $this->error('请至少选择一条订单');
  6213. }
  6214. $processedCcydh = [];
  6215. $doneOrders = 0;
  6216. $allSids = [];
  6217. Db::startTrans();
  6218. try {
  6219. foreach ($anchorIds as $anchorId) {
  6220. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  6221. if (($bundle['pos'] ?? []) === []) {
  6222. continue;
  6223. }
  6224. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6225. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  6226. if (isset($processedCcydh[$dedupeKey])) {
  6227. continue;
  6228. }
  6229. $processedCcydh[$dedupeKey] = true;
  6230. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  6231. if ($sids === []) {
  6232. continue;
  6233. }
  6234. $doneOrders++;
  6235. foreach (array_keys($sids) as $sid) {
  6236. $allSids[(int)$sid] = true;
  6237. }
  6238. }
  6239. if ($doneOrders < 1) {
  6240. throw new \Exception('所选订单均不在待确认供应商状态');
  6241. }
  6242. Db::commit();
  6243. } catch (\Throwable $e) {
  6244. Db::rollback();
  6245. $this->error($e->getMessage());
  6246. }
  6247. $this->pickHiddenScydgySetCache = null;
  6248. $msg = $doneOrders > 1
  6249. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  6250. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  6251. $this->success($msg);
  6252. }
  6253. /**
  6254. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  6255. */
  6256. public function archiveAbandon()
  6257. {
  6258. if (!$this->request->isPost()) {
  6259. $this->error(__('Invalid parameters'));
  6260. }
  6261. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  6262. $this->error(__('You have no permission'));
  6263. }
  6264. $anchorIds = [];
  6265. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  6266. if ($batchRaw !== '') {
  6267. $decoded = json_decode($batchRaw, true);
  6268. if (is_array($decoded)) {
  6269. foreach ($decoded as $id) {
  6270. $s = trim((string)$id);
  6271. if ($s !== '') {
  6272. $anchorIds[] = $s;
  6273. }
  6274. }
  6275. }
  6276. }
  6277. if ($anchorIds === []) {
  6278. $single = trim((string)$this->request->post('scydgy_id', ''));
  6279. if ($single !== '') {
  6280. $anchorIds[] = $single;
  6281. }
  6282. }
  6283. if ($anchorIds === []) {
  6284. $this->error('请至少选择一条订单');
  6285. }
  6286. $processedCcydh = [];
  6287. $doneOrders = 0;
  6288. Db::startTrans();
  6289. try {
  6290. foreach ($anchorIds as $anchorId) {
  6291. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  6292. if (($bundle['pos'] ?? []) === []) {
  6293. continue;
  6294. }
  6295. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6296. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  6297. if (isset($processedCcydh[$dedupeKey])) {
  6298. continue;
  6299. }
  6300. $processedCcydh[$dedupeKey] = true;
  6301. $sids = $this->abandonOrderBundleToPick(
  6302. $bundle,
  6303. 'archive_abandon',
  6304. ',从历史存证退回协助初选'
  6305. );
  6306. if ($sids === []) {
  6307. continue;
  6308. }
  6309. $doneOrders++;
  6310. }
  6311. if ($doneOrders < 1) {
  6312. throw new \Exception('所选订单均不是已完结状态');
  6313. }
  6314. Db::commit();
  6315. } catch (\Throwable $e) {
  6316. Db::rollback();
  6317. $this->error($e->getMessage());
  6318. }
  6319. $this->pickHiddenScydgySetCache = null;
  6320. $msg = $doneOrders > 1
  6321. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  6322. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  6323. $this->success($msg);
  6324. }
  6325. /**
  6326. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  6327. */
  6328. public function purchaseApprovalReject()
  6329. {
  6330. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6331. $this->error(__('Invalid parameters'));
  6332. }
  6333. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  6334. $this->error(__('You have no permission'));
  6335. }
  6336. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  6337. $decoded = json_decode($batchRaw, true);
  6338. if (!is_array($decoded) || $decoded === []) {
  6339. $this->error('提交数据无效');
  6340. }
  6341. $done = 0;
  6342. Db::startTrans();
  6343. try {
  6344. foreach ($decoded as $item) {
  6345. if (!is_array($item)) {
  6346. continue;
  6347. }
  6348. $sid = (int)($item['scydgy_id'] ?? 0);
  6349. if (!$this->isValidScydgyRowId($sid)) {
  6350. continue;
  6351. }
  6352. $this->runPurchaseApprovalRejectForSid($sid);
  6353. $done++;
  6354. }
  6355. if ($done < 1) {
  6356. throw new \Exception('所选订单均不在待审批状态');
  6357. }
  6358. Db::commit();
  6359. } catch (\Throwable $e) {
  6360. Db::rollback();
  6361. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  6362. }
  6363. $this->pickHiddenScydgySetCache = null;
  6364. $this->success('已驳回并退回「协助审批下发」');
  6365. }
  6366. /**
  6367. * @throws \Exception
  6368. */
  6369. protected function runPurchaseApprovalRejectForSid(int $sid): void
  6370. {
  6371. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  6372. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  6373. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  6374. $allIds = $this->purchaseOrderDetail($sid);
  6375. if ($allIds === []) {
  6376. throw new \Exception('未找到下发明细');
  6377. }
  6378. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  6379. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6380. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6381. 'pick_company_name' => '',
  6382. ]);
  6383. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  6384. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  6385. $poId = 0;
  6386. try {
  6387. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6388. if (is_array($po)) {
  6389. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6390. }
  6391. } catch (\Throwable $e) {
  6392. }
  6393. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  6394. }
  6395. /**
  6396. * 审核弹窗(旧入口,POST 已关闭)
  6397. */
  6398. public function review()
  6399. {
  6400. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  6401. $this->error(__('You have no permission'));
  6402. }
  6403. if ($this->request->isPost()) {
  6404. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  6405. }
  6406. $this->view->assign('pickMode', 0);
  6407. return $this->view->fetch('procuremen/review');
  6408. }
  6409. /**
  6410. * 审核弹窗获取公司列表
  6411. */
  6412. public function reviewCompanies()
  6413. {
  6414. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review'])) {
  6415. $this->error(__('You have no permission'));
  6416. }
  6417. if (!$this->request->isAjax()) {
  6418. $this->error(__('Invalid parameters'));
  6419. }
  6420. $list = [];
  6421. try {
  6422. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  6423. $rows = Db::table('customer')
  6424. ->where(function ($q) {
  6425. $q->where('status', 1)
  6426. ->whereOr('status', '1')
  6427. ->whereOr('status', '')
  6428. ->whereNull('status');
  6429. })
  6430. ->order('id', 'desc')
  6431. ->select();
  6432. } catch (\Throwable $e) {
  6433. $this->success('', '', []);
  6434. return;
  6435. }
  6436. if (!is_array($rows)) {
  6437. $this->success('', '', []);
  6438. return;
  6439. }
  6440. $detailColCandidates = [
  6441. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  6442. 'company_detail', 'company_desc', 'address',
  6443. ];
  6444. foreach ($rows as $row) {
  6445. if (!is_array($row)) {
  6446. continue;
  6447. }
  6448. $norm = [];
  6449. foreach ($row as $k => $v) {
  6450. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6451. }
  6452. $row = $norm;
  6453. $st = $row['status'] ?? '';
  6454. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6455. continue;
  6456. }
  6457. $id = isset($row['id']) ? (string)$row['id'] : '';
  6458. $companyName = '';
  6459. foreach (['company_name', 'name'] as $nk) {
  6460. if (!empty($row[$nk])) {
  6461. $companyName = trim((string)$row[$nk]);
  6462. break;
  6463. }
  6464. }
  6465. $username = '';
  6466. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6467. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6468. $username = trim((string)$row[$uk]);
  6469. break;
  6470. }
  6471. }
  6472. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6473. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6474. if ($phone === '' && isset($row['account'])) {
  6475. $phone = trim((string)$row['account']);
  6476. }
  6477. if ($phone === '' && isset($row['mobile'])) {
  6478. $phone = trim((string)$row['mobile']);
  6479. }
  6480. /* 邮箱、手机号均为空则无法发短信/邮件,不在下发弹窗展示 */
  6481. if ($email === '' && $phone === '') {
  6482. continue;
  6483. }
  6484. $category = '';
  6485. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6486. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6487. $category = trim((string)$row[$ck]);
  6488. break;
  6489. }
  6490. }
  6491. $detail = '';
  6492. foreach ($detailColCandidates as $dk) {
  6493. if (!isset($row[$dk])) {
  6494. continue;
  6495. }
  6496. $dv = trim((string)$row[$dk]);
  6497. if ($dv !== '') {
  6498. $detail = $dv;
  6499. break;
  6500. }
  6501. }
  6502. $list[] = [
  6503. 'id' => $id,
  6504. 'name' => $companyName,
  6505. 'company_name' => $companyName,
  6506. 'username' => $username,
  6507. 'email' => $email,
  6508. 'phone' => $phone,
  6509. 'category' => $category,
  6510. 'company_type' => $category,
  6511. 'detail' => $detail,
  6512. ];
  6513. }
  6514. $this->success('', '', $list);
  6515. }
  6516. /**
  6517. * 采购确认-下发明细弹窗:
  6518. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  6519. */
  6520. public function outward_detail()
  6521. {
  6522. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6523. if (is_array($ids)) {
  6524. $ids = isset($ids[0]) ? $ids[0] : '';
  6525. }
  6526. $ids = trim((string)$ids);
  6527. if ($ids === '') {
  6528. $this->error(__('Invalid parameters'));
  6529. }
  6530. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  6531. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  6532. $wffTab = 'all';
  6533. }
  6534. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  6535. $purchaseOrderId = 0;
  6536. $po = null;
  6537. try {
  6538. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6539. if (is_array($po)) {
  6540. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6541. }
  6542. } catch (\Throwable $e) {
  6543. $purchaseOrderId = 0;
  6544. $po = null;
  6545. }
  6546. if (!$isPurchaseConfirm && is_array($po)) {
  6547. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  6548. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  6549. $isPurchaseConfirm = true;
  6550. }
  6551. }
  6552. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  6553. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6554. $confirmProcessCount = 1;
  6555. $confirmPickGroups = [];
  6556. $processDisplayRows = [];
  6557. $allDetailsBySid = [];
  6558. $requiredSidList = [];
  6559. $sidList = [$ids];
  6560. if ($isPurchaseConfirm) {
  6561. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  6562. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  6563. if ($mergeRows !== []) {
  6564. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6565. }
  6566. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  6567. if ($confirmBundle['pos'] !== []) {
  6568. $sidList = [];
  6569. foreach ($confirmBundle['pos'] as $poRow) {
  6570. if (!is_array($poRow)) {
  6571. continue;
  6572. }
  6573. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6574. if (!$this->isValidScydgyRowId($sid)) {
  6575. continue;
  6576. }
  6577. $sidList[] = (string)$sid;
  6578. $requiredSidList[] = $sid;
  6579. }
  6580. }
  6581. if ($sidList === []) {
  6582. $sidList = [$ids];
  6583. $requiredSidList = [(int)$ids];
  6584. }
  6585. $confirmProcessCount = max(1, count($requiredSidList));
  6586. if (is_array($po) && $purchaseOrderId <= 0) {
  6587. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6588. }
  6589. }
  6590. $rows = [];
  6591. try {
  6592. if (count($sidList) === 1) {
  6593. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  6594. } else {
  6595. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  6596. }
  6597. } catch (\Throwable $e) {
  6598. $rows = [];
  6599. }
  6600. if ($isPurchaseConfirm) {
  6601. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  6602. }
  6603. foreach ($rows as &$r) {
  6604. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  6605. $r['id'] = $r['ID'];
  6606. }
  6607. if (isset($r['createtime'])) {
  6608. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  6609. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  6610. } else {
  6611. $r['createtime_text'] = (string)$r['createtime'];
  6612. }
  6613. } else {
  6614. $r['createtime_text'] = '';
  6615. }
  6616. }
  6617. unset($r);
  6618. $pickedCompanyName = '';
  6619. if ($isPurchaseConfirm) {
  6620. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  6621. if (!is_array($poRow)) {
  6622. continue;
  6623. }
  6624. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6625. if ($pn !== '') {
  6626. $pickedCompanyName = $pn;
  6627. break;
  6628. }
  6629. }
  6630. }
  6631. $this->view->assign('rows', $rows ?: []);
  6632. $this->view->assign('rowCount', count($rows ?: []));
  6633. $this->view->assign('scydgyId', $ids);
  6634. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  6635. $this->view->assign('headTitle', $headTitle);
  6636. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  6637. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  6638. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  6639. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  6640. $this->view->assign('processDisplayRows', $processDisplayRows);
  6641. $this->view->assign('confirmPickGroups', $confirmPickGroups);
  6642. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  6643. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  6644. $sysRqDisplay = '—';
  6645. if ($isPurchaseConfirm) {
  6646. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  6647. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  6648. );
  6649. }
  6650. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  6651. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  6652. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  6653. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  6654. if ($isPurchaseConfirm) {
  6655. return $this->view->fetch();
  6656. }
  6657. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6658. $this->view->engine->layout(false);
  6659. try {
  6660. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  6661. $this->view->assign('dialogBody', $bodyHtml);
  6662. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  6663. } finally {
  6664. if ($restoreLayout) {
  6665. $this->view->engine->layout($restoreLayout);
  6666. }
  6667. }
  6668. }
  6669. /**
  6670. * 月度导出记录表(不存在时自动创建)
  6671. */
  6672. protected function ensurePurchaseMonthExportLogTable(): void
  6673. {
  6674. try {
  6675. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  6676. } catch (\Throwable $e) {
  6677. Db::execute(
  6678. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  6679. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  6680. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  6681. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  6682. `admin_name` varchar(64) NOT NULL DEFAULT '',
  6683. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  6684. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  6685. `createtime` int(10) unsigned DEFAULT NULL,
  6686. PRIMARY KEY (`id`),
  6687. KEY `idx_ym` (`ym`),
  6688. KEY `idx_ct` (`createtime`)
  6689. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  6690. );
  6691. }
  6692. }
  6693. /**
  6694. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  6695. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  6696. */
  6697. public function export_month_outward()
  6698. {
  6699. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  6700. $this->error(__('You have no permission'));
  6701. }
  6702. $this->request->filter(['strip_tags', 'trim']);
  6703. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  6704. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  6705. $ym = date('Y-m');
  6706. }
  6707. $dbRows = [];
  6708. try {
  6709. $query = Db::table('purchase_order');
  6710. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  6711. $dbRows = $query->select();
  6712. } catch (\Throwable $e) {
  6713. $dbRows = [];
  6714. }
  6715. if (!is_array($dbRows)) {
  6716. $dbRows = [];
  6717. }
  6718. $completeTsMap = [];
  6719. $sidList = [];
  6720. foreach ($dbRows as $dbRow) {
  6721. if (!is_array($dbRow)) {
  6722. continue;
  6723. }
  6724. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  6725. if ($sid > 0) {
  6726. $sidList[$sid] = true;
  6727. }
  6728. }
  6729. if ($sidList !== []) {
  6730. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  6731. }
  6732. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  6733. if (!is_array($dbRow)) {
  6734. return false;
  6735. }
  6736. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  6737. return $done['ts'] > 0 && date('Y-m', $done['ts']) === $ym;
  6738. }));
  6739. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  6740. $filtered = $pool;
  6741. $mainBySid = [];
  6742. foreach ($filtered as $rw) {
  6743. if (!is_array($rw)) {
  6744. continue;
  6745. }
  6746. $rid = (int)($rw['ID'] ?? 0);
  6747. if ($rid > 0) {
  6748. $mainBySid[$rid] = $rw;
  6749. }
  6750. }
  6751. if ($mainBySid === []) {
  6752. $detailRows = [];
  6753. } else {
  6754. try {
  6755. $detailRows = Db::table('purchase_order_detail')
  6756. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6757. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  6758. ->order('status', 'desc')
  6759. ->order('CCYDH', 'asc')
  6760. ->order('company_name', 'asc')
  6761. ->order('id', 'asc')
  6762. ->select();
  6763. } catch (\Throwable $e) {
  6764. try {
  6765. $detailRows = Db::table('purchase_order_detail')
  6766. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6767. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  6768. ->order('status', 'desc')
  6769. ->order('CCYDH', 'asc')
  6770. ->order('company_name', 'asc')
  6771. ->order('ID', 'asc')
  6772. ->select();
  6773. } catch (\Throwable $e2) {
  6774. $detailRows = [];
  6775. }
  6776. }
  6777. }
  6778. if (!is_array($detailRows)) {
  6779. $detailRows = [];
  6780. }
  6781. $exportLines = [];
  6782. $detailSidSeen = [];
  6783. foreach ($detailRows as $dr) {
  6784. if (!is_array($dr)) {
  6785. continue;
  6786. }
  6787. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6788. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  6789. continue;
  6790. }
  6791. if (isset($detailSidSeen[$sid])) {
  6792. continue;
  6793. }
  6794. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6795. continue;
  6796. }
  6797. $detailSidSeen[$sid] = true;
  6798. $m = $mainBySid[$sid];
  6799. $exportLines[] = [
  6800. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6801. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6802. 'company_name' => (string)($dr['company_name'] ?? ''),
  6803. 'CDF' => (string)($m['CDF'] ?? ''),
  6804. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6805. 'gx' => $this->procuremenExportGxText($m),
  6806. 'detail' => $dr,
  6807. ];
  6808. }
  6809. foreach ($detailRows as $dr) {
  6810. if (!is_array($dr)) {
  6811. continue;
  6812. }
  6813. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6814. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  6815. continue;
  6816. }
  6817. $detailSidSeen[$sid] = true;
  6818. $m = $mainBySid[$sid];
  6819. $exportLines[] = [
  6820. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6821. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6822. 'company_name' => (string)($dr['company_name'] ?? ''),
  6823. 'CDF' => (string)($m['CDF'] ?? ''),
  6824. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6825. 'gx' => $this->procuremenExportGxText($m),
  6826. 'detail' => $dr,
  6827. ];
  6828. }
  6829. foreach ($mainBySid as $sid => $m) {
  6830. if (isset($detailSidSeen[$sid])) {
  6831. continue;
  6832. }
  6833. $company = trim((string)($m['pick_company_name'] ?? ''));
  6834. $exportLines[] = [
  6835. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  6836. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  6837. 'company_name' => $company,
  6838. 'CDF' => (string)($m['CDF'] ?? ''),
  6839. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6840. 'gx' => $this->procuremenExportGxText($m),
  6841. 'detail' => [],
  6842. ];
  6843. }
  6844. $groups = [];
  6845. foreach ($exportLines as $line) {
  6846. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  6847. if (!isset($groups[$k])) {
  6848. $groups[$k] = [];
  6849. }
  6850. $groups[$k][] = $line;
  6851. }
  6852. ksort($groups, SORT_STRING);
  6853. $spreadsheet = new Spreadsheet();
  6854. $sheet = $spreadsheet->getActiveSheet();
  6855. $sheet->setTitle('外协加工明细');
  6856. $mon = (int)substr($ym, 5, 2);
  6857. $sheet->mergeCells('A1:H1');
  6858. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  6859. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  6860. $sheet->getStyle('A1')->getAlignment()
  6861. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  6862. ->setVertical(Alignment::VERTICAL_CENTER);
  6863. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  6864. $col = 'A';
  6865. foreach ($headers as $h) {
  6866. $sheet->setCellValue($col . '2', $h);
  6867. $col++;
  6868. }
  6869. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  6870. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6871. $rowNum = 3;
  6872. $sumSubtotalCounts = 0;
  6873. $grandAmount = 0.0;
  6874. $globalSeq = 0;
  6875. if ($groups === []) {
  6876. $sheet->mergeCells('A3:H3');
  6877. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  6878. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6879. $rowNum = 4;
  6880. } else {
  6881. foreach ($groups as $items) {
  6882. if ($items === []) {
  6883. continue;
  6884. }
  6885. $groupLineCount = count($items);
  6886. $subAmount = 0.0;
  6887. foreach ($items as $line) {
  6888. $globalSeq++;
  6889. $dr = $line['detail'];
  6890. $amt = $this->procuremenExportAmount($dr);
  6891. $subAmount += $amt;
  6892. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  6893. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  6894. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  6895. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  6896. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  6897. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  6898. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  6899. $sheet->setCellValue('H' . $rowNum, $amt);
  6900. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  6901. $rowNum++;
  6902. }
  6903. $sumSubtotalCounts += $groupLineCount;
  6904. $grandAmount += $subAmount;
  6905. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6906. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  6907. $sheet->getStyle('G' . $rowNum)->getAlignment()
  6908. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  6909. ->setVertical(Alignment::VERTICAL_CENTER);
  6910. $rowNum++;
  6911. }
  6912. }
  6913. $sheet->setCellValue('A' . $rowNum, '总计');
  6914. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  6915. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6916. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  6917. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  6918. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  6919. $lastRow = $rowNum;
  6920. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  6921. 'borders' => [
  6922. 'allBorders' => [
  6923. 'borderStyle' => Border::BORDER_THIN,
  6924. 'color' => ['rgb' => '000000'],
  6925. ],
  6926. ],
  6927. ]);
  6928. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  6929. if ($lastRow >= 3) {
  6930. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6931. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6932. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6933. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6934. }
  6935. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  6936. $sheet->getColumnDimension('A')->setWidth(7);
  6937. $sheet->getColumnDimension('B')->setWidth(16);
  6938. $sheet->getColumnDimension('C')->setWidth(52);
  6939. $sheet->getColumnDimension('D')->setWidth(32);
  6940. $sheet->getColumnDimension('E')->setWidth(12);
  6941. $sheet->getColumnDimension('F')->setWidth(44);
  6942. $sheet->getColumnDimension('G')->setWidth(26);
  6943. $sheet->getColumnDimension('H')->setWidth(13);
  6944. $sheet->getRowDimension(1)->setRowHeight(28);
  6945. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  6946. $quoteStartRow = $lastRow + 3;
  6947. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
  6948. if ($quoteLastRow >= $quoteStartRow) {
  6949. $sheet->getColumnDimension('E')->setWidth(28);
  6950. }
  6951. $ymCompact = str_replace('-', '', $ym);
  6952. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  6953. $filename = $fileBase . '.xlsx';
  6954. try {
  6955. $this->ensurePurchaseMonthExportLogTable();
  6956. list($adminId, $adminName) = $this->GetUseName();
  6957. Db::table('purchase_month_export_log')->insert([
  6958. 'ym' => $ym,
  6959. 'admin_id' => (int)$adminId,
  6960. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  6961. 'row_count' => count($exportLines),
  6962. 'total_amount' => round($grandAmount, 2),
  6963. 'createtime' => time(),
  6964. ]);
  6965. } catch (\Throwable $e) {
  6966. Log::write('month export log: ' . $e->getMessage(), 'error');
  6967. }
  6968. if (ob_get_length()) {
  6969. ob_end_clean();
  6970. }
  6971. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  6972. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  6973. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  6974. header('Cache-Control: max-age=0');
  6975. $writer = new Xlsx($spreadsheet);
  6976. $writer->save('php://output');
  6977. $spreadsheet->disconnectWorksheets();
  6978. unset($spreadsheet);
  6979. exit;
  6980. }
  6981. /**
  6982. * 导出用:工序列文案
  6983. */
  6984. protected function procuremenExportGxText(array $r)
  6985. {
  6986. $a = trim((string)($r['CDXMC'] ?? ''));
  6987. $b = trim((string)($r['CGYMC'] ?? ''));
  6988. if ($a !== '' && $b !== '') {
  6989. return $a . ':' . $b;
  6990. }
  6991. return $a !== '' ? $a : $b;
  6992. }
  6993. /**
  6994. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  6995. */
  6996. protected function procuremenExportAmount(array $r)
  6997. {
  6998. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  6999. if (!array_key_exists($k, $r)) {
  7000. continue;
  7001. }
  7002. $v = $r[$k];
  7003. if ($v === null || $v === '') {
  7004. continue;
  7005. }
  7006. if (is_numeric($v)) {
  7007. return (float)$v;
  7008. }
  7009. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  7010. if ($v !== '' && is_numeric($v)) {
  7011. return (float)$v;
  7012. }
  7013. }
  7014. return 0.0;
  7015. }
  7016. /**
  7017. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  7018. *
  7019. * @param array<int, array<string, mixed>> $detailRows
  7020. * @param array<int, array<string, mixed>> $mainBySid
  7021. * @return array<int, array<string, mixed>>
  7022. */
  7023. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  7024. {
  7025. $lines = [];
  7026. foreach ($detailRows as $dr) {
  7027. if (!is_array($dr)) {
  7028. continue;
  7029. }
  7030. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7031. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7032. continue;
  7033. }
  7034. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  7035. continue;
  7036. }
  7037. $cn = trim((string)($dr['company_name'] ?? ''));
  7038. if ($cn === '') {
  7039. continue;
  7040. }
  7041. $m = $mainBySid[$sid];
  7042. $am = trim((string)($dr['amount'] ?? ''));
  7043. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  7044. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  7045. $amountText = $amountFilled
  7046. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  7047. : '未填写';
  7048. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  7049. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  7050. if ($deliveryShow === '' && $deliveryRaw !== '') {
  7051. $deliveryShow = $deliveryRaw;
  7052. }
  7053. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  7054. ? $deliveryShow
  7055. : '未填写';
  7056. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  7057. $lines[] = [
  7058. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7059. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7060. 'gx' => $this->procuremenExportGxText($m),
  7061. 'company_name' => $cn,
  7062. 'amount_text' => $amountText,
  7063. 'amount_num' => $amountFilled ? $amountNum : null,
  7064. 'delivery_text' => $deliveryText,
  7065. 'picked_text' => $picked ? '中标' : '未中标',
  7066. 'picked' => $picked,
  7067. ];
  7068. }
  7069. $winnerSupplierByOrder = [];
  7070. foreach ($lines as $line) {
  7071. $dh = trim((string)($line['CCYDH'] ?? ''));
  7072. $cn = trim((string)($line['company_name'] ?? ''));
  7073. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  7074. $winnerSupplierByOrder[$dh][$cn] = true;
  7075. }
  7076. }
  7077. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  7078. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  7079. if ($c !== 0) {
  7080. return $c;
  7081. }
  7082. $dh = trim((string)($a['CCYDH'] ?? ''));
  7083. $aCn = trim((string)($a['company_name'] ?? ''));
  7084. $bCn = trim((string)($b['company_name'] ?? ''));
  7085. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  7086. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  7087. if ($aSupplierWin !== $bSupplierWin) {
  7088. return $aSupplierWin ? -1 : 1;
  7089. }
  7090. $c = strcmp($aCn, $bCn);
  7091. if ($c !== 0) {
  7092. return $c;
  7093. }
  7094. if (!empty($a['picked']) !== !empty($b['picked'])) {
  7095. return !empty($a['picked']) ? -1 : 1;
  7096. }
  7097. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  7098. if ($c !== 0) {
  7099. return $c;
  7100. }
  7101. return 0;
  7102. });
  7103. return $lines;
  7104. }
  7105. /**
  7106. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  7107. *
  7108. * @param array<int, array<string, mixed>> $quoteLines
  7109. */
  7110. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  7111. {
  7112. $mon = (int)substr($ym, 5, 2);
  7113. $titleRow = $startRow;
  7114. $headerRow = $startRow + 1;
  7115. $dataStartRow = $startRow + 2;
  7116. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  7117. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  7118. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  7119. $sheet->getStyle('A' . $titleRow)->getAlignment()
  7120. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7121. ->setVertical(Alignment::VERTICAL_CENTER);
  7122. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  7123. $col = 'A';
  7124. foreach ($headers as $h) {
  7125. $sheet->setCellValue($col . $headerRow, $h);
  7126. $col++;
  7127. }
  7128. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  7129. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7130. $rowNum = $dataStartRow;
  7131. if ($quoteLines === []) {
  7132. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  7133. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  7134. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7135. $rowNum = $dataStartRow + 1;
  7136. } else {
  7137. $i = 0;
  7138. foreach ($quoteLines as $line) {
  7139. $i++;
  7140. $sheet->setCellValue('A' . $rowNum, $i);
  7141. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  7142. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  7143. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  7144. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  7145. if ($line['amount_num'] !== null) {
  7146. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  7147. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  7148. } else {
  7149. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  7150. }
  7151. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  7152. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  7153. if (!empty($line['picked'])) {
  7154. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  7155. }
  7156. $rowNum++;
  7157. }
  7158. }
  7159. $lastRow = $rowNum - 1;
  7160. if ($lastRow >= $headerRow) {
  7161. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  7162. 'borders' => [
  7163. 'allBorders' => [
  7164. 'borderStyle' => Border::BORDER_THIN,
  7165. 'color' => ['rgb' => '000000'],
  7166. ],
  7167. ],
  7168. ]);
  7169. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  7170. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7171. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7172. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7173. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  7174. if ($lastRow >= $dataStartRow) {
  7175. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  7176. }
  7177. }
  7178. return $lastRow;
  7179. }
  7180. /**
  7181. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  7182. */
  7183. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  7184. {
  7185. if ($lastRow < $dataStartRow || $headerRow < 1) {
  7186. return;
  7187. }
  7188. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  7189. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7190. ->setVertical(Alignment::VERTICAL_CENTER);
  7191. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  7192. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7193. ->setVertical(Alignment::VERTICAL_CENTER);
  7194. if ($lastCol > 'B') {
  7195. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  7196. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  7197. ->setVertical(Alignment::VERTICAL_CENTER);
  7198. }
  7199. }
  7200. /**
  7201. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  7202. */
  7203. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  7204. {
  7205. $s = trim($ccydh);
  7206. if ($s === '') {
  7207. return 'ORDER';
  7208. }
  7209. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  7210. $s = trim($s, '._-');
  7211. if ($s === '') {
  7212. return 'ORDER';
  7213. }
  7214. if (function_exists('mb_substr')) {
  7215. return mb_substr($s, 0, 80, 'UTF-8');
  7216. }
  7217. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  7218. }
  7219. /**
  7220. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  7221. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  7222. *
  7223. * @return array{objectKey: string, webPath: string}
  7224. */
  7225. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  7226. {
  7227. $sid = (int)$scydgyId;
  7228. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  7229. $y = date('Y');
  7230. $m = date('m');
  7231. $d = date('d');
  7232. $basename = $safeOrder . '_' . $sid . '.pdf';
  7233. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  7234. return [
  7235. 'objectKey' => $objectKey,
  7236. 'webPath' => '/' . $objectKey,
  7237. ];
  7238. }
  7239. /**
  7240. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  7241. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  7242. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  7243. *
  7244. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  7245. */
  7246. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  7247. {
  7248. if (!$this->isValidScydgyRowId($scydgyId)) {
  7249. return '';
  7250. }
  7251. $ids = trim((string)$scydgyId);
  7252. $prep = $this->prepareProcuremenDetailsView($ids);
  7253. if (!$prep['ok']) {
  7254. return '';
  7255. }
  7256. $ccydh = $prep['ccydh'];
  7257. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  7258. $objectKey = $paths['objectKey'];
  7259. $webPath = $paths['webPath'];
  7260. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  7261. $this->view->assign([
  7262. 'pdf_export' => 1,
  7263. 'pdfMetaLine' => $meta,
  7264. ]);
  7265. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  7266. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  7267. $this->view->engine->layout(false);
  7268. try {
  7269. $html = $this->view->fetch('procuremen/details_pdf_shell');
  7270. } catch (\Throwable $e) {
  7271. if ($restoreLayout) {
  7272. $this->view->engine->layout($restoreLayout);
  7273. }
  7274. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  7275. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  7276. return '';
  7277. }
  7278. if ($restoreLayout) {
  7279. $this->view->engine->layout($restoreLayout);
  7280. }
  7281. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  7282. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  7283. if (!is_dir($tempDir)) {
  7284. @mkdir($tempDir, 0755, true);
  7285. }
  7286. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  7287. try {
  7288. $mpdf = new \Mpdf\Mpdf([
  7289. 'mode' => 'utf-8',
  7290. 'format' => 'A4',
  7291. 'margin_left' => 12,
  7292. 'margin_right' => 12,
  7293. 'margin_top' => 14,
  7294. 'margin_bottom' => 14,
  7295. 'tempDir' => $tempDir,
  7296. 'autoScriptToLang' => true,
  7297. 'autoLangToFont' => true,
  7298. ]);
  7299. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  7300. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  7301. $mpdf->SetBasePath('http://127.0.0.1/');
  7302. $mpdf->WriteHTML($html);
  7303. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  7304. } catch (\Throwable $e) {
  7305. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  7306. if (is_file($tempPdf)) {
  7307. @unlink($tempPdf);
  7308. }
  7309. return '';
  7310. }
  7311. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  7312. if ($ossUrl !== '') {
  7313. @unlink($tempPdf);
  7314. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  7315. return $ossUrl;
  7316. }
  7317. $pi = pathinfo($objectKey);
  7318. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  7319. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  7320. if ($baseFile === '') {
  7321. @unlink($tempPdf);
  7322. return '';
  7323. }
  7324. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  7325. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  7326. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  7327. @unlink($tempPdf);
  7328. return '';
  7329. }
  7330. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  7331. if (!@copy($tempPdf, $fullPath)) {
  7332. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  7333. @unlink($tempPdf);
  7334. return '';
  7335. }
  7336. @unlink($tempPdf);
  7337. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  7338. return $webPath;
  7339. }
  7340. /**
  7341. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  7342. */
  7343. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  7344. {
  7345. if ($scydgyId <= 0 || $webPath === '') {
  7346. return;
  7347. }
  7348. try {
  7349. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  7350. } catch (\Throwable $e) {
  7351. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  7352. }
  7353. }
  7354. /**
  7355. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  7356. *
  7357. * @param array<string, string> $vars
  7358. * @return array<string, string>
  7359. */
  7360. protected function normalizeSmsTemplateVars(array $vars): array
  7361. {
  7362. $out = [];
  7363. foreach ($vars as $k => $v) {
  7364. $out[(string)$k] = trim((string)$v);
  7365. }
  7366. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  7367. $out['contact_name'] = $out['company_name'];
  7368. }
  7369. return $out;
  7370. }
  7371. /**
  7372. * 按手机号或公司名称查 customer 表联系人姓名
  7373. */
  7374. protected function resolveCustomerContactName(string $phone, string $companyName): string
  7375. {
  7376. $phone = trim($phone);
  7377. $companyName = trim($companyName);
  7378. try {
  7379. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  7380. $row = Db::table('customer')
  7381. ->where(function ($q) use ($phone) {
  7382. $q->where('phone', $phone)->whereOr('account', $phone);
  7383. })
  7384. ->order('id', 'asc')
  7385. ->find();
  7386. if (is_array($row)) {
  7387. $nm = trim((string)($row['username'] ?? ''));
  7388. if ($nm !== '') {
  7389. return $nm;
  7390. }
  7391. }
  7392. }
  7393. if ($companyName !== '') {
  7394. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  7395. if (is_array($row)) {
  7396. return trim((string)($row['username'] ?? ''));
  7397. }
  7398. }
  7399. } catch (\Throwable $e) {
  7400. }
  7401. return '';
  7402. }
  7403. /**
  7404. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  7405. */
  7406. protected function plainTextToHtmlEmailBody(string $text): string
  7407. {
  7408. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  7409. $parts = explode("\n", $text);
  7410. $out = [];
  7411. foreach ($parts as $line) {
  7412. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  7413. $out[] = $line;
  7414. } else {
  7415. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  7416. }
  7417. }
  7418. return implode("<br>\n", $out);
  7419. }
  7420. /**
  7421. * 短信场景:去掉链接类变量,避免误填 URL
  7422. *
  7423. * @param array<string, string> $vars
  7424. * @return array<string, string>
  7425. */
  7426. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  7427. {
  7428. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  7429. return $vars;
  7430. }
  7431. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  7432. $vars[$k] = '';
  7433. }
  7434. return $vars;
  7435. }
  7436. /**
  7437. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  7438. *
  7439. * @param array<string, string> $vars
  7440. */
  7441. protected function renderNotifyTemplate(string $scene, array $vars): string
  7442. {
  7443. $vars = $this->normalizeSmsTemplateVars($vars);
  7444. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  7445. $row = $this->loadNotifyTemplateRow($scene);
  7446. if ($row === null) {
  7447. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  7448. }
  7449. $tpl = trim((string)($row['content'] ?? ''));
  7450. if ($tpl === '') {
  7451. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  7452. }
  7453. foreach ($vars as $k => $v) {
  7454. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  7455. }
  7456. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  7457. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  7458. return $tpl;
  7459. }
  7460. protected function resolveProcuremenEmailSubject(string $scene): string
  7461. {
  7462. $map = [
  7463. 'review_email' => '您有新的协助加工订单',
  7464. ];
  7465. $subject = trim((string)($map[$scene] ?? ''));
  7466. if ($subject === '') {
  7467. $this->error('未配置邮件主题:' . $scene);
  7468. }
  7469. return $subject;
  7470. }
  7471. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  7472. {
  7473. $map = [
  7474. 'review_email' => '协助下发-邮箱',
  7475. 'review_sms' => '协助下发-短信',
  7476. 'confirm_ok' => '采购确认-通过',
  7477. 'confirm_fail' => '采购确认-未通过',
  7478. ];
  7479. $label = $map[$scene] ?? $scene;
  7480. if ($titleRequired) {
  7481. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  7482. }
  7483. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  7484. }
  7485. /**
  7486. * 是否开启协助通知演练(不发真实短信/邮件)
  7487. */
  7488. protected function isProcuremenNotifyDryRun(): bool
  7489. {
  7490. return (bool)Config::get('procuremen_notify_dry_run');
  7491. }
  7492. /**
  7493. * @param array<string, mixed> $payload
  7494. */
  7495. protected function recordNotifyDryRunPreview(array $payload): void
  7496. {
  7497. $this->notifyDryRunPreview[] = $payload;
  7498. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  7499. }
  7500. /**
  7501. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  7502. * @throws \Exception
  7503. */
  7504. protected function smsbao($phone, $content)
  7505. {
  7506. if ($this->isProcuremenNotifyDryRun()) {
  7507. $this->recordNotifyDryRunPreview([
  7508. 'scene' => 'sms_only',
  7509. 'phone' => $phone,
  7510. 'sms_content' => $content,
  7511. ]);
  7512. return;
  7513. }
  7514. $statusStr = [
  7515. '0' => '短信发送成功',
  7516. '-1' => '参数不全',
  7517. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  7518. '30' => '密码错误',
  7519. '40' => '账号不存在',
  7520. '41' => '余额不足',
  7521. '42' => '帐户已过期',
  7522. '43' => 'IP地址限制',
  7523. '50' => '内容含有敏感词',
  7524. ];
  7525. $smsapi = 'http://api.smsbao.com/';
  7526. $user = 'zhuwei123';
  7527. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  7528. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  7529. $result = @file_get_contents($sendurl);
  7530. if ($result === false) {
  7531. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  7532. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  7533. }
  7534. $result = trim((string)$result);
  7535. if ($result !== '0') {
  7536. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  7537. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  7538. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  7539. }
  7540. }
  7541. }