admin.py 288 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855
  1. """运营端接口"""
  2. import json
  3. import random
  4. import string
  5. import uuid
  6. from typing import Optional, List, Any, Tuple
  7. from datetime import datetime
  8. from decimal import Decimal
  9. from fastapi import APIRouter, Depends, HTTPException, Query, Request, UploadFile, File, Form
  10. from sqlalchemy.orm import Session
  11. from sqlalchemy import and_, or_, func
  12. from sqlalchemy.exc import IntegrityError
  13. from app.core.database import get_db
  14. from app.core.auth import get_current_user
  15. from app.core.security import get_password_hash, verify_password
  16. from app.core.response import success_response, error_response
  17. from app.core.storage import storage
  18. from app.models.models import (
  19. SysUser, SysRegion, BasProductCategory, BasProductUnit, BasProduct,
  20. BizOrder, BizOrderItem, BizPriceList, BizPriceListItem,
  21. OrdClientSettlement, OrdClientSettlementItem,
  22. OrdSupplierSettlement, OrdSupplierSettlementItem,
  23. )
  24. from app.api.upload import validate_file, ALLOWED_IMAGE_TYPES, MAX_IMAGE_SIZE
  25. from app.crud.region import region_crud
  26. from app.crud.category import category_crud
  27. from app.crud.unit import unit_crud
  28. from app.crud.user import user_crud
  29. from app.crud.password_history import password_history_crud
  30. from app.crud.product import product_crud
  31. from app.crud.address import address_crud
  32. from app.core.utils import generate_id
  33. from app.services.china_region_tree import build_china_region_tree, query_china_regions_active
  34. router = APIRouter(prefix="/web/admin", tags=["运营端管理接口"])
  35. def _numeric_to_float_optional(v) -> Optional[float]:
  36. if v is None:
  37. return None
  38. return float(v)
  39. def _category_path_display(db: Session, category_id: Optional[str]) -> str:
  40. """一级/二级分类用 / 连接(自底向上回溯父级)。"""
  41. if not category_id:
  42. return ""
  43. names: List[str] = []
  44. cid = str(category_id).strip()
  45. seen = set()
  46. depth = 0
  47. while cid and depth < 24 and cid not in seen:
  48. seen.add(cid)
  49. cat = category_crud.get(db, cid)
  50. if not cat:
  51. break
  52. names.insert(0, (getattr(cat, "name", None) or "").strip())
  53. pid = getattr(cat, "parent_id", None)
  54. cid = str(pid).strip() if pid else ""
  55. depth += 1
  56. return "/".join([n for n in names if n])
  57. def _supplier_pickup_address_block(db: Session, supplier_id: Optional[str]) -> dict:
  58. """供应商默认取货地址;无默认时取第一条 pickup 类型地址。"""
  59. empty = {"fullAddress": None, "contactPerson": None, "contactPhone": None}
  60. if not supplier_id:
  61. return empty
  62. addr = address_crud.get_default(db, supplier_id, "pickup")
  63. if not addr:
  64. rows = address_crud.get_by_user_and_type(db, supplier_id, "pickup")
  65. addr = rows[0] if rows else None
  66. if not addr:
  67. return empty
  68. segs = [
  69. getattr(addr, "province", None),
  70. getattr(addr, "city", None),
  71. getattr(addr, "district", None),
  72. getattr(addr, "detail_address", None),
  73. ]
  74. full = "".join(s for s in segs if s)
  75. return {
  76. "fullAddress": full or None,
  77. "contactPerson": addr.contact_person,
  78. "contactPhone": addr.contact_phone,
  79. }
  80. def require_admin(current_user: dict = Depends(get_current_user)):
  81. """验证运营人员权限"""
  82. if current_user.get("role") != "admin":
  83. raise HTTPException(status_code=403, detail="需要运营人员权限")
  84. return current_user
  85. def get_admin_region_filter(db: Session, current_user: dict) -> Optional[str]:
  86. """获取管理员的区域过滤条件
  87. 对于区域管理员,返回其所属区域ID(用于过滤数据)
  88. 对于超级管理员(无区域绑定),返回None(不过滤)
  89. """
  90. user_id = current_user.get("user_id")
  91. if not user_id:
  92. return None
  93. user = user_crud.get(db, user_id)
  94. if not user:
  95. return None
  96. # 如果管理员绑定了区域ID,则只能查看该区域的数据
  97. if user.region_id:
  98. return user.region_id
  99. return None
  100. def _effective_settlement_region_id(
  101. admin_region_id: Optional[str],
  102. tab_or_filter_region_id: Optional[str],
  103. ) -> Optional[str]:
  104. """结算相关接口:区域管理员固定为其绑定区域;超级管理员可按 Tab 的 regionId 筛选。"""
  105. if admin_region_id:
  106. return admin_region_id
  107. return tab_or_filter_region_id or None
  108. def _aggregate_client_settlement_history(
  109. db: Session,
  110. eff_region_id: Optional[str],
  111. client_id: Optional[str],
  112. ) -> Tuple[float, int]:
  113. """已生成客户结算单:结算金额合计、订单笔数合计(与结算单主表 order_count 汇总一致)。"""
  114. q = db.query(
  115. func.coalesce(func.sum(OrdClientSettlement.total_amount), 0),
  116. func.coalesce(func.sum(OrdClientSettlement.order_count), 0),
  117. ).filter(OrdClientSettlement.is_del == 0)
  118. if client_id:
  119. q = q.filter(OrdClientSettlement.client_id == client_id)
  120. if eff_region_id:
  121. sub = (
  122. db.query(OrdClientSettlementItem.settlement_id)
  123. .join(BizOrder, BizOrder.id == OrdClientSettlementItem.order_id)
  124. .filter(
  125. OrdClientSettlementItem.is_del == 0,
  126. BizOrder.is_del == 0,
  127. BizOrder.region_id == eff_region_id,
  128. )
  129. .distinct()
  130. )
  131. q = q.filter(OrdClientSettlement.id.in_(sub))
  132. row = q.one()
  133. return float(row[0] or 0), int(row[1] or 0)
  134. def _aggregate_supplier_settlement_history(
  135. db: Session,
  136. eff_region_id: Optional[str],
  137. supplier_id: Optional[str],
  138. ) -> Tuple[float, int]:
  139. """已生成供应商结算单:结算金额合计、订单笔数合计。"""
  140. q = db.query(
  141. func.coalesce(func.sum(OrdSupplierSettlement.total_amount), 0),
  142. func.coalesce(func.sum(OrdSupplierSettlement.order_count), 0),
  143. ).filter(OrdSupplierSettlement.is_del == 0)
  144. if supplier_id:
  145. q = q.filter(OrdSupplierSettlement.supplier_id == supplier_id)
  146. if eff_region_id:
  147. sub = (
  148. db.query(OrdSupplierSettlementItem.settlement_id)
  149. .join(BizOrder, BizOrder.id == OrdSupplierSettlementItem.order_id)
  150. .filter(
  151. OrdSupplierSettlementItem.is_del == 0,
  152. BizOrder.is_del == 0,
  153. BizOrder.region_id == eff_region_id,
  154. )
  155. .distinct()
  156. )
  157. q = q.filter(OrdSupplierSettlement.id.in_(sub))
  158. row = q.one()
  159. return float(row[0] or 0), int(row[1] or 0)
  160. _REGION_MINUTES_UNSET = object()
  161. def _minutes_value_from_request(request: dict, camel: str, snake: str):
  162. """解析区域配送相关分钟配置;键不存在返回 _REGION_MINUTES_UNSET,空值为 None。"""
  163. if camel not in request and snake not in request:
  164. return _REGION_MINUTES_UNSET
  165. raw = request.get(camel, request.get(snake))
  166. if raw is None or raw == "":
  167. return None
  168. try:
  169. n = int(raw)
  170. except (TypeError, ValueError):
  171. raise ValueError("预计配送时长、预警提前时间须为非负整数(分钟)")
  172. if n < 0:
  173. raise ValueError("预计配送时长、预警提前时间须为非负整数(分钟)")
  174. return n
  175. def _apply_region_minutes_to_data(request: dict, data: dict):
  176. """将 expectedDeliveryMinutes / deliveryWarnAdvanceMinutes 写入 data(字典为 create_data 或 update_data)。失败返回 error_response 的 dict。"""
  177. try:
  178. ed = _minutes_value_from_request(
  179. request, "expectedDeliveryMinutes", "expected_delivery_minutes"
  180. )
  181. wa = _minutes_value_from_request(
  182. request, "deliveryWarnAdvanceMinutes", "delivery_warn_advance_minutes"
  183. )
  184. except ValueError as e:
  185. return error_response(400, str(e))
  186. if ed is not _REGION_MINUTES_UNSET:
  187. data["expected_delivery_minutes"] = ed
  188. if wa is not _REGION_MINUTES_UNSET:
  189. data["delivery_warn_advance_minutes"] = wa
  190. return None
  191. # ============ 中国行政区划(省市区,bas_china_region)============
  192. @router.get("/china-region-tree", response_model=dict)
  193. def get_china_region_tree_admin(
  194. db: Session = Depends(get_db),
  195. current_user: dict = Depends(require_admin),
  196. ):
  197. """省市区三级树,供运营端级联选择器等使用(数据源 bas_china_region)。"""
  198. rows = query_china_regions_active(db)
  199. return success_response({"tree": build_china_region_tree(rows)})
  200. # ============ 区域管理 ============
  201. @router.get("/regions", response_model=dict)
  202. def list_regions(
  203. page: int = Query(1, ge=1, description="页码"),
  204. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  205. keyword: Optional[str] = Query(None, description="关键词搜索"),
  206. isActive: Optional[bool] = Query(None, description="是否启用"),
  207. db: Session = Depends(get_db),
  208. current_user: dict = Depends(require_admin)
  209. ):
  210. """获取区域列表"""
  211. query = db.query(SysRegion).filter(SysRegion.is_del == 0)
  212. if keyword:
  213. query = query.filter(
  214. (SysRegion.name.like(f"%{keyword}%")) |
  215. (SysRegion.code.like(f"%{keyword}%"))
  216. )
  217. if isActive is not None:
  218. query = query.filter(SysRegion.is_active == isActive)
  219. total = query.count()
  220. skip = (page - 1) * pageSize
  221. regions = query.order_by(SysRegion.sort_order.asc()).offset(skip).limit(pageSize).all()
  222. return success_response({
  223. "list": [{"id": r.id, "name": r.name, "code": r.code, "description": r.description,
  224. "sortOrder": r.sort_order,
  225. "expectedDeliveryMinutes": r.expected_delivery_minutes,
  226. "deliveryWarnAdvanceMinutes": r.delivery_warn_advance_minutes,
  227. "isActive": r.is_active,
  228. "createAt": str(r.create_at) if r.create_at else None} for r in regions],
  229. "total": total,
  230. "page": page,
  231. "pageSize": pageSize,
  232. "totalPages": (total + pageSize - 1) // pageSize
  233. })
  234. @router.get("/regions/active", response_model=dict)
  235. def list_active_regions(
  236. db: Session = Depends(get_db),
  237. current_user: dict = Depends(require_admin)
  238. ):
  239. """获取所有启用区域(用于下拉选择)"""
  240. regions = region_crud.get_active_all(db)
  241. return success_response([{"id": r.id, "name": r.name, "code": r.code} for r in regions])
  242. @router.get("/regions/{region_id}", response_model=dict)
  243. def get_region(
  244. region_id: str,
  245. db: Session = Depends(get_db),
  246. current_user: dict = Depends(require_admin)
  247. ):
  248. """获取区域详情"""
  249. region = region_crud.get(db, region_id)
  250. if not region:
  251. return error_response(404, "区域不存在")
  252. return success_response({
  253. "id": region.id,
  254. "name": region.name,
  255. "code": region.code,
  256. "description": region.description,
  257. "sortOrder": region.sort_order,
  258. "expectedDeliveryMinutes": region.expected_delivery_minutes,
  259. "deliveryWarnAdvanceMinutes": region.delivery_warn_advance_minutes,
  260. "isActive": region.is_active,
  261. "createAt": str(region.create_at) if region.create_at else None,
  262. "createBy": region.create_by,
  263. "createName": region.create_name
  264. })
  265. @router.post("/regions", response_model=dict)
  266. def create_region(
  267. request: dict,
  268. db: Session = Depends(get_db),
  269. current_user: dict = Depends(require_admin)
  270. ):
  271. """创建区域"""
  272. # 检查编码唯一性
  273. existing = region_crud.get_by_code(db, request.get("code"))
  274. if existing:
  275. return error_response(400, "区域编码已存在")
  276. # 字段名映射
  277. create_data = {
  278. "name": request.get("name"),
  279. "code": request.get("code"),
  280. "description": request.get("description"),
  281. }
  282. if "sortOrder" in request or "sort_order" in request:
  283. create_data["sort_order"] = request.get("sortOrder", request.get("sort_order", 0))
  284. if "isActive" in request or "is_active" in request:
  285. create_data["is_active"] = request.get("isActive", request.get("is_active", True))
  286. err = _apply_region_minutes_to_data(request, create_data)
  287. if err is not None:
  288. return err
  289. creator = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  290. region = region_crud.create(db, create_data, creator)
  291. return success_response({
  292. "id": region.id,
  293. "name": region.name,
  294. "code": region.code,
  295. "description": region.description,
  296. "sortOrder": region.sort_order,
  297. "expectedDeliveryMinutes": region.expected_delivery_minutes,
  298. "deliveryWarnAdvanceMinutes": region.delivery_warn_advance_minutes,
  299. "isActive": region.is_active,
  300. "createAt": str(region.create_at) if region.create_at else None,
  301. "createBy": region.create_by,
  302. "createName": region.create_name
  303. })
  304. @router.put("/regions/{region_id}", response_model=dict)
  305. def update_region(
  306. region_id: str,
  307. request: dict,
  308. db: Session = Depends(get_db),
  309. current_user: dict = Depends(require_admin)
  310. ):
  311. """更新区域"""
  312. # 检查编码唯一性(排除自己)
  313. if "code" in request and request["code"]:
  314. existing = region_crud.get_by_code(db, request["code"])
  315. if existing and existing.id != region_id:
  316. return error_response(400, "区域编码已存在")
  317. # 字段名映射
  318. update_data = {
  319. "name": request.get("name"),
  320. "code": request.get("code"),
  321. "description": request.get("description"),
  322. }
  323. if "sortOrder" in request or "sort_order" in request:
  324. update_data["sort_order"] = request.get("sortOrder", request.get("sort_order", 0))
  325. if "isActive" in request or "is_active" in request:
  326. update_data["is_active"] = request.get("isActive", request.get("is_active", True))
  327. err = _apply_region_minutes_to_data(request, update_data)
  328. if err is not None:
  329. return err
  330. updater = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  331. region = region_crud.update_with_history(db, region_id, update_data, updater)
  332. if not region:
  333. return error_response(404, "区域不存在")
  334. return success_response({
  335. "id": region.id,
  336. "name": region.name,
  337. "code": region.code,
  338. "description": region.description,
  339. "sortOrder": region.sort_order,
  340. "expectedDeliveryMinutes": region.expected_delivery_minutes,
  341. "deliveryWarnAdvanceMinutes": region.delivery_warn_advance_minutes,
  342. "isActive": region.is_active
  343. })
  344. @router.delete("/regions/{region_id}", response_model=dict)
  345. def delete_region(
  346. region_id: str,
  347. db: Session = Depends(get_db),
  348. current_user: dict = Depends(require_admin)
  349. ):
  350. """删除区域"""
  351. success = region_crud.soft_delete_with_history(db, region_id)
  352. if not success:
  353. return error_response(404, "区域不存在")
  354. return success_response({"id": region_id})
  355. # ============ 商品分类管理 ============
  356. def _category_price_coefficient_value(category: BasProductCategory) -> float:
  357. v = getattr(category, "price_coefficient", None)
  358. if v is None:
  359. return 0.0
  360. return float(v)
  361. @router.get("/categories", response_model=dict)
  362. def list_categories(
  363. page: int = Query(1, ge=1, description="页码"),
  364. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  365. keyword: Optional[str] = Query(None, description="关键词搜索"),
  366. isActive: Optional[bool] = Query(None, description="是否启用"),
  367. db: Session = Depends(get_db),
  368. current_user: dict = Depends(require_admin)
  369. ):
  370. """获取商品分类列表"""
  371. query = db.query(BasProductCategory).filter(BasProductCategory.is_del == 0)
  372. if keyword:
  373. query = query.filter(BasProductCategory.name.like(f"%{keyword}%"))
  374. if isActive is not None:
  375. query = query.filter(BasProductCategory.is_active == isActive)
  376. total = query.count()
  377. skip = (page - 1) * pageSize
  378. categories = query.order_by(BasProductCategory.sort_order.asc()).offset(skip).limit(pageSize).all()
  379. # 查询所有分类用于获取父分类名称
  380. all_categories = db.query(BasProductCategory).filter(BasProductCategory.is_del == 0).all()
  381. parent_map = {c.id: c.name for c in all_categories}
  382. return success_response({
  383. "list": [{
  384. "id": c.id,
  385. "name": c.name,
  386. "parentId": c.parent_id,
  387. "parentName": parent_map.get(c.parent_id) if c.parent_id else None,
  388. "sortOrder": c.sort_order,
  389. "priceCoefficient": _category_price_coefficient_value(c),
  390. "isActive": c.is_active,
  391. "imageUrl": getattr(c, "image_url", None),
  392. } for c in categories],
  393. "total": total,
  394. "page": page,
  395. "pageSize": pageSize,
  396. "totalPages": (total + pageSize - 1) // pageSize
  397. })
  398. @router.get("/categories/tree", response_model=dict)
  399. def get_category_tree(
  400. db: Session = Depends(get_db),
  401. current_user: dict = Depends(require_admin)
  402. ):
  403. """获取商品分类树形结构"""
  404. tree = category_crud.get_tree(db)
  405. return success_response(tree)
  406. @router.get("/categories/active", response_model=dict)
  407. def list_active_categories(
  408. db: Session = Depends(get_db),
  409. current_user: dict = Depends(require_admin)
  410. ):
  411. """获取所有启用分类"""
  412. categories = category_crud.get_active_all(db)
  413. return success_response([{
  414. "id": c.id,
  415. "name": c.name,
  416. "parentId": c.parent_id,
  417. "priceCoefficient": _category_price_coefficient_value(c),
  418. } for c in categories])
  419. @router.get("/categories/{category_id}", response_model=dict)
  420. def get_category(
  421. category_id: str,
  422. db: Session = Depends(get_db),
  423. current_user: dict = Depends(require_admin)
  424. ):
  425. """获取分类详情"""
  426. category = category_crud.get(db, category_id)
  427. if not category:
  428. return error_response(404, "分类不存在")
  429. return success_response({
  430. "id": category.id,
  431. "name": category.name,
  432. "parentId": category.parent_id,
  433. "sortOrder": category.sort_order,
  434. "priceCoefficient": _category_price_coefficient_value(category),
  435. "isActive": category.is_active,
  436. "imageUrl": getattr(category, "image_url", None),
  437. })
  438. @router.post("/categories", response_model=dict)
  439. def create_category(
  440. request: dict,
  441. db: Session = Depends(get_db),
  442. current_user: dict = Depends(require_admin)
  443. ):
  444. """创建商品分类"""
  445. creator = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  446. create_data = {
  447. "name": request.get("name"),
  448. }
  449. # 前端传参使用驼峰命名:parentId/sortOrder/isActive/imageUrl
  450. if "parentId" in request or "parent_id" in request:
  451. v = request.get("parentId", request.get("parent_id"))
  452. create_data["parent_id"] = v or None
  453. if "sortOrder" in request or "sort_order" in request:
  454. create_data["sort_order"] = request.get("sortOrder", request.get("sort_order"))
  455. if "isActive" in request or "is_active" in request:
  456. create_data["is_active"] = request.get("isActive", request.get("is_active"))
  457. if "imageUrl" in request or "image_url" in request:
  458. v = request.get("imageUrl", request.get("image_url"))
  459. create_data["image_url"] = v or None
  460. if "priceCoefficient" in request or "price_coefficient" in request:
  461. raw = request.get("priceCoefficient", request.get("price_coefficient"))
  462. if raw is not None and raw != "":
  463. try:
  464. create_data["price_coefficient"] = float(raw)
  465. except (TypeError, ValueError):
  466. return error_response(400, "价格系数格式不正确")
  467. category = category_crud.create(db, create_data, creator)
  468. return success_response({
  469. "id": category.id,
  470. "name": category.name,
  471. "parentId": category.parent_id,
  472. "sortOrder": category.sort_order,
  473. "priceCoefficient": _category_price_coefficient_value(category),
  474. "isActive": category.is_active,
  475. "imageUrl": getattr(category, "image_url", None),
  476. })
  477. @router.put("/categories/{category_id}", response_model=dict)
  478. def update_category(
  479. category_id: str,
  480. request: dict,
  481. db: Session = Depends(get_db),
  482. current_user: dict = Depends(require_admin)
  483. ):
  484. """更新商品分类"""
  485. updater = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  486. update_data: dict = {}
  487. if "name" in request:
  488. update_data["name"] = request.get("name")
  489. if "parentId" in request or "parent_id" in request:
  490. v = request.get("parentId", request.get("parent_id"))
  491. update_data["parent_id"] = v or None
  492. if "sortOrder" in request or "sort_order" in request:
  493. update_data["sort_order"] = request.get("sortOrder", request.get("sort_order"))
  494. if "isActive" in request or "is_active" in request:
  495. update_data["is_active"] = request.get("isActive", request.get("is_active"))
  496. if "imageUrl" in request or "image_url" in request:
  497. v = request.get("imageUrl", request.get("image_url"))
  498. update_data["image_url"] = v or None
  499. if "priceCoefficient" in request or "price_coefficient" in request:
  500. raw = request.get("priceCoefficient", request.get("price_coefficient"))
  501. if raw is None or raw == "":
  502. update_data["price_coefficient"] = 0.0
  503. else:
  504. try:
  505. update_data["price_coefficient"] = float(raw)
  506. except (TypeError, ValueError):
  507. return error_response(400, "价格系数格式不正确")
  508. category = category_crud.update_with_history(db, category_id, update_data, updater)
  509. if not category:
  510. return error_response(404, "分类不存在")
  511. return success_response({
  512. "id": category.id,
  513. "name": category.name,
  514. "parentId": category.parent_id,
  515. "sortOrder": category.sort_order,
  516. "priceCoefficient": _category_price_coefficient_value(category),
  517. "isActive": category.is_active,
  518. "imageUrl": getattr(category, "image_url", None),
  519. })
  520. @router.delete("/categories/{category_id}", response_model=dict)
  521. def delete_category(
  522. category_id: str,
  523. db: Session = Depends(get_db),
  524. current_user: dict = Depends(require_admin)
  525. ):
  526. """删除商品分类"""
  527. success = category_crud.soft_delete_with_history(db, category_id)
  528. if not success:
  529. return error_response(404, "分类不存在")
  530. return success_response({"id": category_id})
  531. @router.post("/categories/upload-image", response_model=dict)
  532. async def upload_category_image(
  533. file: UploadFile = File(...),
  534. folder: str = Form("categories"),
  535. current_user: dict = Depends(require_admin),
  536. ):
  537. """上传商品分类图片(MinIO)并返回图片URL"""
  538. try:
  539. content = await validate_file(file, MAX_IMAGE_SIZE, ALLOWED_IMAGE_TYPES)
  540. original_filename = file.filename or "category.png"
  541. url = storage.upload_file(content, original_filename, folder)
  542. return success_response({"url": url})
  543. except HTTPException:
  544. raise
  545. except Exception as e:
  546. return error_response(500, f"上传失败: {str(e)}")
  547. # ============ 商品单位管理 ============
  548. @router.get("/units", response_model=dict)
  549. def list_units(
  550. page: int = Query(1, ge=1, description="页码"),
  551. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  552. keyword: Optional[str] = Query(None, description="关键词搜索"),
  553. isActive: Optional[bool] = Query(None, description="是否启用"),
  554. db: Session = Depends(get_db),
  555. current_user: dict = Depends(require_admin)
  556. ):
  557. """获取商品单位列表"""
  558. query = db.query(BasProductUnit).filter(BasProductUnit.is_del == 0)
  559. if keyword:
  560. query = query.filter(
  561. (BasProductUnit.name.like(f"%{keyword}%")) |
  562. (BasProductUnit.code.like(f"%{keyword}%"))
  563. )
  564. if isActive is not None:
  565. query = query.filter(BasProductUnit.is_active == isActive)
  566. total = query.count()
  567. skip = (page - 1) * pageSize
  568. units = query.order_by(BasProductUnit.sort_order.asc(), BasProductUnit.create_at.desc()).offset(skip).limit(pageSize).all()
  569. return success_response({
  570. "list": [{"id": u.id, "name": u.name, "code": u.code, "isActive": u.is_active, "sortOrder": u.sort_order} for u in units],
  571. "total": total,
  572. "page": page,
  573. "pageSize": pageSize,
  574. "totalPages": (total + pageSize - 1) // pageSize
  575. })
  576. @router.get("/units/active", response_model=dict)
  577. def list_active_units(
  578. db: Session = Depends(get_db),
  579. current_user: dict = Depends(require_admin)
  580. ):
  581. """获取所有启用单位"""
  582. units = unit_crud.get_active_all(db)
  583. return success_response([{"id": u.id, "name": u.name, "code": u.code} for u in units])
  584. @router.get("/units/{unit_id}", response_model=dict)
  585. def get_unit(
  586. unit_id: str,
  587. db: Session = Depends(get_db),
  588. current_user: dict = Depends(require_admin)
  589. ):
  590. """获取单位详情"""
  591. unit = unit_crud.get(db, unit_id)
  592. if not unit:
  593. return error_response(404, "单位不存在")
  594. return success_response({
  595. "id": unit.id,
  596. "name": unit.name,
  597. "code": unit.code,
  598. "isActive": unit.is_active,
  599. "sortOrder": unit.sort_order
  600. })
  601. @router.post("/units", response_model=dict)
  602. def create_unit(
  603. request: dict,
  604. db: Session = Depends(get_db),
  605. current_user: dict = Depends(require_admin)
  606. ):
  607. """创建商品单位"""
  608. # 检查编码唯一性
  609. existing = unit_crud.get_by_code(db, request.get("code"))
  610. if existing:
  611. return error_response(400, "单位编码已存在")
  612. creator = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  613. unit = unit_crud.create(db, request, creator)
  614. return success_response({
  615. "id": unit.id,
  616. "name": unit.name,
  617. "code": unit.code,
  618. "isActive": unit.is_active,
  619. "sortOrder": unit.sort_order
  620. })
  621. @router.put("/units/{unit_id}", response_model=dict)
  622. def update_unit(
  623. unit_id: str,
  624. request: dict,
  625. db: Session = Depends(get_db),
  626. current_user: dict = Depends(require_admin)
  627. ):
  628. """更新商品单位"""
  629. # 检查编码唯一性
  630. if "code" in request and request["code"]:
  631. existing = unit_crud.get_by_code(db, request["code"])
  632. if existing and existing.id != unit_id:
  633. return error_response(400, "单位编码已存在")
  634. updater = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  635. unit = unit_crud.update_with_history(db, unit_id, request, updater)
  636. if not unit:
  637. return error_response(404, "单位不存在")
  638. return success_response({
  639. "id": unit.id,
  640. "name": unit.name,
  641. "code": unit.code,
  642. "isActive": unit.is_active,
  643. "sortOrder": unit.sort_order
  644. })
  645. @router.delete("/units/{unit_id}", response_model=dict)
  646. def delete_unit(
  647. unit_id: str,
  648. db: Session = Depends(get_db),
  649. current_user: dict = Depends(require_admin)
  650. ):
  651. """删除商品单位"""
  652. success = unit_crud.soft_delete_with_history(db, unit_id)
  653. if not success:
  654. return error_response(404, "单位不存在")
  655. return success_response({"id": unit_id})
  656. # ============ 用户管理 ============
  657. # 角色定义常量
  658. ROLE_OPTIONS = [
  659. {"label": "运营管理员", "value": "admin"},
  660. {"label": "供应商", "value": "supplier"},
  661. {"label": "客户", "value": "client"},
  662. {"label": "配送员", "value": "deliver"}
  663. ]
  664. @router.get("/roles", response_model=dict)
  665. def list_roles(
  666. current_user: dict = Depends(require_admin)
  667. ):
  668. """获取角色列表"""
  669. return success_response(ROLE_OPTIONS)
  670. @router.get("/users", response_model=dict)
  671. def list_users(
  672. page: int = Query(1, ge=1, description="页码"),
  673. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  674. role: Optional[str] = Query(None, description="角色筛选"),
  675. regionId: Optional[str] = Query(None, description="区域ID"),
  676. keyword: Optional[str] = Query(None, description="关键词搜索"),
  677. isActive: Optional[bool] = Query(None, description="是否激活"),
  678. db: Session = Depends(get_db),
  679. current_user: dict = Depends(require_admin)
  680. ):
  681. """获取用户列表"""
  682. users, total = user_crud.get_multi_with_filters(
  683. db,
  684. role=role,
  685. region_id=regionId,
  686. keyword=keyword,
  687. is_active=isActive,
  688. skip=(page - 1) * pageSize,
  689. limit=pageSize
  690. )
  691. region_map = {}
  692. for user in users:
  693. if user.region_id and user.region_id not in region_map:
  694. region = region_crud.get(db, user.region_id)
  695. if region:
  696. region_map[user.region_id] = region.name
  697. return success_response({
  698. "list": [{
  699. "id": u.id,
  700. "username": u.username,
  701. "realName": u.real_name,
  702. "phone": u.phone,
  703. "avatarUrl": (str(u.avatar_url).strip() if getattr(u, "avatar_url", None) else None) or None,
  704. "role": u.role,
  705. "regionId": u.region_id,
  706. "regionName": region_map.get(u.region_id),
  707. "isActive": u.is_active,
  708. "createAt": str(u.create_at) if u.create_at else None,
  709. "createName": getattr(u, "create_name", None)
  710. } for u in users],
  711. "total": total,
  712. "page": page,
  713. "pageSize": pageSize,
  714. "totalPages": (total + pageSize - 1) // pageSize
  715. })
  716. @router.get("/users/{user_id}", response_model=dict)
  717. def get_user(
  718. user_id: str,
  719. db: Session = Depends(get_db),
  720. current_user: dict = Depends(require_admin)
  721. ):
  722. """获取用户详情"""
  723. user = user_crud.get(db, user_id)
  724. if not user:
  725. return error_response(404, "用户不存在")
  726. region_name = None
  727. if user.region_id:
  728. region = region_crud.get(db, user.region_id)
  729. region_name = region.name if region else None
  730. return success_response({
  731. "id": user.id,
  732. "username": user.username,
  733. "realName": user.real_name,
  734. "phone": user.phone,
  735. "avatarUrl": (str(user.avatar_url).strip() if getattr(user, "avatar_url", None) else None) or None,
  736. "role": user.role,
  737. "regionId": user.region_id,
  738. "regionName": region_name,
  739. "isActive": user.is_active,
  740. "createAt": str(user.create_at) if user.create_at else None,
  741. "createName": getattr(user, "create_name", None)
  742. })
  743. @router.post("/users", response_model=dict)
  744. def create_user(
  745. request: dict,
  746. db: Session = Depends(get_db),
  747. current_user: dict = Depends(require_admin)
  748. ):
  749. """创建用户"""
  750. # 检查用户名唯一性
  751. existing = user_crud.get_by_username(db, request.get("username"))
  752. if existing:
  753. return error_response(400, "用户名已存在")
  754. creator = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  755. body = dict(request) if request else {}
  756. if body.get("avatarUrl") == "":
  757. body["avatarUrl"] = None
  758. try:
  759. user, initial_password = user_crud.create_with_password(db, body, creator)
  760. except ValueError as e:
  761. return error_response(400, str(e))
  762. payload = {
  763. "id": user.id,
  764. "username": user.username,
  765. "realName": user.real_name,
  766. "avatarUrl": (str(user.avatar_url).strip() if getattr(user, "avatar_url", None) else None) or None,
  767. }
  768. if initial_password is not None:
  769. payload["initialPassword"] = initial_password
  770. return success_response(payload)
  771. @router.put("/users/{user_id}", response_model=dict)
  772. def update_user(
  773. user_id: str,
  774. request: dict,
  775. db: Session = Depends(get_db),
  776. current_user: dict = Depends(require_admin)
  777. ):
  778. """更新用户"""
  779. updater = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  780. req = dict(request) if request else {}
  781. if req.get("avatarUrl") == "":
  782. req["avatarUrl"] = None
  783. user = user_crud.update_with_history(db, user_id, req, updater)
  784. if not user:
  785. return error_response(404, "用户不存在")
  786. region_name = None
  787. if user.region_id:
  788. region = region_crud.get(db, user.region_id)
  789. region_name = region.name if region else None
  790. return success_response({
  791. "id": user.id,
  792. "username": user.username,
  793. "realName": user.real_name,
  794. "phone": user.phone,
  795. "avatarUrl": (str(user.avatar_url).strip() if getattr(user, "avatar_url", None) else None) or None,
  796. "role": user.role,
  797. "regionId": user.region_id,
  798. "regionName": region_name,
  799. "isActive": user.is_active
  800. })
  801. @router.delete("/users/{user_id}", response_model=dict)
  802. def delete_user(
  803. user_id: str,
  804. db: Session = Depends(get_db),
  805. current_user: dict = Depends(require_admin)
  806. ):
  807. """删除用户"""
  808. # 不能删除自己
  809. if user_id == current_user.get("user_id"):
  810. return error_response(400, "不能删除当前登录账号")
  811. success = user_crud.soft_delete_with_history(db, user_id)
  812. if not success:
  813. return error_response(404, "用户不存在")
  814. return success_response({"id": user_id})
  815. @router.post("/users/upload-avatar", response_model=dict)
  816. async def upload_user_avatar(
  817. file: UploadFile = File(...),
  818. folder: str = Form("avatars"),
  819. current_user: dict = Depends(require_admin),
  820. ):
  821. """上传用户头像图片,返回可写入 avatarUrl 的地址"""
  822. try:
  823. content = await validate_file(file, MAX_IMAGE_SIZE, ALLOWED_IMAGE_TYPES)
  824. original_filename = file.filename or "avatar.png"
  825. url = storage.upload_file(content, original_filename, folder)
  826. return success_response({"url": url})
  827. except HTTPException:
  828. raise
  829. except Exception as e:
  830. return error_response(500, f"上传失败: {str(e)}")
  831. @router.post("/users/{user_id}/reset-password", response_model=dict)
  832. def reset_user_password(
  833. user_id: str,
  834. request: Request,
  835. db: Session = Depends(get_db),
  836. current_user: dict = Depends(require_admin)
  837. ):
  838. """重置用户密码为服务端固定默认(明文不由请求传入,响应中也不返回密码)"""
  839. try:
  840. success = user_crud.reset_password_to_admin_default(db, user_id)
  841. except ValueError as e:
  842. return error_response(400, str(e))
  843. if not success:
  844. return error_response(404, "用户不存在")
  845. ip_address = get_client_ip(request)
  846. password_history_crud.create_password_history(
  847. db,
  848. user_id=user_id,
  849. operation_type="reset",
  850. operator_id=current_user.get("user_id"),
  851. operator_name=current_user.get("real_name"),
  852. ip_address=ip_address
  853. )
  854. return success_response({"ok": True})
  855. @router.get("/users/{user_id}/password-history", response_model=dict)
  856. def get_user_password_history(
  857. user_id: str,
  858. page: int = Query(1, ge=1, description="页码"),
  859. page_size: int = Query(10, ge=1, le=50, description="每页条数"),
  860. db: Session = Depends(get_db),
  861. current_user: dict = Depends(require_admin)
  862. ):
  863. """获取用户密码修改历史记录"""
  864. try:
  865. from app.models.models import SysPasswordHistory
  866. query = db.query(SysPasswordHistory).filter(
  867. SysPasswordHistory.user_id == user_id,
  868. SysPasswordHistory.is_del == 0
  869. )
  870. total = query.count()
  871. items = query.order_by(SysPasswordHistory.create_at.desc()).offset((page - 1) * page_size).limit(page_size).all()
  872. result = []
  873. for item in items:
  874. result.append({
  875. "id": item.id,
  876. "userId": item.user_id,
  877. "operationType": item.operation_type,
  878. "operationTypeText": "重置密码" if item.operation_type == "reset" else "修改密码" if item.operation_type == "change" else item.operation_type,
  879. "operatorName": item.operator_name,
  880. "operatorId": item.operator_id,
  881. "ipAddress": item.ip_address,
  882. "createAt": str(item.create_at) if item.create_at else None
  883. })
  884. return success_response({
  885. "list": result,
  886. "total": total,
  887. "page": page,
  888. "pageSize": page_size
  889. })
  890. except Exception as e:
  891. return error_response(500, f"获取密码历史失败: {str(e)}")
  892. @router.get("/password-history", response_model=dict)
  893. def get_password_history_list(
  894. page: int = Query(1, ge=1, description="页码"),
  895. page_size: int = Query(10, ge=1, le=50, description="每页条数"),
  896. user_id: str = Query(None, description="用户ID"),
  897. operation_type: str = Query(None, description="操作类型"),
  898. keyword: str = Query(None, description="关键词搜索"),
  899. db: Session = Depends(get_db),
  900. current_user: dict = Depends(require_admin)
  901. ):
  902. """获取密码修改历史记录列表(后台管理用)"""
  903. try:
  904. from app.models.models import SysPasswordHistory
  905. query = db.query(SysPasswordHistory).filter(SysPasswordHistory.is_del == 0)
  906. if user_id:
  907. query = query.filter(SysPasswordHistory.user_id == user_id)
  908. if operation_type:
  909. query = query.filter(SysPasswordHistory.operation_type == operation_type)
  910. if keyword:
  911. query = query.filter(SysPasswordHistory.operator_name.like(f"%{keyword}%"))
  912. total = query.count()
  913. items = query.order_by(SysPasswordHistory.create_at.desc()).offset((page - 1) * page_size).limit(page_size).all()
  914. result = []
  915. for item in items:
  916. # 获取用户信息
  917. user_info = {}
  918. user = user_crud.get(db, item.user_id)
  919. if user:
  920. user_info = {
  921. "userName": user.username,
  922. "realName": user.real_name,
  923. "role": user.role
  924. }
  925. result.append({
  926. "id": item.id,
  927. "userId": item.user_id,
  928. "userInfo": user_info,
  929. "operationType": item.operation_type,
  930. "operationTypeText": "重置密码" if item.operation_type == "reset" else "修改密码" if item.operation_type == "change" else item.operation_type,
  931. "operatorName": item.operator_name,
  932. "operatorId": item.operator_id,
  933. "ipAddress": item.ip_address,
  934. "createAt": str(item.create_at) if item.create_at else None
  935. })
  936. return success_response({
  937. "list": result,
  938. "total": total,
  939. "page": page,
  940. "pageSize": page_size
  941. })
  942. except Exception as e:
  943. return error_response(500, f"获取密码历史失败: {str(e)}")
  944. @router.post("/users/change-password", response_model=dict)
  945. def change_password(
  946. body: dict,
  947. request: Request,
  948. db: Session = Depends(get_db),
  949. current_user: dict = Depends(get_current_user)
  950. ):
  951. """用户修改密码"""
  952. old_password = body.get("oldPassword")
  953. new_password = body.get("newPassword")
  954. if not old_password or not new_password:
  955. return error_response(400, "旧密码和新密码都不能为空")
  956. if len(new_password) < 6:
  957. return error_response(400, "新密码长度不能少于6位")
  958. user = user_crud.get(db, current_user.get("user_id"))
  959. if not user:
  960. return error_response(404, "用户不存在")
  961. if not verify_password(old_password, user.password_hash):
  962. return error_response(400, "旧密码错误")
  963. user.password_hash = get_password_hash(new_password)
  964. db.commit()
  965. ip_address = get_client_ip(request)
  966. password_history_crud.create_password_history(
  967. db,
  968. user_id=user.id,
  969. operation_type="modify",
  970. operator_id=user.id,
  971. operator_name=user.real_name,
  972. ip_address=ip_address
  973. )
  974. return success_response({"message": "密码修改成功"})
  975. # ============ 商品管理 ============
  976. @router.get("/products", response_model=dict)
  977. def list_products(
  978. page: int = Query(1, ge=1, description="页码"),
  979. pageSize: int = Query(10, ge=1, le=1000, description="每页条数"),
  980. categoryId: Optional[str] = Query(None, description="分类ID"),
  981. keyword: Optional[str] = Query(None, description="关键词搜索"),
  982. isActive: Optional[bool] = Query(None, description="是否启用"),
  983. db: Session = Depends(get_db),
  984. current_user: dict = Depends(require_admin)
  985. ):
  986. """获取商品列表"""
  987. products, total = product_crud.get_multi_with_filters(
  988. db,
  989. category_id=categoryId,
  990. keyword=keyword,
  991. is_active=isActive,
  992. skip=(page - 1) * pageSize,
  993. limit=pageSize
  994. )
  995. # 获取分类和单位名称映射
  996. category_map = {}
  997. unit_map = {}
  998. for p in products:
  999. if p.category_id and p.category_id not in category_map:
  1000. cat = category_crud.get(db, p.category_id)
  1001. if cat:
  1002. category_map[p.category_id] = cat.name
  1003. if p.unit_id and p.unit_id not in unit_map:
  1004. u = unit_crud.get(db, p.unit_id)
  1005. if u:
  1006. unit_map[p.unit_id] = u.name
  1007. return success_response({
  1008. "list": [{
  1009. "id": p.id,
  1010. "name": p.name,
  1011. "skuCode": p.sku_code,
  1012. "categoryId": p.category_id,
  1013. "categoryName": category_map.get(p.category_id),
  1014. "unitId": p.unit_id,
  1015. "unitName": unit_map.get(p.unit_id),
  1016. "measureValue": _numeric_to_float_optional(getattr(p, "measure_value", None)),
  1017. "description": p.description,
  1018. "detailContent": p.detail_content,
  1019. "imageUrl": p.image_url,
  1020. "priceCoefficient": _numeric_to_float_optional(getattr(p, "price_coefficient", None)) or 0.0,
  1021. "isActive": p.is_active,
  1022. "createAt": str(p.create_at) if p.create_at else None
  1023. } for p in products],
  1024. "total": total,
  1025. "page": page,
  1026. "pageSize": pageSize,
  1027. "totalPages": (total + pageSize - 1) // pageSize
  1028. })
  1029. @router.get("/products/{product_id}", response_model=dict)
  1030. def get_product(
  1031. product_id: str,
  1032. db: Session = Depends(get_db),
  1033. current_user: dict = Depends(require_admin)
  1034. ):
  1035. """获取商品详情"""
  1036. product = product_crud.get(db, product_id)
  1037. if not product:
  1038. return error_response(404, "商品不存在")
  1039. category_name = None
  1040. if product.category_id:
  1041. cat = category_crud.get(db, product.category_id)
  1042. category_name = cat.name if cat else None
  1043. unit_name = None
  1044. if product.unit_id:
  1045. u = unit_crud.get(db, product.unit_id)
  1046. unit_name = u.name if u else None
  1047. return success_response({
  1048. "id": product.id,
  1049. "name": product.name,
  1050. "skuCode": product.sku_code,
  1051. "categoryId": product.category_id,
  1052. "categoryName": category_name,
  1053. "unitId": product.unit_id,
  1054. "unitName": unit_name,
  1055. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)),
  1056. "description": product.description,
  1057. "detailContent": product.detail_content,
  1058. "imageUrl": product.image_url,
  1059. "priceCoefficient": _numeric_to_float_optional(getattr(product, "price_coefficient", None)) or 0.0,
  1060. "isActive": product.is_active,
  1061. "createAt": str(product.create_at) if product.create_at else None
  1062. })
  1063. @router.get("/products/{product_id}/region-prices", response_model=dict)
  1064. def get_product_region_prices(
  1065. product_id: str,
  1066. db: Session = Depends(get_db),
  1067. current_user: dict = Depends(require_admin)
  1068. ):
  1069. """各启用区域下,当前生效价格清单中该商品的单价(无生效价则 price 为空)"""
  1070. from app.crud.price_list import price_list_item_crud
  1071. product = product_crud.get(db, product_id)
  1072. if not product:
  1073. return error_response(404, "商品不存在")
  1074. regions = region_crud.get_active_all(db)
  1075. admin_region_id = get_admin_region_filter(db, current_user)
  1076. if admin_region_id:
  1077. regions = [r for r in regions if r.id == admin_region_id]
  1078. rows = []
  1079. for r in regions:
  1080. item = price_list_item_crud.get_product_price(db, r.id, product_id)
  1081. if item:
  1082. unit_name = None
  1083. if item.unit_id:
  1084. u = unit_crud.get(db, item.unit_id)
  1085. unit_name = u.name if u else None
  1086. rows.append({
  1087. "regionId": r.id,
  1088. "regionName": r.name,
  1089. "price": float(item.price) if item.price is not None else None,
  1090. "unitId": item.unit_id,
  1091. "unitName": unit_name
  1092. })
  1093. else:
  1094. rows.append({
  1095. "regionId": r.id,
  1096. "regionName": r.name,
  1097. "price": None,
  1098. "unitId": None,
  1099. "unitName": None
  1100. })
  1101. return success_response({"list": rows})
  1102. @router.post("/products", response_model=dict)
  1103. def create_product(
  1104. request: dict,
  1105. db: Session = Depends(get_db),
  1106. current_user: dict = Depends(require_admin)
  1107. ):
  1108. """创建商品"""
  1109. creator = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  1110. try:
  1111. product = product_crud.create(db, request, creator)
  1112. except IntegrityError as e:
  1113. db.rollback()
  1114. err = str(getattr(e.orig, "args", e) or e)
  1115. if "uk_sku_code" in err or "sku_code" in err.lower():
  1116. return error_response(400, "SKU 编码已存在,请修改或点击「自动生成」")
  1117. raise
  1118. return success_response({
  1119. "id": product.id,
  1120. "name": product.name
  1121. })
  1122. @router.post("/products/upload-image", response_model=dict)
  1123. async def upload_product_image(
  1124. file: UploadFile = File(...),
  1125. db: Session = Depends(get_db),
  1126. current_user: dict = Depends(require_admin)
  1127. ):
  1128. """上传商品图片/轮播图(支持图片和视频)"""
  1129. try:
  1130. # 验证文件类型
  1131. allowed_image_types = {"image/jpeg", "image/png", "image/gif", "image/webp", "image/heic", "image/heif"}
  1132. allowed_video_types = {"video/mp4", "video/quicktime", "video/webm", "video/x-msvideo"}
  1133. allowed_types = allowed_image_types | allowed_video_types
  1134. if file.content_type not in allowed_types:
  1135. return error_response(400, "不支持的文件格式,支持:JPG、PNG、GIF、WebP、HEIC、MP4")
  1136. # 验证文件大小 (图片10MB,视频100MB)
  1137. max_size = 100 * 1024 * 1024 if file.content_type.startswith("video/") else 10 * 1024 * 1024
  1138. content = b""
  1139. chunk_size = 1024 * 1024
  1140. while True:
  1141. chunk = await file.read(chunk_size)
  1142. if not chunk:
  1143. break
  1144. content += chunk
  1145. if len(content) > max_size:
  1146. return error_response(400, f"{'视频' if file.content_type.startswith('video/') else '图片'}大小不能超过{'100MB' if file.content_type.startswith('video/') else '10MB'}")
  1147. await file.seek(0)
  1148. # 确定文件后缀和上传目录
  1149. if file.content_type.startswith("video/"):
  1150. ext = "mp4" if file.content_type == "video/mp4" else "mov" if file.content_type == "video/quicktime" else "webm" if file.content_type == "video/webm" else "avi"
  1151. folder = "products/banners"
  1152. filename = f"video_{uuid.uuid4().hex[:8]}.{ext}"
  1153. else:
  1154. ext = file.filename.rsplit(".", 1)[-1] if "." in (file.filename or "") else "jpg"
  1155. folder = "products"
  1156. filename = file.filename or f"image_{uuid.uuid4().hex[:8]}.{ext}"
  1157. # 上传文件
  1158. url = storage.upload_file(content, filename, folder)
  1159. return success_response({
  1160. "url": url,
  1161. "filename": file.filename,
  1162. "contentType": file.content_type,
  1163. "size": len(content)
  1164. })
  1165. except Exception as e:
  1166. return error_response(500, f"上传失败: {str(e)}")
  1167. @router.post("/products/upload-base64", response_model=dict)
  1168. async def upload_product_image_base64(
  1169. data: dict,
  1170. db: Session = Depends(get_db),
  1171. current_user: dict = Depends(require_admin)
  1172. ):
  1173. """上传商品图片(Base64方式)"""
  1174. try:
  1175. base64_data = data.get("base64")
  1176. if not base64_data:
  1177. return error_response(400, "base64数据不能为空")
  1178. # 去除前缀
  1179. if "," in base64_data:
  1180. base64_data = base64_data.split(",")[1]
  1181. # 验证图片大小
  1182. decoded_len = len(base64_data) * 3 // 4
  1183. if decoded_len > 5 * 1024 * 1024:
  1184. return error_response(400, "图片大小不能超过5MB")
  1185. url = storage.upload_base64(base64_data, "product.png", "products")
  1186. return success_response({
  1187. "url": url,
  1188. "filename": "product.png"
  1189. })
  1190. except Exception as e:
  1191. return error_response(500, f"上传失败: {str(e)}")
  1192. @router.put("/products/{product_id}", response_model=dict)
  1193. def update_product(
  1194. product_id: str,
  1195. request: dict,
  1196. db: Session = Depends(get_db),
  1197. current_user: dict = Depends(require_admin)
  1198. ):
  1199. """更新商品"""
  1200. updater = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  1201. product = product_crud.update_with_history(db, product_id, request, updater)
  1202. if not product:
  1203. return error_response(404, "商品不存在")
  1204. return success_response({
  1205. "id": product.id,
  1206. "name": product.name,
  1207. "skuCode": product.sku_code,
  1208. "categoryId": product.category_id,
  1209. "unitId": product.unit_id,
  1210. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)),
  1211. "description": product.description,
  1212. "detailContent": product.detail_content,
  1213. "imageUrl": product.image_url,
  1214. "priceCoefficient": _numeric_to_float_optional(getattr(product, "price_coefficient", None)) or 0.0,
  1215. "isActive": product.is_active
  1216. })
  1217. @router.delete("/products/{product_id}", response_model=dict)
  1218. def delete_product(
  1219. product_id: str,
  1220. db: Session = Depends(get_db),
  1221. current_user: dict = Depends(require_admin)
  1222. ):
  1223. """删除商品"""
  1224. success = product_crud.soft_delete_with_history(db, product_id)
  1225. if not success:
  1226. return error_response(404, "商品不存在")
  1227. return success_response({"id": product_id})
  1228. # ============ 询价单管理 ============
  1229. @router.get("/inquiries", response_model=dict)
  1230. def list_inquiries(
  1231. page: int = Query(1, ge=1, description="页码"),
  1232. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  1233. regionId: Optional[str] = Query(None, description="区域ID"),
  1234. status: Optional[str] = Query(None, description="状态: draft/published/closed"),
  1235. keyword: Optional[str] = Query(None, description="关键词搜索"),
  1236. db: Session = Depends(get_db),
  1237. current_user: dict = Depends(require_admin)
  1238. ):
  1239. """获取询价单列表"""
  1240. from app.crud.inquiry import inquiry_crud
  1241. # 区域管理员只能查看自己区域的询价单
  1242. admin_region_id = get_admin_region_filter(db, current_user)
  1243. if admin_region_id and not regionId:
  1244. regionId = admin_region_id
  1245. elif admin_region_id and regionId != admin_region_id:
  1246. return success_response({
  1247. "list": [],
  1248. "total": 0,
  1249. "page": page,
  1250. "pageSize": pageSize,
  1251. "totalPages": 0
  1252. })
  1253. inquiries, total = inquiry_crud.get_multi_with_filters(
  1254. db,
  1255. region_id=regionId,
  1256. status=status,
  1257. keyword=keyword,
  1258. skip=(page - 1) * pageSize,
  1259. limit=pageSize
  1260. )
  1261. region_map = {}
  1262. for inquiry in inquiries:
  1263. if inquiry.region_id and inquiry.region_id not in region_map:
  1264. region = region_crud.get(db, inquiry.region_id)
  1265. if region:
  1266. region_map[inquiry.region_id] = region.name
  1267. return success_response({
  1268. "list": [{
  1269. "id": i.id,
  1270. "regionId": i.region_id,
  1271. "regionName": region_map.get(i.region_id),
  1272. "title": i.title,
  1273. "status": i.status,
  1274. "publishTime": str(i.publish_time) if i.publish_time else None,
  1275. "closeTime": str(i.close_time) if i.close_time else None,
  1276. "remark": i.remark,
  1277. "createAt": str(i.create_at) if i.create_at else None,
  1278. "createName": i.create_name
  1279. } for i in inquiries],
  1280. "total": total,
  1281. "page": page,
  1282. "pageSize": pageSize,
  1283. "totalPages": (total + pageSize - 1) // pageSize
  1284. })
  1285. @router.get("/inquiries/{inquiry_id}", response_model=dict)
  1286. def get_inquiry(
  1287. inquiry_id: str,
  1288. db: Session = Depends(get_db),
  1289. current_user: dict = Depends(require_admin)
  1290. ):
  1291. """获取询价单详情"""
  1292. from app.crud.inquiry import inquiry_crud, inquiry_item_crud
  1293. from app.crud.product import product_crud
  1294. inquiry = inquiry_crud.get(db, inquiry_id)
  1295. if not inquiry:
  1296. return error_response(404, "询价单不存在")
  1297. items = inquiry_item_crud.get_by_inquiry(db, inquiry_id)
  1298. region_name = None
  1299. if inquiry.region_id:
  1300. region = region_crud.get(db, inquiry.region_id)
  1301. region_name = region.name if region else None
  1302. item_details = []
  1303. for item in items:
  1304. product = product_crud.get(db, item.product_id)
  1305. category_name = None
  1306. if product and product.category_id:
  1307. cat = category_crud.get(db, product.category_id)
  1308. category_name = cat.name if cat else None
  1309. unit_name = None
  1310. if product and product.unit_id:
  1311. u = unit_crud.get(db, product.unit_id)
  1312. unit_name = u.name if u else None
  1313. item_details.append({
  1314. "id": item.id,
  1315. "productId": item.product_id,
  1316. "productName": product.name if product else None,
  1317. "categoryId": product.category_id if product else None,
  1318. "categoryName": category_name,
  1319. "unitName": unit_name,
  1320. "description": product.description if product else None,
  1321. "imageUrl": product.image_url if product else None,
  1322. "createAt": str(item.create_at) if item.create_at else None
  1323. })
  1324. return success_response({
  1325. "id": inquiry.id,
  1326. "regionId": inquiry.region_id,
  1327. "regionName": region_name,
  1328. "title": inquiry.title,
  1329. "status": inquiry.status,
  1330. "publishTime": str(inquiry.publish_time) if inquiry.publish_time else None,
  1331. "closeTime": str(inquiry.close_time) if inquiry.close_time else None,
  1332. "remark": inquiry.remark,
  1333. "createAt": str(inquiry.create_at) if inquiry.create_at else None,
  1334. "createName": inquiry.create_name,
  1335. "items": item_details
  1336. })
  1337. @router.post("/inquiries", response_model=dict)
  1338. def create_inquiry(
  1339. request: dict,
  1340. db: Session = Depends(get_db),
  1341. current_user: dict = Depends(require_admin)
  1342. ):
  1343. """创建询价单"""
  1344. from app.crud.inquiry import inquiry_crud, inquiry_item_crud
  1345. creator = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  1346. inquiry_data = {
  1347. "region_id": request.get("regionId"),
  1348. "title": request.get("title"),
  1349. "remark": request.get("remark"),
  1350. "status": "draft"
  1351. }
  1352. inquiry = inquiry_crud.create(db, inquiry_data, creator)
  1353. product_ids = request.get("productIds", [])
  1354. if product_ids:
  1355. inquiry_item_crud.create_items(db, inquiry.id, product_ids, creator)
  1356. region_name = None
  1357. if inquiry.region_id:
  1358. region = region_crud.get(db, inquiry.region_id)
  1359. region_name = region.name if region else None
  1360. return success_response({
  1361. "id": inquiry.id,
  1362. "regionId": inquiry.region_id,
  1363. "regionName": region_name,
  1364. "title": inquiry.title,
  1365. "status": inquiry.status
  1366. })
  1367. @router.put("/inquiries/{inquiry_id}", response_model=dict)
  1368. def update_inquiry(
  1369. inquiry_id: str,
  1370. request: dict,
  1371. db: Session = Depends(get_db),
  1372. current_user: dict = Depends(require_admin)
  1373. ):
  1374. """更新询价单"""
  1375. from app.crud.inquiry import inquiry_crud, inquiry_item_crud
  1376. inquiry = inquiry_crud.get(db, inquiry_id)
  1377. if not inquiry:
  1378. return error_response(404, "询价单不存在")
  1379. if inquiry.status != "draft":
  1380. return error_response(400, "只能编辑草稿状态的询价单")
  1381. updater = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  1382. update_data = {}
  1383. if "title" in request:
  1384. update_data["title"] = request["title"]
  1385. if "remark" in request:
  1386. update_data["remark"] = request["remark"]
  1387. if update_data:
  1388. inquiry = inquiry_crud.update_with_history(db, inquiry_id, update_data, updater)
  1389. if "productIds" in request:
  1390. inquiry_item_crud.update_items(db, inquiry_id, request["productIds"], updater)
  1391. region_name = None
  1392. if inquiry.region_id:
  1393. region = region_crud.get(db, inquiry.region_id)
  1394. region_name = region.name if region else None
  1395. return success_response({
  1396. "id": inquiry.id,
  1397. "regionId": inquiry.region_id,
  1398. "regionName": region_name,
  1399. "title": inquiry.title,
  1400. "status": inquiry.status
  1401. })
  1402. @router.delete("/inquiries/{inquiry_id}", response_model=dict)
  1403. def delete_inquiry(
  1404. inquiry_id: str,
  1405. db: Session = Depends(get_db),
  1406. current_user: dict = Depends(require_admin)
  1407. ):
  1408. """删除询价单"""
  1409. from app.crud.inquiry import inquiry_crud, inquiry_item_crud
  1410. inquiry = inquiry_crud.get(db, inquiry_id)
  1411. if not inquiry:
  1412. return error_response(404, "询价单不存在")
  1413. if inquiry.status == "published":
  1414. return error_response(400, "已发布的询价单不能删除")
  1415. inquiry_item_crud.delete_by_inquiry(db, inquiry_id)
  1416. inquiry_crud.soft_delete_with_history(db, inquiry_id)
  1417. return success_response({"id": inquiry_id})
  1418. @router.post("/inquiries/{inquiry_id}/publish", response_model=dict)
  1419. def publish_inquiry(
  1420. inquiry_id: str,
  1421. db: Session = Depends(get_db),
  1422. current_user: dict = Depends(require_admin)
  1423. ):
  1424. """发布询价单"""
  1425. from app.crud.inquiry import inquiry_crud, inquiry_item_crud
  1426. from app.models.models import BizInquiry
  1427. from sqlalchemy import and_
  1428. inquiry = inquiry_crud.get(db, inquiry_id)
  1429. if not inquiry:
  1430. return error_response(404, "询价单不存在")
  1431. if inquiry.status != "draft":
  1432. return error_response(400, "只能发布草稿状态的询价单")
  1433. items = inquiry_item_crud.get_by_inquiry(db, inquiry_id)
  1434. if not items:
  1435. return error_response(400, "询价单必须包含至少一个商品")
  1436. # 同区域仅允许一个发布中的询价单(并发下尽量避免双发布)
  1437. try:
  1438. # 锁住同区域发布中的记录(若存在)与当前记录
  1439. db.query(BizInquiry).filter(
  1440. and_(
  1441. BizInquiry.region_id == inquiry.region_id,
  1442. BizInquiry.status == "published",
  1443. BizInquiry.is_del == 0
  1444. )
  1445. ).with_for_update().all()
  1446. db.query(BizInquiry).filter(BizInquiry.id == inquiry_id).with_for_update().all()
  1447. except Exception:
  1448. # with_for_update 在某些配置下可能不生效,但不影响基本校验
  1449. pass
  1450. existing = inquiry_crud.get_current_published_by_region(db, inquiry.region_id)
  1451. if existing and existing.id != inquiry_id:
  1452. return error_response(400, "该区域已存在发布中的询价单,请先取消发布当前询价单后再发布新的询价单")
  1453. inquiry = inquiry_crud.publish(db, inquiry_id)
  1454. return success_response({
  1455. "id": inquiry.id,
  1456. "status": inquiry.status,
  1457. "publishTime": str(inquiry.publish_time) if inquiry.publish_time else None
  1458. })
  1459. @router.post("/inquiries/{inquiry_id}/unpublish", response_model=dict)
  1460. def unpublish_inquiry(
  1461. inquiry_id: str,
  1462. db: Session = Depends(get_db),
  1463. current_user: dict = Depends(require_admin)
  1464. ):
  1465. """取消发布询价单(published -> draft)"""
  1466. from app.crud.inquiry import inquiry_crud
  1467. inquiry = inquiry_crud.get(db, inquiry_id)
  1468. if not inquiry:
  1469. return error_response(404, "询价单不存在")
  1470. if inquiry.status != "published":
  1471. return error_response(400, "只能取消发布已发布状态的询价单")
  1472. inquiry = inquiry_crud.unpublish(db, inquiry_id)
  1473. return success_response({
  1474. "id": inquiry.id,
  1475. "status": inquiry.status
  1476. })
  1477. @router.post("/inquiries/{inquiry_id}/close", response_model=dict)
  1478. def close_inquiry(
  1479. inquiry_id: str,
  1480. db: Session = Depends(get_db),
  1481. current_user: dict = Depends(require_admin)
  1482. ):
  1483. """关闭询价单"""
  1484. from app.crud.inquiry import inquiry_crud
  1485. inquiry = inquiry_crud.get(db, inquiry_id)
  1486. if not inquiry:
  1487. return error_response(404, "询价单不存在")
  1488. if inquiry.status != "published":
  1489. return error_response(400, "只能关闭已发布的询价单")
  1490. inquiry = inquiry_crud.close(db, inquiry_id)
  1491. return success_response({
  1492. "id": inquiry.id,
  1493. "status": inquiry.status,
  1494. "closeTime": str(inquiry.close_time) if inquiry.close_time else None
  1495. })
  1496. # ============ 报价管理(无审批) ============
  1497. @router.get("/quotations", response_model=dict)
  1498. def list_quotations(
  1499. page: int = Query(1, ge=1, description="页码"),
  1500. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  1501. inquiryId: Optional[str] = Query(None, description="询价单ID"),
  1502. regionId: Optional[str] = Query(None, description="区域ID"),
  1503. status: Optional[str] = Query(None, description="状态: submitted/selected"),
  1504. db: Session = Depends(get_db),
  1505. current_user: dict = Depends(require_admin)
  1506. ):
  1507. """获取报价单列表"""
  1508. from app.crud.quotation import quotation_crud, quotation_item_crud
  1509. from app.crud.inquiry import inquiry_crud
  1510. from app.crud.user import user_crud
  1511. # 区域管理员只能查看自己区域的报价单
  1512. admin_region_id = get_admin_region_filter(db, current_user)
  1513. if admin_region_id and not regionId:
  1514. regionId = admin_region_id
  1515. elif admin_region_id and regionId != admin_region_id:
  1516. return success_response({
  1517. "list": [],
  1518. "total": 0,
  1519. "page": page,
  1520. "pageSize": pageSize,
  1521. "totalPages": 0
  1522. })
  1523. quotations, total = quotation_crud.get_multi_with_filters(
  1524. db,
  1525. inquiry_id=inquiryId,
  1526. region_id=regionId,
  1527. status=status,
  1528. skip=(page - 1) * pageSize,
  1529. limit=pageSize
  1530. )
  1531. region_map = {}
  1532. inquiry_map = {}
  1533. supplier_map = {}
  1534. for q in quotations:
  1535. if q.region_id and q.region_id not in region_map:
  1536. region = region_crud.get(db, q.region_id)
  1537. region_map[q.region_id] = region.name if region else None
  1538. if q.inquiry_id and q.inquiry_id not in inquiry_map:
  1539. inquiry = inquiry_crud.get(db, q.inquiry_id)
  1540. inquiry_map[q.inquiry_id] = inquiry.title if inquiry else None
  1541. if q.supplier_id and q.supplier_id not in supplier_map:
  1542. supplier = user_crud.get(db, q.supplier_id)
  1543. supplier_map[q.supplier_id] = supplier.real_name if supplier else None
  1544. return success_response({
  1545. "list": [{
  1546. "id": q.id,
  1547. "inquiryId": q.inquiry_id,
  1548. "inquiryTitle": inquiry_map.get(q.inquiry_id),
  1549. "supplierId": q.supplier_id,
  1550. "supplierName": supplier_map.get(q.supplier_id),
  1551. "regionId": q.region_id,
  1552. "regionName": region_map.get(q.region_id),
  1553. "status": q.status,
  1554. "totalAmount": float(q.total_amount) if q.total_amount else 0,
  1555. "submitTime": str(q.submit_time) if q.submit_time else None,
  1556. "createAt": str(q.create_at) if q.create_at else None
  1557. } for q in quotations],
  1558. "total": total,
  1559. "page": page,
  1560. "pageSize": pageSize,
  1561. "totalPages": (total + pageSize - 1) // pageSize
  1562. })
  1563. @router.get("/quotations/{quotation_id}", response_model=dict)
  1564. def get_quotation(
  1565. quotation_id: str,
  1566. db: Session = Depends(get_db),
  1567. current_user: dict = Depends(require_admin)
  1568. ):
  1569. """获取报价单详情"""
  1570. from app.crud.quotation import quotation_crud, quotation_item_crud
  1571. from app.crud.inquiry import inquiry_crud
  1572. from app.crud.user import user_crud
  1573. from app.crud.product import product_crud
  1574. from app.crud.category import category_crud
  1575. from app.models.models import BizPriceList, BizPriceListItem, BizInquiryItem
  1576. from sqlalchemy import and_
  1577. quotation = quotation_crud.get(db, quotation_id)
  1578. if not quotation:
  1579. return error_response(404, "报价单不存在")
  1580. # 询价单商品作为主表,确保供应商未报价商品也能展示
  1581. inquiry_items = db.query(BizInquiryItem).filter(
  1582. and_(
  1583. BizInquiryItem.inquiry_id == quotation.inquiry_id,
  1584. BizInquiryItem.is_del == 0
  1585. )
  1586. ).order_by(BizInquiryItem.create_at.asc()).all()
  1587. # 报价单项作为从表(按 product_id 映射)
  1588. items = quotation_item_crud.get_by_quotation(db, quotation_id)
  1589. q_item_by_pid: dict[str, object] = {}
  1590. for it in items:
  1591. pid = str(getattr(it, "product_id", "") or "")
  1592. if pid and pid not in q_item_by_pid:
  1593. q_item_by_pid[pid] = it
  1594. # 若该报价已被选中并生成价格清单,则回显调价系数/最终售价(用于运营端查看)
  1595. pl = db.query(BizPriceList).filter(
  1596. and_(
  1597. BizPriceList.quotation_id == quotation_id,
  1598. BizPriceList.is_del == 0
  1599. )
  1600. ).order_by(BizPriceList.version.desc(), BizPriceList.published_time.desc()).first()
  1601. # key: product_id, value: pricing_coefficient(%) used at publish-time
  1602. # NOTE: older price lists may have NULL pricing_coefficient; we keep None to allow fallback to product.price_coefficient.
  1603. coeff_map: dict[str, Optional[float]] = {}
  1604. final_price_map: dict[str, float] = {}
  1605. if pl:
  1606. pl_items = db.query(BizPriceListItem).filter(
  1607. and_(
  1608. BizPriceListItem.price_list_id == pl.id,
  1609. BizPriceListItem.is_del == 0
  1610. )
  1611. ).all()
  1612. for pit in pl_items:
  1613. pid = str(pit.product_id or "")
  1614. if not pid:
  1615. continue
  1616. coeff_map[pid] = float(pit.pricing_coefficient) if getattr(pit, "pricing_coefficient", None) is not None else None
  1617. final_price_map[pid] = float(pit.price) if pit.price else 0
  1618. region_name = None
  1619. if quotation.region_id:
  1620. region = region_crud.get(db, quotation.region_id)
  1621. region_name = region.name if region else None
  1622. inquiry_title = None
  1623. if quotation.inquiry_id:
  1624. inquiry = inquiry_crud.get(db, quotation.inquiry_id)
  1625. inquiry_title = inquiry.title if inquiry else None
  1626. supplier_name = None
  1627. supplier_phone = None
  1628. if quotation.supplier_id:
  1629. supplier = user_crud.get(db, quotation.supplier_id)
  1630. if supplier:
  1631. supplier_name = supplier.real_name
  1632. supplier_phone = supplier.phone
  1633. item_details = []
  1634. for inq_item in inquiry_items:
  1635. pid = str(getattr(inq_item, "product_id", "") or "")
  1636. q_item = q_item_by_pid.get(pid)
  1637. product = product_crud.get(db, pid) if pid else None
  1638. default_coeff = _numeric_to_float_optional(getattr(product, "price_coefficient", None)) if product else None
  1639. default_coeff = float(default_coeff) if default_coeff is not None else 0.0
  1640. category_name = None
  1641. if product and getattr(product, "category_id", None):
  1642. category = category_crud.get(db, product.category_id)
  1643. category_name = category.name if category else None
  1644. unit_id = None
  1645. unit_name = None
  1646. # unit 优先取报价单项(更准确),否则回退商品默认 unit_id
  1647. if q_item and getattr(q_item, "unit_id", None):
  1648. unit_id = getattr(q_item, "unit_id", None)
  1649. elif product and getattr(product, "unit_id", None):
  1650. unit_id = getattr(product, "unit_id", None)
  1651. if unit_id:
  1652. u = unit_crud.get(db, unit_id)
  1653. unit_name = u.name if u else None
  1654. supplier_price = float(getattr(q_item, "price", 0) or 0) if q_item else 0
  1655. pricing_coeff = coeff_map.get(pid, None)
  1656. if pricing_coeff is None:
  1657. pricing_coeff = default_coeff
  1658. item_details.append({
  1659. "id": getattr(q_item, "id", None) if q_item else None,
  1660. "productId": pid,
  1661. "productName": product.name if product else None,
  1662. "imageUrl": getattr(product, "image_url", None) if product else None,
  1663. "categoryName": category_name,
  1664. "unitId": unit_id,
  1665. "unitName": unit_name,
  1666. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)) if product else None,
  1667. "supplierPrice": supplier_price,
  1668. "pricingCoefficient": pricing_coeff,
  1669. "finalPrice": final_price_map.get(pid, 0),
  1670. # 兼容旧前端字段:price 仍返回供应商报价
  1671. "price": supplier_price
  1672. })
  1673. return success_response({
  1674. "id": quotation.id,
  1675. "inquiryId": quotation.inquiry_id,
  1676. "inquiryTitle": inquiry_title,
  1677. "supplierId": quotation.supplier_id,
  1678. "supplierName": supplier_name,
  1679. "supplierPhone": supplier_phone,
  1680. "regionId": quotation.region_id,
  1681. "regionName": region_name,
  1682. "status": quotation.status,
  1683. "totalAmount": float(quotation.total_amount) if quotation.total_amount else 0,
  1684. "submitTime": str(quotation.submit_time) if quotation.submit_time else None,
  1685. "createAt": str(quotation.create_at) if quotation.create_at else None,
  1686. "items": item_details
  1687. })
  1688. # =========================================
  1689. # 询价单报价聚合查询(用于询价报价管理页)
  1690. # =========================================
  1691. @router.get("/inquiries/{inquiry_id}/quotations/latest-by-supplier", response_model=dict)
  1692. def list_latest_quotations_by_supplier(
  1693. inquiry_id: str,
  1694. db: Session = Depends(get_db),
  1695. current_user: dict = Depends(require_admin)
  1696. ):
  1697. """按询价单聚合:每个供应商最新一次报价(包含未报价供应商)"""
  1698. from app.models.models import BizInquiry, BizQuotation, SysUser, BizInquiryItem
  1699. from app.crud.quotation import quotation_item_crud
  1700. from sqlalchemy import and_
  1701. inquiry = db.query(BizInquiry).filter(and_(BizInquiry.id == inquiry_id, BizInquiry.is_del == 0)).first()
  1702. if not inquiry:
  1703. return error_response(404, "询价单不存在")
  1704. # 询价单商品作为主表:后续给每个供应商补齐这些商品行
  1705. inquiry_items = db.query(BizInquiryItem).filter(
  1706. and_(
  1707. BizInquiryItem.inquiry_id == inquiry_id,
  1708. BizInquiryItem.is_del == 0
  1709. )
  1710. ).order_by(BizInquiryItem.create_at.asc()).all()
  1711. # 该区域全部供应商(包含未报价)
  1712. suppliers = db.query(SysUser).filter(
  1713. and_(
  1714. SysUser.role == "supplier",
  1715. SysUser.region_id == inquiry.region_id,
  1716. SysUser.is_del == 0,
  1717. SysUser.is_active == True
  1718. )
  1719. ).order_by(SysUser.create_at.asc()).all()
  1720. # 查询该询价单下全部报价单,然后在内存中取每个供应商最新一条
  1721. quotations = db.query(BizQuotation).filter(
  1722. and_(
  1723. BizQuotation.inquiry_id == inquiry_id,
  1724. BizQuotation.is_del == 0
  1725. )
  1726. ).order_by(BizQuotation.create_at.desc()).all()
  1727. latest_by_supplier: dict[str, BizQuotation] = {}
  1728. for q in quotations:
  1729. if q.supplier_id not in latest_by_supplier:
  1730. latest_by_supplier[q.supplier_id] = q
  1731. # 组装返回:供应商维度 + 最新报价(如无则为空)
  1732. result = []
  1733. for s in suppliers:
  1734. q = latest_by_supplier.get(s.id)
  1735. quotation_items = []
  1736. q_item_by_pid: dict[str, object] = {}
  1737. if q:
  1738. items = quotation_item_crud.get_by_quotation(db, q.id)
  1739. for it in items:
  1740. pid = str(getattr(it, "product_id", "") or "")
  1741. if pid and pid not in q_item_by_pid:
  1742. q_item_by_pid[pid] = it
  1743. # LEFT JOIN:以询价单商品为主,补齐未报价商品
  1744. for inq_item in inquiry_items:
  1745. pid = str(getattr(inq_item, "product_id", "") or "")
  1746. it = q_item_by_pid.get(pid)
  1747. product = product_crud.get(db, pid) if pid else None
  1748. category_name = None
  1749. if product and getattr(product, "category_id", None):
  1750. cat = category_crud.get(db, product.category_id)
  1751. category_name = cat.name if cat else None
  1752. unit_id = None
  1753. unit_name = None
  1754. if it and getattr(it, "unit_id", None):
  1755. unit_id = getattr(it, "unit_id", None)
  1756. elif product and getattr(product, "unit_id", None):
  1757. unit_id = getattr(product, "unit_id", None)
  1758. if unit_id:
  1759. u = unit_crud.get(db, unit_id)
  1760. unit_name = u.name if u else None
  1761. price_val = None
  1762. if it is not None:
  1763. try:
  1764. price_val = float(getattr(it, "price", 0) or 0)
  1765. except Exception:
  1766. price_val = 0
  1767. quotation_items.append({
  1768. "id": getattr(it, "id", None) if it else None,
  1769. "productId": pid,
  1770. "productName": product.name if product else None,
  1771. "categoryName": category_name,
  1772. "unitId": unit_id,
  1773. "unitName": unit_name,
  1774. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)) if product else None,
  1775. "imageUrl": getattr(product, "image_url", None) if product else None,
  1776. # 没报价时保持 null,便于前端区分“未报价”与“0元”
  1777. "price": price_val
  1778. })
  1779. result.append({
  1780. "supplierId": s.id,
  1781. "supplierName": s.real_name or s.username,
  1782. "supplierPhone": s.phone,
  1783. # 即使供应商未报价,也返回 quotation.items(=询价单全部商品),用于前端完整展示商品行
  1784. "quotation": {
  1785. "id": q.id if q else None,
  1786. "status": q.status if q else None,
  1787. "totalAmount": float(q.total_amount) if (q and q.total_amount) else 0,
  1788. "submitTime": str(q.submit_time) if (q and q.submit_time) else None,
  1789. "createAt": str(q.create_at) if (q and q.create_at) else None,
  1790. "items": quotation_items
  1791. }
  1792. })
  1793. return success_response({
  1794. "inquiryId": inquiry_id,
  1795. "regionId": inquiry.region_id,
  1796. "list": result,
  1797. "total": len(result)
  1798. })
  1799. @router.get("/inquiries/{inquiry_id}/quotations/history", response_model=dict)
  1800. def list_quotation_history_by_inquiry(
  1801. inquiry_id: str,
  1802. page: int = Query(1, ge=1, description="页码"),
  1803. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  1804. supplierId: Optional[str] = Query(None, description="供应商ID"),
  1805. status: Optional[str] = Query(None, description="状态: submitted/selected"),
  1806. startDate: Optional[str] = Query(None, description="开始日期(ISO)"),
  1807. endDate: Optional[str] = Query(None, description="结束日期(ISO)"),
  1808. db: Session = Depends(get_db),
  1809. current_user: dict = Depends(require_admin)
  1810. ):
  1811. """按询价单查看全部报价单(第三个tab)"""
  1812. from app.models.models import BizQuotation, BizInquiry, BizQuotationItem, BizInquiryItem
  1813. from app.crud.quotation import quotation_crud
  1814. from app.crud.user import user_crud
  1815. from sqlalchemy import and_
  1816. from datetime import datetime
  1817. inquiry = db.query(BizInquiry).filter(and_(BizInquiry.id == inquiry_id, BizInquiry.is_del == 0)).first()
  1818. if not inquiry:
  1819. return error_response(404, "询价单不存在")
  1820. query = db.query(BizQuotation).filter(
  1821. and_(
  1822. BizQuotation.is_del == 0,
  1823. BizQuotation.inquiry_id == inquiry_id,
  1824. BizQuotation.region_id == inquiry.region_id
  1825. )
  1826. )
  1827. if supplierId:
  1828. query = query.filter(BizQuotation.supplier_id == supplierId)
  1829. if status:
  1830. query = query.filter(BizQuotation.status == status)
  1831. def _parse_dt(v: Optional[str]) -> Optional[datetime]:
  1832. if not v:
  1833. return None
  1834. try:
  1835. return datetime.fromisoformat(v.replace("Z", "+00:00"))
  1836. except Exception:
  1837. return None
  1838. sd = _parse_dt(startDate)
  1839. ed = _parse_dt(endDate)
  1840. if sd:
  1841. query = query.filter(BizQuotation.create_at >= sd)
  1842. if ed:
  1843. query = query.filter(BizQuotation.create_at <= ed)
  1844. total = query.count()
  1845. quotations = query.order_by(BizQuotation.create_at.desc()).offset((page - 1) * pageSize).limit(pageSize).all()
  1846. supplier_map = {}
  1847. for q in quotations:
  1848. if q.supplier_id and q.supplier_id not in supplier_map:
  1849. u = user_crud.get(db, q.supplier_id)
  1850. supplier_map[q.supplier_id] = u.real_name if u else None
  1851. q_ids = [q.id for q in quotations]
  1852. partial_ids: set[str] = set()
  1853. inquiry_pids = [
  1854. r[0]
  1855. for r in db.query(BizInquiryItem.product_id)
  1856. .filter(BizInquiryItem.inquiry_id == inquiry_id, BizInquiryItem.is_del == 0)
  1857. .all()
  1858. ]
  1859. expected = set(inquiry_pids)
  1860. if q_ids:
  1861. item_rows = (
  1862. db.query(BizQuotationItem.quotation_id, BizQuotationItem.product_id, BizQuotationItem.price)
  1863. .filter(BizQuotationItem.quotation_id.in_(q_ids), BizQuotationItem.is_del == 0)
  1864. .all()
  1865. )
  1866. by_quotation: dict[str, dict[str, object]] = {}
  1867. for qid, pid, price in item_rows:
  1868. by_quotation.setdefault(qid, {})[pid] = price
  1869. for qid in q_ids:
  1870. pmap = by_quotation.get(qid, {})
  1871. if expected:
  1872. for pid in expected:
  1873. pr = pmap.get(pid)
  1874. try:
  1875. pv = float(pr) if pr is not None else 0.0
  1876. except (TypeError, ValueError):
  1877. pv = 0.0
  1878. if pv <= 0:
  1879. partial_ids.add(qid)
  1880. break
  1881. else:
  1882. for pr in pmap.values():
  1883. try:
  1884. pv = float(pr) if pr is not None else 0.0
  1885. except (TypeError, ValueError):
  1886. pv = 0.0
  1887. if pv <= 0:
  1888. partial_ids.add(qid)
  1889. break
  1890. return success_response({
  1891. "list": [{
  1892. "id": q.id,
  1893. "inquiryId": q.inquiry_id,
  1894. "supplierId": q.supplier_id,
  1895. "supplierName": supplier_map.get(q.supplier_id),
  1896. "regionId": q.region_id,
  1897. "status": q.status,
  1898. "totalAmount": float(q.total_amount) if q.total_amount else 0,
  1899. "submitTime": str(q.submit_time) if q.submit_time else None,
  1900. "createAt": str(q.create_at) if q.create_at else None,
  1901. "partialPriceMissing": q.id in partial_ids
  1902. } for q in quotations],
  1903. "total": total,
  1904. "page": page,
  1905. "pageSize": pageSize,
  1906. "totalPages": (total + pageSize - 1) // pageSize
  1907. })
  1908. @router.get("/inquiries/{inquiry_id}/quotations/selected", response_model=dict)
  1909. def get_selected_quotation_for_inquiry(
  1910. inquiry_id: str,
  1911. db: Session = Depends(get_db),
  1912. current_user: dict = Depends(require_admin)
  1913. ):
  1914. """获取某询价单当前被选中的报价(若已生成价格清单,则从价格清单反查)"""
  1915. from app.models.models import BizInquiry, BizQuotation, BizPriceList, BizPriceListItem, BizQuotationItem, BizInquiryItem
  1916. from sqlalchemy import and_
  1917. from app.crud.user import user_crud
  1918. inquiry = db.query(BizInquiry).filter(and_(BizInquiry.id == inquiry_id, BizInquiry.is_del == 0)).first()
  1919. if not inquiry:
  1920. return error_response(404, "询价单不存在")
  1921. # 询价单商品清单(作为主表,确保完整展示)
  1922. inquiry_items = db.query(BizInquiryItem).filter(
  1923. and_(
  1924. BizInquiryItem.inquiry_id == inquiry_id,
  1925. BizInquiryItem.is_del == 0
  1926. )
  1927. ).order_by(BizInquiryItem.create_at.asc()).all()
  1928. # 优先从价格清单查来源(允许后续价格已被新的询价覆盖 active)
  1929. pl = db.query(BizPriceList).filter(
  1930. and_(
  1931. BizPriceList.inquiry_id == inquiry_id,
  1932. BizPriceList.is_del == 0
  1933. )
  1934. ).order_by(BizPriceList.version.desc(), BizPriceList.published_time.desc()).first()
  1935. if not pl:
  1936. # 兜底:直接查 selected 报价
  1937. q = db.query(BizQuotation).filter(
  1938. and_(
  1939. BizQuotation.inquiry_id == inquiry_id,
  1940. BizQuotation.status == "selected",
  1941. BizQuotation.is_del == 0
  1942. )
  1943. ).order_by(BizQuotation.create_at.desc()).first()
  1944. if not q:
  1945. # 未选择任何供应商报价时,也返回询价单商品清单(用于前端完整展示)
  1946. item_details = []
  1947. for inq_item in inquiry_items:
  1948. pid = str(getattr(inq_item, "product_id", "") or "")
  1949. product = product_crud.get(db, pid) if pid else None
  1950. default_coeff = _numeric_to_float_optional(getattr(product, "price_coefficient", None)) if product else None
  1951. default_coeff = float(default_coeff) if default_coeff is not None else 0.0
  1952. category_name = None
  1953. if product and getattr(product, "category_id", None):
  1954. cat = category_crud.get(db, product.category_id)
  1955. category_name = cat.name if cat else None
  1956. unit_id = getattr(product, "unit_id", None) if product else None
  1957. unit_name = None
  1958. if unit_id:
  1959. u = unit_crud.get(db, unit_id)
  1960. unit_name = u.name if u else None
  1961. item_details.append({
  1962. "productId": pid,
  1963. "productName": product.name if product else None,
  1964. "skuCode": getattr(product, "sku_code", None) if product else None,
  1965. "description": getattr(product, "description", None) if product else None,
  1966. "imageUrl": getattr(product, "image_url", None) if product else None,
  1967. "categoryName": category_name,
  1968. "unitId": unit_id,
  1969. "unitName": unit_name,
  1970. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)) if product else None,
  1971. # 未报价:返回 0 / 0,前端可按需展示为 '-'
  1972. "supplierPrice": 0,
  1973. "price": 0,
  1974. "pricingCoefficient": default_coeff
  1975. })
  1976. return success_response({
  1977. "quotationId": None,
  1978. "quotationCreateAt": None,
  1979. "quotationSubmitTime": None,
  1980. "supplierId": None,
  1981. "supplierName": None,
  1982. "supplierLogoUrl": None,
  1983. "items": item_details
  1984. })
  1985. supplier = user_crud.get(db, q.supplier_id) if q.supplier_id else None
  1986. # 兜底分支也补齐询价单商品行:supplierPrice 从报价项拿,最终售价未知则为 0
  1987. supplier_price_map: dict[str, float] = {}
  1988. q_items = db.query(BizQuotationItem).filter(
  1989. and_(BizQuotationItem.quotation_id == q.id, BizQuotationItem.is_del == 0)
  1990. ).all()
  1991. for qi in q_items:
  1992. if not qi.product_id:
  1993. continue
  1994. supplier_price_map[str(qi.product_id)] = float(qi.price) if qi.price else 0
  1995. item_details = []
  1996. for inq_item in inquiry_items:
  1997. pid = str(getattr(inq_item, "product_id", "") or "")
  1998. product = product_crud.get(db, pid) if pid else None
  1999. default_coeff = _numeric_to_float_optional(getattr(product, "price_coefficient", None)) if product else None
  2000. default_coeff = float(default_coeff) if default_coeff is not None else 0.0
  2001. category_name = None
  2002. if product and getattr(product, "category_id", None):
  2003. cat = category_crud.get(db, product.category_id)
  2004. category_name = cat.name if cat else None
  2005. unit_id = getattr(product, "unit_id", None) if product else None
  2006. unit_name = None
  2007. if unit_id:
  2008. u = unit_crud.get(db, unit_id)
  2009. unit_name = u.name if u else None
  2010. item_details.append({
  2011. "productId": pid,
  2012. "productName": product.name if product else None,
  2013. "skuCode": getattr(product, "sku_code", None) if product else None,
  2014. "description": getattr(product, "description", None) if product else None,
  2015. "imageUrl": getattr(product, "image_url", None) if product else None,
  2016. "categoryName": category_name,
  2017. "unitId": unit_id,
  2018. "unitName": unit_name,
  2019. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)) if product else None,
  2020. # 未报价商品返回 0(兜底分支无法区分 null/0;主流程会更准确)
  2021. "supplierPrice": supplier_price_map.get(pid, 0),
  2022. "price": 0,
  2023. "pricingCoefficient": default_coeff
  2024. })
  2025. return success_response({
  2026. "quotationId": q.id,
  2027. "quotationCreateAt": str(q.create_at) if getattr(q, "create_at", None) else None,
  2028. "quotationSubmitTime": str(q.submit_time) if getattr(q, "submit_time", None) else None,
  2029. "supplierId": q.supplier_id,
  2030. "supplierName": supplier.real_name if supplier else None,
  2031. "supplierLogoUrl": getattr(supplier, "avatar_url", None) if supplier else None,
  2032. "items": item_details
  2033. })
  2034. supplier = user_crud.get(db, pl.supplier_id) if pl.supplier_id else None
  2035. quotation_create_at = None
  2036. quotation_submit_time = None
  2037. if pl.quotation_id:
  2038. q = db.query(BizQuotation).filter(
  2039. and_(
  2040. BizQuotation.id == pl.quotation_id,
  2041. BizQuotation.is_del == 0
  2042. )
  2043. ).first()
  2044. if q:
  2045. quotation_create_at = str(q.create_at) if getattr(q, "create_at", None) else None
  2046. quotation_submit_time = str(q.submit_time) if getattr(q, "submit_time", None) else None
  2047. items = db.query(BizPriceListItem).filter(
  2048. and_(BizPriceListItem.price_list_id == pl.id, BizPriceListItem.is_del == 0)
  2049. ).all()
  2050. # price list item 按 product_id 映射(LEFT JOIN)
  2051. pl_item_by_pid: dict[str, object] = {}
  2052. for it in items:
  2053. pid = str(getattr(it, "product_id", "") or "")
  2054. if pid and pid not in pl_item_by_pid:
  2055. pl_item_by_pid[pid] = it
  2056. supplier_price_map: dict[str, float] = {}
  2057. if pl.quotation_id:
  2058. q_items = db.query(BizQuotationItem).filter(
  2059. and_(BizQuotationItem.quotation_id == pl.quotation_id, BizQuotationItem.is_del == 0)
  2060. ).all()
  2061. for qi in q_items:
  2062. if not qi.product_id:
  2063. continue
  2064. supplier_price_map[str(qi.product_id)] = float(qi.price) if qi.price else 0
  2065. item_details = []
  2066. for inq_item in inquiry_items:
  2067. pid = str(getattr(inq_item, "product_id", "") or "")
  2068. it = pl_item_by_pid.get(pid)
  2069. product = product_crud.get(db, pid) if pid else None
  2070. default_coeff = _numeric_to_float_optional(getattr(product, "price_coefficient", None)) if product else None
  2071. default_coeff = float(default_coeff) if default_coeff is not None else 0.0
  2072. category_name = None
  2073. if product and getattr(product, "category_id", None):
  2074. cat = category_crud.get(db, product.category_id)
  2075. category_name = cat.name if cat else None
  2076. unit_id = None
  2077. unit_name = None
  2078. if it and getattr(it, "unit_id", None):
  2079. unit_id = getattr(it, "unit_id", None)
  2080. elif product and getattr(product, "unit_id", None):
  2081. unit_id = getattr(product, "unit_id", None)
  2082. if unit_id:
  2083. u = unit_crud.get(db, unit_id)
  2084. unit_name = u.name if u else None
  2085. item_details.append({
  2086. "productId": pid,
  2087. "productName": product.name if product else None,
  2088. "skuCode": getattr(product, "sku_code", None) if product else None,
  2089. "description": getattr(product, "description", None) if product else None,
  2090. "imageUrl": getattr(product, "image_url", None) if product else None,
  2091. "categoryName": category_name,
  2092. "unitId": unit_id,
  2093. "unitName": unit_name,
  2094. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)) if product else None,
  2095. "supplierPrice": supplier_price_map.get(pid, 0),
  2096. # 最终售价来自 price list item;未生成/不存在时返回 0
  2097. "price": float(getattr(it, "price", 0) or 0) if it else 0,
  2098. "pricingCoefficient": float(getattr(it, "pricing_coefficient", 0)) if (it and getattr(it, "pricing_coefficient", None) is not None) else default_coeff
  2099. })
  2100. return success_response({
  2101. "priceListId": pl.id,
  2102. "priceVersion": pl.version,
  2103. "quotationId": pl.quotation_id,
  2104. "quotationCreateAt": quotation_create_at,
  2105. "quotationSubmitTime": quotation_submit_time,
  2106. "supplierId": pl.supplier_id,
  2107. "supplierName": supplier.real_name if supplier else None,
  2108. "supplierLogoUrl": getattr(supplier, "avatar_url", None) if supplier else None,
  2109. "items": item_details
  2110. })
  2111. @router.get("/quotation-compare", response_model=dict)
  2112. def compare_quotations(
  2113. inquiryId: str = Query(..., description="询价单ID"),
  2114. supplierIds: str = Query(..., description="供应商ID,逗号分隔"),
  2115. db: Session = Depends(get_db),
  2116. current_user: dict = Depends(require_admin)
  2117. ):
  2118. """报价对比(按询价单+供应商)"""
  2119. from app.crud.quotation import quotation_crud, quotation_item_crud
  2120. supplier_id_list = [x.strip() for x in supplierIds.split(",") if x.strip()]
  2121. if len(supplier_id_list) < 2:
  2122. return error_response(400, "至少选择两个供应商")
  2123. quotations, _ = quotation_crud.get_multi_with_filters(
  2124. db,
  2125. inquiry_id=inquiryId,
  2126. skip=0,
  2127. limit=500
  2128. )
  2129. quotations = [q for q in quotations if q.supplier_id in supplier_id_list]
  2130. if not quotations:
  2131. return success_response([])
  2132. # 汇总每个商品在不同供应商下的价格
  2133. compare_map = {}
  2134. for q in quotations:
  2135. items = quotation_item_crud.get_by_quotation(db, q.id)
  2136. for item in items:
  2137. product = product_crud.get(db, item.product_id)
  2138. unit_name = None
  2139. if item.unit_id:
  2140. u = unit_crud.get(db, item.unit_id)
  2141. unit_name = u.name if u else None
  2142. key = f"{item.product_id}:{item.unit_id or ''}"
  2143. row = compare_map.get(key)
  2144. if not row:
  2145. row = {
  2146. "productId": item.product_id,
  2147. "productName": product.name if product else item.product_id,
  2148. "unitId": item.unit_id,
  2149. "unitName": unit_name,
  2150. "prices": {},
  2151. "lowestPrice": None,
  2152. "highestPrice": None
  2153. }
  2154. compare_map[key] = row
  2155. price_value = float(item.price) if item.price is not None else 0
  2156. row["prices"][q.supplier_id] = price_value
  2157. result = []
  2158. for _, row in compare_map.items():
  2159. price_values = [v for v in row["prices"].values() if v is not None]
  2160. if price_values:
  2161. row["lowestPrice"] = min(price_values)
  2162. row["highestPrice"] = max(price_values)
  2163. else:
  2164. row["lowestPrice"] = 0
  2165. row["highestPrice"] = 0
  2166. result.append(row)
  2167. result.sort(key=lambda x: (x.get("productName") or "", x.get("unitName") or ""))
  2168. return success_response(result)
  2169. @router.post("/quotations/{quotation_id}/approve", response_model=dict)
  2170. def approve_quotation(
  2171. quotation_id: str,
  2172. request: dict,
  2173. db: Session = Depends(get_db),
  2174. current_user: dict = Depends(require_admin)
  2175. ):
  2176. """报价无需审核(接口已停用)"""
  2177. return error_response(410, "报价无需审核:请在“询价报价管理-最新报价对比”中直接选中供应商生效价格")
  2178. @router.post("/quotations/{quotation_id}/reject", response_model=dict)
  2179. def reject_quotation(
  2180. quotation_id: str,
  2181. request: dict,
  2182. db: Session = Depends(get_db),
  2183. current_user: dict = Depends(require_admin)
  2184. ):
  2185. """报价无需审核(接口已停用)"""
  2186. return error_response(410, "报价无需审核:请在“询价报价管理-最新报价对比”中直接选中供应商生效价格")
  2187. # =========================================
  2188. # 价格清单管理 API (Web端)
  2189. # =========================================
  2190. @router.get("/price-lists", response_model=dict)
  2191. def list_price_lists(
  2192. page: int = Query(1, ge=1, description="页码"),
  2193. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  2194. regionId: Optional[str] = Query(None, description="区域ID"),
  2195. status: Optional[str] = Query(None, description="状态: draft/pending/active/expired"),
  2196. db: Session = Depends(get_db),
  2197. current_user: dict = Depends(require_admin)
  2198. ):
  2199. """获取价格清单列表"""
  2200. from app.crud.price_list import price_list_crud
  2201. from app.crud.user import user_crud
  2202. # 区域管理员只能查看自己区域的价格清单
  2203. admin_region_id = get_admin_region_filter(db, current_user)
  2204. if admin_region_id and not regionId:
  2205. regionId = admin_region_id
  2206. elif admin_region_id and regionId != admin_region_id:
  2207. return success_response({
  2208. "list": [],
  2209. "total": 0,
  2210. "page": page,
  2211. "pageSize": pageSize,
  2212. "totalPages": 0
  2213. })
  2214. price_lists, total = price_list_crud.get_multi_with_filters(
  2215. db,
  2216. region_id=regionId,
  2217. status=status,
  2218. skip=(page - 1) * pageSize,
  2219. limit=pageSize
  2220. )
  2221. region_map = {}
  2222. supplier_map = {}
  2223. publisher_map = {}
  2224. for pl in price_lists:
  2225. if pl.region_id and pl.region_id not in region_map:
  2226. region = region_crud.get(db, pl.region_id)
  2227. region_map[pl.region_id] = region.name if region else None
  2228. if pl.supplier_id and pl.supplier_id not in supplier_map:
  2229. supplier = user_crud.get(db, pl.supplier_id)
  2230. supplier_map[pl.supplier_id] = supplier.real_name if supplier else None
  2231. if pl.published_by and pl.published_by not in publisher_map:
  2232. publisher = user_crud.get(db, pl.published_by)
  2233. publisher_map[pl.published_by] = publisher.real_name if publisher else None
  2234. return success_response({
  2235. "list": [{
  2236. "id": pl.id,
  2237. "regionId": pl.region_id,
  2238. "regionName": region_map.get(pl.region_id),
  2239. "supplierId": pl.supplier_id,
  2240. "supplierName": supplier_map.get(pl.supplier_id),
  2241. "version": pl.version,
  2242. "status": pl.status,
  2243. "effectiveTime": str(pl.effective_time) if pl.effective_time else None,
  2244. "publishedBy": pl.published_by,
  2245. "publishedByName": publisher_map.get(pl.published_by),
  2246. "publishedTime": str(pl.published_time) if pl.published_time else None,
  2247. "remark": pl.remark,
  2248. "createAt": str(pl.create_at) if pl.create_at else None
  2249. } for pl in price_lists],
  2250. "total": total,
  2251. "page": page,
  2252. "pageSize": pageSize,
  2253. "totalPages": (total + pageSize - 1) // pageSize
  2254. })
  2255. @router.post("/price-lists", response_model=dict)
  2256. def create_price_list(
  2257. request: dict,
  2258. db: Session = Depends(get_db),
  2259. current_user: dict = Depends(require_admin)
  2260. ):
  2261. """创建价格清单"""
  2262. from app.crud.price_list import price_list_crud
  2263. from datetime import datetime
  2264. region_id = request.get("regionId")
  2265. supplier_id = request.get("supplierId")
  2266. items = request.get("items", [])
  2267. effective_type = request.get("effectiveType", "immediate")
  2268. effective_time_str = request.get("effectiveTime")
  2269. remark = request.get("remark")
  2270. if not region_id:
  2271. return error_response(400, "请选择区域")
  2272. if not supplier_id:
  2273. return error_response(400, "请选择供应商")
  2274. if not items:
  2275. return error_response(400, "请添加价格项")
  2276. effective_time = None
  2277. if effective_time_str:
  2278. try:
  2279. effective_time = datetime.fromisoformat(effective_time_str.replace("Z", "+00:00"))
  2280. except:
  2281. effective_time = None
  2282. creator = {
  2283. "user_id": current_user.get("user_id"),
  2284. "real_name": current_user.get("real_name")
  2285. }
  2286. price_list = price_list_crud.create_with_items(
  2287. db,
  2288. obj_in={
  2289. "region_id": region_id,
  2290. "supplier_id": supplier_id,
  2291. "effective_time": effective_time,
  2292. "remark": remark
  2293. },
  2294. items=items,
  2295. creator=creator
  2296. )
  2297. # 如果是立即生效,直接发布
  2298. if effective_type == "immediate":
  2299. price_list_crud.publish(
  2300. db,
  2301. price_list.id,
  2302. current_user.get("user_id"),
  2303. effective_type="immediate"
  2304. )
  2305. return success_response({
  2306. "id": price_list.id,
  2307. "message": "创建成功"
  2308. })
  2309. @router.get("/price-lists/{price_list_id}", response_model=dict)
  2310. def get_price_list(
  2311. price_list_id: str,
  2312. db: Session = Depends(get_db),
  2313. current_user: dict = Depends(require_admin)
  2314. ):
  2315. """获取价格清单详情"""
  2316. from app.crud.price_list import price_list_crud, price_list_item_crud
  2317. from app.crud.user import user_crud
  2318. price_list = price_list_crud.get(db, price_list_id)
  2319. if not price_list:
  2320. return error_response(404, "价格清单不存在")
  2321. items = price_list_item_crud.get_by_price_list(db, price_list_id)
  2322. # 获取关联信息
  2323. region_name = None
  2324. if price_list.region_id:
  2325. region = region_crud.get(db, price_list.region_id)
  2326. region_name = region.name if region else None
  2327. supplier_name = None
  2328. if price_list.supplier_id:
  2329. supplier = user_crud.get(db, price_list.supplier_id)
  2330. supplier_name = supplier.real_name if supplier else None
  2331. publisher_name = None
  2332. if price_list.published_by:
  2333. publisher = user_crud.get(db, price_list.published_by)
  2334. publisher_name = publisher.real_name if publisher else None
  2335. # 订单关联供应商(来自订单价格清单)
  2336. from app.crud.price_list import price_list_crud
  2337. price_list = price_list_crud.get(db, order.price_list_id) if order.price_list_id else None
  2338. supplier_id_from_price_list = getattr(price_list, "supplier_id", None) if price_list else None
  2339. supplier_name_from_price_list = None
  2340. if supplier_id_from_price_list:
  2341. _sup_u = user_crud.get(db, supplier_id_from_price_list)
  2342. if _sup_u:
  2343. supplier_name_from_price_list = _sup_u.real_name or _sup_u.username
  2344. pl_ids_for_order = [order.price_list_id] if order.price_list_id else []
  2345. pli_map_for_order = _price_list_item_map(db, pl_ids_for_order)
  2346. # 获取商品和单位信息
  2347. item_details = []
  2348. supplier_total_amount = 0.0
  2349. selling_total_amount = 0.0
  2350. for item in items:
  2351. product = product_crud.get(db, item.product_id)
  2352. category_name = None
  2353. if product and product.category_id:
  2354. cat = category_crud.get(db, product.category_id)
  2355. category_name = cat.name if cat else None
  2356. unit_name = None
  2357. if item.unit_id:
  2358. u = unit_crud.get(db, item.unit_id)
  2359. unit_name = u.name if u else None
  2360. qty = float(item.quantity) if item.quantity else 0
  2361. selling_u = float(item.unit_price) if item.unit_price else 0
  2362. selling_amt = float(item.amount) if item.amount else round(qty * selling_u, 2)
  2363. pli = pli_map_for_order.get((order.price_list_id, item.product_id, item.unit_id))
  2364. supplier_u = _supplier_unit_yuan_from_pli(pli)
  2365. if supplier_u is None:
  2366. supplier_u = selling_u
  2367. supplier_amt = round(qty * supplier_u, 2)
  2368. supplier_total_amount += supplier_amt
  2369. selling_total_amount += selling_amt
  2370. item_details.append({
  2371. "id": item.id,
  2372. "productId": item.product_id,
  2373. "productName": product.name if product else None,
  2374. "categoryName": category_name,
  2375. "unitId": item.unit_id,
  2376. "unitName": unit_name,
  2377. "price": float(item.price) if item.price else 0,
  2378. "imageUrl": product.image_url if product else None
  2379. })
  2380. return success_response({
  2381. "id": price_list.id,
  2382. "regionId": price_list.region_id,
  2383. "regionName": region_name,
  2384. "supplierId": price_list.supplier_id,
  2385. "supplierName": supplier_name,
  2386. "version": price_list.version,
  2387. "status": price_list.status,
  2388. "effectiveTime": str(price_list.effective_time) if price_list.effective_time else None,
  2389. "publishedBy": price_list.published_by,
  2390. "publishedByName": publisher_name,
  2391. "publishedTime": str(price_list.published_time) if price_list.published_time else None,
  2392. "remark": price_list.remark,
  2393. "createAt": str(price_list.create_at) if price_list.create_at else None,
  2394. "items": item_details
  2395. })
  2396. @router.put("/price-lists/{price_list_id}", response_model=dict)
  2397. def update_price_list(
  2398. price_list_id: str,
  2399. request: dict,
  2400. db: Session = Depends(get_db),
  2401. current_user: dict = Depends(require_admin)
  2402. ):
  2403. """更新价格清单(只有草稿状态可编辑)"""
  2404. from app.crud.price_list import price_list_crud
  2405. from datetime import datetime
  2406. price_list = price_list_crud.get(db, price_list_id)
  2407. if not price_list:
  2408. return error_response(404, "价格清单不存在")
  2409. if price_list.status != "draft":
  2410. return error_response(400, "只有草稿状态的价格清单可以编辑")
  2411. items = request.get("items")
  2412. effective_time_str = request.get("effectiveTime")
  2413. remark = request.get("remark")
  2414. obj_in = {}
  2415. if effective_time_str:
  2416. try:
  2417. obj_in["effective_time"] = datetime.fromisoformat(effective_time_str.replace("Z", "+00:00"))
  2418. except:
  2419. pass
  2420. if remark is not None:
  2421. obj_in["remark"] = remark
  2422. updater = {
  2423. "user_id": current_user.get("user_id"),
  2424. "real_name": current_user.get("real_name")
  2425. }
  2426. price_list_crud.update_with_items(
  2427. db,
  2428. price_list_id,
  2429. obj_in,
  2430. items=items,
  2431. updater=updater
  2432. )
  2433. return success_response({
  2434. "id": price_list_id,
  2435. "message": "更新成功"
  2436. })
  2437. @router.post("/price-lists/{price_list_id}/publish", response_model=dict)
  2438. def publish_price_list(
  2439. price_list_id: str,
  2440. request: dict,
  2441. db: Session = Depends(get_db),
  2442. current_user: dict = Depends(require_admin)
  2443. ):
  2444. """发布价格清单"""
  2445. from app.crud.price_list import price_list_crud
  2446. from datetime import datetime
  2447. price_list = price_list_crud.get(db, price_list_id)
  2448. if not price_list:
  2449. return error_response(404, "价格清单不存在")
  2450. if price_list.status != "draft":
  2451. return error_response(400, "只有草稿状态的价格清单可以发布")
  2452. effective_type = request.get("effectiveType", "immediate")
  2453. effective_time_str = request.get("effectiveTime")
  2454. effective_time = None
  2455. if effective_time_str:
  2456. try:
  2457. effective_time = datetime.fromisoformat(effective_time_str.replace("Z", "+00:00"))
  2458. except:
  2459. pass
  2460. price_list_crud.publish(
  2461. db,
  2462. price_list_id,
  2463. current_user.get("user_id"),
  2464. effective_time=effective_time,
  2465. effective_type=effective_type
  2466. )
  2467. return success_response({
  2468. "id": price_list_id,
  2469. "message": "发布成功"
  2470. })
  2471. @router.post("/price-lists/{price_list_id}/invalidate", response_model=dict)
  2472. def invalidate_price_list(
  2473. price_list_id: str,
  2474. db: Session = Depends(get_db),
  2475. current_user: dict = Depends(require_admin)
  2476. ):
  2477. """使价格清单失效"""
  2478. from app.crud.price_list import price_list_crud
  2479. price_list = price_list_crud.get(db, price_list_id)
  2480. if not price_list:
  2481. return error_response(404, "价格清单不存在")
  2482. if price_list.status not in ["active", "pending"]:
  2483. return error_response(400, "只有生效中或待生效的价格清单可以失效")
  2484. price_list_crud.invalidate(db, price_list_id)
  2485. return success_response({
  2486. "id": price_list_id,
  2487. "message": "操作成功"
  2488. })
  2489. @router.delete("/price-lists/{price_list_id}", response_model=dict)
  2490. def delete_price_list(
  2491. price_list_id: str,
  2492. db: Session = Depends(get_db),
  2493. current_user: dict = Depends(require_admin)
  2494. ):
  2495. """删除价格清单(只有草稿状态可删除)"""
  2496. from app.crud.price_list import price_list_crud
  2497. price_list = price_list_crud.get(db, price_list_id)
  2498. if not price_list:
  2499. return error_response(404, "价格清单不存在")
  2500. if price_list.status != "draft":
  2501. return error_response(400, "只有草稿状态的价格清单可以删除")
  2502. price_list_crud.delete(db, price_list_id)
  2503. return success_response({
  2504. "message": "删除成功"
  2505. })
  2506. @router.get("/price-lists/product-history", response_model=dict)
  2507. def get_product_price_history(
  2508. regionId: str = Query(..., description="区域ID"),
  2509. productId: str = Query(..., description="商品ID"),
  2510. page: int = Query(1, ge=1, description="页码"),
  2511. pageSize: int = Query(20, ge=1, le=100, description="每页条数"),
  2512. db: Session = Depends(get_db),
  2513. current_user: dict = Depends(require_admin)
  2514. ):
  2515. """按商品维度查询价格历史"""
  2516. from app.crud.price_list import price_list_crud, price_list_item_crud
  2517. product = product_crud.get(db, productId)
  2518. if not product:
  2519. return error_response(404, "商品不存在")
  2520. items, total = price_list_item_crud.get_product_price_history(
  2521. db,
  2522. region_id=regionId,
  2523. product_id=productId,
  2524. skip=(page - 1) * pageSize,
  2525. limit=pageSize
  2526. )
  2527. # 获取单位信息
  2528. for item in items:
  2529. if item.get("unit_id"):
  2530. u = unit_crud.get(db, item["unit_id"])
  2531. item["unitName"] = u.name if u else None
  2532. return success_response({
  2533. "productId": productId,
  2534. "productName": product.name,
  2535. "history": items,
  2536. "total": total,
  2537. "page": page,
  2538. "pageSize": pageSize
  2539. })
  2540. @router.get("/price-lists/generate-options", response_model=dict)
  2541. def get_generate_price_list_options(
  2542. regionId: str = Query(..., description="区域ID"),
  2543. db: Session = Depends(get_db),
  2544. current_user: dict = Depends(require_admin)
  2545. ):
  2546. """获取生成价格清单的选项(该区域已提交、尚未被选中的报价单,报价无审核流程)"""
  2547. from app.crud.quotation import quotation_crud, quotation_item_crud
  2548. from app.crud.user import user_crud
  2549. quotations, total = quotation_crud.get_multi_with_filters(
  2550. db,
  2551. region_id=regionId,
  2552. status="submitted",
  2553. skip=0,
  2554. limit=100
  2555. )
  2556. result = []
  2557. for q in quotations:
  2558. supplier = user_crud.get(db, q.supplier_id)
  2559. items = quotation_item_crud.get_by_quotation(db, q.id)
  2560. item_details = []
  2561. for item in items:
  2562. product = product_crud.get(db, item.product_id)
  2563. unit_name = None
  2564. if item.unit_id:
  2565. u = unit_crud.get(db, item.unit_id)
  2566. unit_name = u.name if u else None
  2567. item_details.append({
  2568. "productId": item.product_id,
  2569. "productName": product.name if product else None,
  2570. "unitId": item.unit_id,
  2571. "unitName": unit_name,
  2572. "price": float(item.price) if item.price else 0
  2573. })
  2574. result.append({
  2575. "quotationId": q.id,
  2576. "quotationNo": f"QT{q.create_at.strftime('%Y%m%d%H%M%S') if q.create_at else ''}",
  2577. "supplierId": q.supplier_id,
  2578. "supplierName": supplier.real_name if supplier else None,
  2579. "totalAmount": float(q.total_amount) if q.total_amount else 0,
  2580. "items": item_details
  2581. })
  2582. return success_response({
  2583. "list": result,
  2584. "total": len(result)
  2585. })
  2586. @router.get("/price-lists/compare", response_model=dict)
  2587. def compare_price_list_versions(
  2588. regionId: str = Query(..., description="区域ID"),
  2589. version1Id: str = Query(..., description="版本1ID"),
  2590. version2Id: str = Query(..., description="版本2ID"),
  2591. db: Session = Depends(get_db),
  2592. current_user: dict = Depends(require_admin)
  2593. ):
  2594. """对比两个价格版本"""
  2595. from app.crud.price_list import price_list_crud, price_list_item_crud
  2596. # 获取两个版本的价格清单
  2597. price_list1 = price_list_crud.get(db, version1Id)
  2598. price_list2 = price_list_crud.get(db, version2Id)
  2599. if not price_list1 or not price_list2:
  2600. return error_response(404, "价格版本不存在")
  2601. if price_list1.region_id != regionId or price_list2.region_id != regionId:
  2602. return error_response(400, "价格版本不属于该区域")
  2603. # 获取两个版本的价格项
  2604. items1 = price_list_item_crud.get_by_price_list(db, version1Id)
  2605. items2 = price_list_item_crud.get_by_price_list(db, version2Id)
  2606. # 构建价格映射
  2607. price_map1 = {item.product_id: item for item in items1}
  2608. price_map2 = {item.product_id: item for item in items2}
  2609. # 获取所有涉及的商品
  2610. all_product_ids = set(price_map1.keys()) | set(price_map2.keys())
  2611. # 构建对比数据
  2612. comparison = []
  2613. for product_id in all_product_ids:
  2614. item1 = price_map1.get(product_id)
  2615. item2 = price_map2.get(product_id)
  2616. product = product_crud.get(db, product_id)
  2617. unit_name = None
  2618. if item1 and item1.unit_id:
  2619. u = unit_crud.get(db, item1.unit_id)
  2620. unit_name = u.name if u else None
  2621. elif item2 and item2.unit_id:
  2622. u = unit_crud.get(db, item2.unit_id)
  2623. unit_name = u.name if u else None
  2624. price1 = float(item1.price) if item1 and item1.price else None
  2625. price2 = float(item2.price) if item2 and item2.price else None
  2626. # 计算差异
  2627. price_diff = None
  2628. price_change = None
  2629. change_rate = None
  2630. if price1 is not None and price2 is not None:
  2631. price_diff = price2 - price1
  2632. if price1 > 0:
  2633. change_rate = round((price_diff / price1) * 100, 2)
  2634. if price_diff > 0:
  2635. price_change = "up"
  2636. elif price_diff < 0:
  2637. price_change = "down"
  2638. else:
  2639. price_change = "same"
  2640. comparison.append({
  2641. "productId": product_id,
  2642. "productName": product.name if product else None,
  2643. "categoryId": product.category_id if product else None,
  2644. "unitId": item1.unit_id if item1 else (item2.unit_id if item2 else None),
  2645. "unitName": unit_name,
  2646. "price1": price1,
  2647. "price2": price2,
  2648. "priceDiff": price_diff,
  2649. "priceChange": price_change,
  2650. "changeRate": change_rate,
  2651. "existIn1": item1 is not None,
  2652. "existIn2": item2 is not None
  2653. })
  2654. # 计算汇总统计
  2655. total_products = len(comparison)
  2656. price_up_count = sum(1 for c in comparison if c["priceChange"] == "up")
  2657. price_down_count = sum(1 for c in comparison if c["priceChange"] == "down")
  2658. price_same_count = sum(1 for c in comparison if c["priceChange"] == "same")
  2659. new_product_count = sum(1 for c in comparison if not c["existIn1"] and c["existIn2"])
  2660. removed_product_count = sum(1 for c in comparison if c["existIn1"] and not c["existIn2"])
  2661. return success_response({
  2662. "version1": {
  2663. "id": price_list1.id,
  2664. "version": price_list1.version,
  2665. "status": price_list1.status,
  2666. "publishedTime": str(price_list1.published_time) if price_list1.published_time else None
  2667. },
  2668. "version2": {
  2669. "id": price_list2.id,
  2670. "version": price_list2.version,
  2671. "status": price_list2.status,
  2672. "publishedTime": str(price_list2.published_time) if price_list2.published_time else None
  2673. },
  2674. "statistics": {
  2675. "totalProducts": total_products,
  2676. "priceUp": price_up_count,
  2677. "priceDown": price_down_count,
  2678. "priceSame": price_same_count,
  2679. "newProducts": new_product_count,
  2680. "removedProducts": removed_product_count
  2681. },
  2682. "comparison": comparison
  2683. })
  2684. @router.get("/price-lists/history", response_model=dict)
  2685. def get_price_list_history(
  2686. regionId: str = Query(..., description="区域ID"),
  2687. page: int = Query(1, ge=1, description="页码"),
  2688. pageSize: int = Query(10, ge=1, le=50, description="每页条数"),
  2689. db: Session = Depends(get_db),
  2690. current_user: dict = Depends(require_admin)
  2691. ):
  2692. """获取价格清单历史版本列表"""
  2693. from app.crud.price_list import price_list_crud
  2694. from app.crud.user import user_crud
  2695. price_lists, total = price_list_crud.get_multi_with_filters(
  2696. db,
  2697. region_id=regionId,
  2698. skip=(page - 1) * pageSize,
  2699. limit=pageSize
  2700. )
  2701. result = []
  2702. for pl in price_lists:
  2703. supplier = user_crud.get(db, pl.supplier_id)
  2704. region = region_crud.get(db, pl.region_id)
  2705. result.append({
  2706. "id": pl.id,
  2707. "version": pl.version,
  2708. "status": pl.status,
  2709. "statusText": "生效中" if pl.status == "active" else "待生效" if pl.status == "pending" else "已失效" if pl.status == "expired" else "草稿",
  2710. "supplierId": pl.supplier_id,
  2711. "supplierName": supplier.real_name if supplier else None,
  2712. "regionName": region.name if region else None,
  2713. "effectiveTime": str(pl.effective_time) if pl.effective_time else None,
  2714. "publishedTime": str(pl.published_time) if pl.published_time else None,
  2715. "remark": pl.remark,
  2716. "createAt": str(pl.create_at) if pl.create_at else None
  2717. })
  2718. return success_response({
  2719. "list": result,
  2720. "total": total,
  2721. "page": page,
  2722. "pageSize": pageSize
  2723. })
  2724. # =========================================
  2725. # 订单管理 API (Web端)
  2726. # =========================================
  2727. # 订单状态映射
  2728. ORDER_STATUS_MAP = {
  2729. "pending_payment": "待支付",
  2730. "pending_review_cancel": "待审核取消",
  2731. "pending_dispatch": "待分配配送",
  2732. "delivering": "配送中",
  2733. "pending_confirm": "待确认收货",
  2734. "completed": "已完结",
  2735. "cancelled": "已取消"
  2736. }
  2737. # 订单状态日志展示(含配送/支付维度的结构化 to_status)
  2738. DELIVERY_STATUS_LOG_LABELS = {
  2739. "pending_dispatch": "待分配配送",
  2740. "delivering": "配送中",
  2741. "delivered": "配送完成",
  2742. }
  2743. def _order_log_status_display_map() -> dict:
  2744. m = dict(ORDER_STATUS_MAP)
  2745. m["delivery.assign"] = "分配配送员"
  2746. m["delivery.reassign"] = "更换配送员"
  2747. for k, v in DELIVERY_STATUS_LOG_LABELS.items():
  2748. m[f"ds_{k}"] = f"配送状态:{v}"
  2749. m["pay_pending_payment"] = "支付状态:待支付"
  2750. m["pay_paid"] = "支付状态:已支付"
  2751. m["pay_refunding"] = "支付状态:退款中"
  2752. m["pay_refunded"] = "支付状态:已退款"
  2753. _task_lbl = {
  2754. "pending": "待分配",
  2755. "assigned": "已分配",
  2756. "supplier_stocking": "供应商备货中",
  2757. "supplier_ready": "备货完成(待取货)",
  2758. "picking": "取货中",
  2759. "delivering": "配送中",
  2760. "completed": "已完成",
  2761. "cancelled": "已取消",
  2762. }
  2763. for k, v in _task_lbl.items():
  2764. m[f"dt_{k}"] = f"配送任务:{v}"
  2765. return m
  2766. ORDER_LOG_STATUS_MAP = _order_log_status_display_map()
  2767. def _status_log_timeline_description(entry: dict) -> str:
  2768. """与 web-admin 订单详情「操作记录」中对 reason/note 的展示规则保持一致。"""
  2769. note = (entry.get("note") or "").strip()
  2770. raw_reason = entry.get("reason")
  2771. description = note or ""
  2772. if raw_reason and str(raw_reason).strip().startswith("{"):
  2773. try:
  2774. o = json.loads(raw_reason)
  2775. if isinstance(o, dict) and (
  2776. o.get("toDeliverName") is not None or o.get("fromDeliverName") is not None
  2777. ):
  2778. description = f"配送员:{o.get('fromDeliverName') or '—'} → {o.get('toDeliverName') or '—'}"
  2779. if note:
  2780. description += f";{note}"
  2781. except json.JSONDecodeError:
  2782. if not description:
  2783. description = str(raw_reason)
  2784. elif raw_reason and not description:
  2785. description = str(raw_reason)
  2786. return description
  2787. def _delivery_timeline_type(to_status: str) -> str:
  2788. if to_status == "dt_completed":
  2789. return "success"
  2790. if to_status == "dt_cancelled":
  2791. return "danger"
  2792. return "primary"
  2793. def _log_entry_in_delivery_timeline(entry: dict) -> bool:
  2794. ts = entry.get("status") or ""
  2795. if ts in ("delivery.assign", "delivery.reassign"):
  2796. return True
  2797. if ts.startswith("dt_") or ts.startswith("ds_"):
  2798. return True
  2799. return False
  2800. def _build_order_delivery_timeline(dtask, log_details: List[dict], order) -> List[dict]:
  2801. """
  2802. 配送进度以订单状态日志为权威来源(配送任务 dt_*、配送状态 ds_*、分配配送员等),
  2803. 与「操作记录」同源,避免两套拼接逻辑长期漂移。
  2804. """
  2805. events: List[dict] = []
  2806. if dtask is not None and dtask.create_at:
  2807. dr = (getattr(dtask, "dispatch_remark", None) or "").strip() or None
  2808. events.append({
  2809. "time": str(dtask.create_at),
  2810. "title": "配送任务已创建",
  2811. "description": dr or "",
  2812. "type": "info",
  2813. "hollow": False,
  2814. })
  2815. timeline_statuses: set = set()
  2816. for entry in log_details:
  2817. if not _log_entry_in_delivery_timeline(entry):
  2818. continue
  2819. ts_key = entry.get("status") or ""
  2820. timeline_statuses.add(ts_key)
  2821. t = entry.get("createAt")
  2822. if not t:
  2823. continue
  2824. from_t = (entry.get("fromStatusText") or "").strip()
  2825. to_t = (entry.get("statusText") or "").strip() or ts_key or "-"
  2826. title = f"{from_t} → {to_t}" if from_t else to_t
  2827. events.append({
  2828. "time": t,
  2829. "title": title,
  2830. "description": _status_log_timeline_description(entry),
  2831. "type": _delivery_timeline_type(ts_key),
  2832. "hollow": False,
  2833. })
  2834. if dtask is not None:
  2835. if dtask.pickup_time and "dt_picking" not in timeline_statuses:
  2836. pr = (dtask.pickup_remark or "").strip() or ""
  2837. events.append({
  2838. "time": str(dtask.pickup_time),
  2839. "title": "配送任务:取货中",
  2840. "description": pr,
  2841. "type": "primary",
  2842. "hollow": False,
  2843. })
  2844. if "dt_completed" not in timeline_statuses and (
  2845. dtask.status == "completed"
  2846. or (getattr(dtask, "deliverer_status", None) == "delivered")
  2847. ):
  2848. t_end = dtask.delivery_time or getattr(order, "delivered_time", None)
  2849. if t_end:
  2850. dr = (dtask.delivery_remark or "").strip() or ""
  2851. events.append({
  2852. "time": str(t_end),
  2853. "title": "配送任务:已完成",
  2854. "description": dr,
  2855. "type": "success",
  2856. "hollow": False,
  2857. })
  2858. events = [e for e in events if e.get("time")]
  2859. events.sort(key=lambda x: str(x.get("time") or ""))
  2860. return events
  2861. @router.get("/orders", response_model=dict)
  2862. def list_orders(
  2863. page: int = Query(1, ge=1, description="页码"),
  2864. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  2865. regionId: Optional[str] = Query(None, description="区域ID"),
  2866. status: Optional[str] = Query(None, description="订单状态"),
  2867. orderStatus: Optional[str] = Query(None, description="订单主状态"),
  2868. deliveryStatus: Optional[str] = Query(None, description="配送状态"),
  2869. payStatus: Optional[str] = Query(None, description="支付状态"),
  2870. paymentMethod: Optional[str] = Query(None, description="支付方式: online/offline"),
  2871. clientId: Optional[str] = Query(None, description="客户ID"),
  2872. orderNo: Optional[str] = Query(None, description="订单号"),
  2873. startDate: Optional[str] = Query(None, description="开始日期"),
  2874. endDate: Optional[str] = Query(None, description="结束日期"),
  2875. db: Session = Depends(get_db),
  2876. current_user: dict = Depends(require_admin)
  2877. ):
  2878. """获取订单列表"""
  2879. from app.crud.order import order_crud, order_item_crud
  2880. # 区域管理员只能查看自己区域的订单
  2881. admin_region_id = get_admin_region_filter(db, current_user)
  2882. if admin_region_id and not regionId:
  2883. # 如果是区域管理员且未指定区域,默认使用其所属区域
  2884. regionId = admin_region_id
  2885. elif admin_region_id and regionId != admin_region_id:
  2886. # 区域管理员不能查看其他区域的订单
  2887. return success_response({
  2888. "list": [],
  2889. "total": 0,
  2890. "page": page,
  2891. "pageSize": pageSize,
  2892. "totalPages": 0
  2893. })
  2894. orders, total = order_crud.get_multi_with_filters(
  2895. db,
  2896. region_id=regionId,
  2897. status=status,
  2898. order_status=orderStatus,
  2899. delivery_status=deliveryStatus,
  2900. pay_status=payStatus,
  2901. payment_method=paymentMethod,
  2902. client_id=clientId,
  2903. order_no=orderNo,
  2904. start_date=startDate,
  2905. end_date=endDate,
  2906. skip=(page - 1) * pageSize,
  2907. limit=pageSize
  2908. )
  2909. # 列表页:按订单行汇总供货总金额 / 售出总金额(与订单详情口径一致)
  2910. order_ids_page = [o.id for o in orders]
  2911. oid_to_order = {o.id: o for o in orders}
  2912. items_by_oid: dict = {}
  2913. if order_ids_page:
  2914. for ln in (
  2915. db.query(BizOrderItem)
  2916. .filter(BizOrderItem.order_id.in_(order_ids_page), BizOrderItem.is_del == 0)
  2917. .all()
  2918. ):
  2919. items_by_oid.setdefault(ln.order_id, []).append(ln)
  2920. pl_ids_page = list({o.price_list_id for o in orders if o.price_list_id})
  2921. pli_map_page = _price_list_item_map(db, pl_ids_page) if pl_ids_page else {}
  2922. order_supplier_selling_totals: dict = {}
  2923. for oid, lines in items_by_oid.items():
  2924. o = oid_to_order.get(oid)
  2925. pl_id = o.price_list_id if o else None
  2926. sup_acc = 0.0
  2927. sel_acc = 0.0
  2928. for item in lines:
  2929. qty = float(item.quantity or 0)
  2930. selling_u = float(item.unit_price or 0)
  2931. selling_amt = (
  2932. float(item.amount) if item.amount is not None else round(qty * selling_u, 2)
  2933. )
  2934. pli = pli_map_page.get((pl_id, item.product_id, item.unit_id)) if pl_id else None
  2935. supplier_u = _supplier_unit_yuan_from_pli(pli)
  2936. if supplier_u is None:
  2937. supplier_u = selling_u
  2938. sup_acc += round(qty * supplier_u, 2)
  2939. sel_acc += selling_amt
  2940. order_supplier_selling_totals[oid] = (round(sup_acc, 2), round(sel_acc, 2))
  2941. region_map = {}
  2942. region_delivery_minutes_map = {}
  2943. client_map = {}
  2944. result = []
  2945. for order in orders:
  2946. order_status = getattr(order, "order_status", None) or "pending_confirm"
  2947. delivery_status = getattr(order, "delivery_status", None) or "pending_dispatch"
  2948. pay_status = getattr(order, "pay_status", None) or "pending_payment"
  2949. # 获取区域名称、预计配送时长
  2950. if order.region_id and order.region_id not in region_map:
  2951. region = region_crud.get(db, order.region_id)
  2952. region_map[order.region_id] = region.name if region else None
  2953. region_delivery_minutes_map[order.region_id] = (
  2954. getattr(region, "expected_delivery_minutes", None) if region else None
  2955. )
  2956. # 获取客户名称
  2957. if order.client_id and order.client_id not in client_map:
  2958. client = user_crud.get(db, order.client_id)
  2959. client_map[order.client_id] = client.real_name if client else None
  2960. # 获取订单项数量
  2961. item_count = order_item_crud.get_count_by_order(db, order.id)
  2962. _sup_total, _sel_total = order_supplier_selling_totals.get(order.id, (0.0, 0.0))
  2963. result.append({
  2964. "id": order.id,
  2965. "orderNo": order.order_no,
  2966. "clientId": order.client_id,
  2967. "clientName": client_map.get(order.client_id),
  2968. "regionId": order.region_id,
  2969. "regionName": region_map.get(order.region_id),
  2970. "regionExpectedDeliveryMinutes": region_delivery_minutes_map.get(order.region_id),
  2971. "totalAmount": float(order.total_amount) if order.total_amount else 0,
  2972. "supplierTotalAmount": _sup_total,
  2973. "sellingTotalAmount": _sel_total,
  2974. "paidAmount": float(order.paid_amount) if order.paid_amount else 0,
  2975. "receivableAmount": float(order.receivable_amount) if order.receivable_amount else 0,
  2976. "status": order.status,
  2977. "orderStatus": order_status,
  2978. "deliveryStatus": delivery_status,
  2979. "payStatus": pay_status,
  2980. "cancelStatus": getattr(order, "cancel_status", None),
  2981. "paymentMethod": order_crud.normalize_payment_method(order.payment_method),
  2982. "paymentStatus": "paid" if order.paid_amount and order.paid_amount > 0 else "unpaid",
  2983. "itemCount": item_count,
  2984. "createAt": str(order.create_at) if order.create_at else None,
  2985. "paymentTime": str(order.payment_time) if order.payment_time else None
  2986. })
  2987. return success_response({
  2988. "list": result,
  2989. "total": total,
  2990. "page": page,
  2991. "pageSize": pageSize,
  2992. "totalPages": (total + pageSize - 1) // pageSize
  2993. })
  2994. @router.get("/orders/{order_id}", response_model=dict)
  2995. def get_order(
  2996. order_id: str,
  2997. db: Session = Depends(get_db),
  2998. current_user: dict = Depends(require_admin)
  2999. ):
  3000. """获取订单详情"""
  3001. from app.crud.order import order_crud, order_item_crud, order_status_log_crud
  3002. order = order_crud.get(db, order_id)
  3003. if not order:
  3004. return error_response(404, "订单不存在")
  3005. # 获取订单项
  3006. items = order_item_crud.get_by_order(db, order_id)
  3007. from app.crud.price_list import price_list_crud
  3008. price_list = price_list_crud.get(db, order.price_list_id) if order.price_list_id else None
  3009. supplier_id_from_price_list = getattr(price_list, "supplier_id", None) if price_list else None
  3010. supplier_name_from_price_list = None
  3011. if supplier_id_from_price_list:
  3012. _sup_u = user_crud.get(db, supplier_id_from_price_list)
  3013. if _sup_u:
  3014. supplier_name_from_price_list = _sup_u.real_name or _sup_u.username
  3015. pl_ids_for_order = [order.price_list_id] if order.price_list_id else []
  3016. pli_map_for_order = _price_list_item_map(db, pl_ids_for_order)
  3017. from app.crud.price_list import price_list_crud
  3018. price_list = price_list_crud.get(db, order.price_list_id) if order.price_list_id else None
  3019. supplier_id_from_price_list = getattr(price_list, "supplier_id", None) if price_list else None
  3020. supplier_name_from_price_list = None
  3021. if supplier_id_from_price_list:
  3022. _sup_u = user_crud.get(db, supplier_id_from_price_list)
  3023. if _sup_u:
  3024. supplier_name_from_price_list = _sup_u.real_name or _sup_u.username
  3025. pl_ids_for_order = [order.price_list_id] if order.price_list_id else []
  3026. pli_map_for_order = _price_list_item_map(db, pl_ids_for_order)
  3027. from app.crud.price_list import price_list_crud
  3028. price_list = price_list_crud.get(db, order.price_list_id) if order.price_list_id else None
  3029. supplier_id_from_price_list = getattr(price_list, "supplier_id", None) if price_list else None
  3030. supplier_name_from_price_list = None
  3031. if supplier_id_from_price_list:
  3032. _sup_u = user_crud.get(db, supplier_id_from_price_list)
  3033. if _sup_u:
  3034. supplier_name_from_price_list = _sup_u.real_name or _sup_u.username
  3035. pl_ids_for_order = [order.price_list_id] if order.price_list_id else []
  3036. pli_map_for_order = _price_list_item_map(db, pl_ids_for_order)
  3037. # 获取状态日志
  3038. status_logs = order_status_log_crud.get_by_order(db, order_id)
  3039. # 尝试锁定订单(防止并发操作)
  3040. lock_info = None
  3041. operator_id = current_user.get("user_id")
  3042. try:
  3043. order_crud.lock_order(db, order_id, operator_id)
  3044. except ValueError as e:
  3045. # 已被其他用户锁定,返回锁定信息但不阻止查看
  3046. lock_info = {
  3047. "isLocked": True,
  3048. "lockedBy": order.lock_operator_id,
  3049. "lockedTime": str(order.lock_time) if order.lock_time else None,
  3050. "message": str(e)
  3051. }
  3052. else:
  3053. lock_info = {"isLocked": False}
  3054. # 获取关联信息
  3055. region_name = None
  3056. region_expected_delivery_minutes = None
  3057. if order.region_id:
  3058. region = region_crud.get(db, order.region_id)
  3059. region_name = region.name if region else None
  3060. region_expected_delivery_minutes = (
  3061. getattr(region, "expected_delivery_minutes", None) if region else None
  3062. )
  3063. client_name = None
  3064. if order.client_id:
  3065. client = user_crud.get(db, order.client_id)
  3066. client_name = client.real_name if client else None
  3067. # 配送任务明细上的已送达量(订单行 delivered_quantity 可能未同步,展示时与任务明细取大)
  3068. from app.crud.delivery import delivery_task_item_crud as _merge_task_delivered
  3069. _line_delivered_from_task = _merge_task_delivered.get_delivered_quantity_by_order_item(db, order_id)
  3070. # 获取商品和单位信息
  3071. item_details = []
  3072. supplier_total_amount = 0.0
  3073. selling_total_amount = 0.0
  3074. for item in items:
  3075. product = product_crud.get(db, item.product_id)
  3076. unit_name = None
  3077. if item.unit_id:
  3078. u = unit_crud.get(db, item.unit_id)
  3079. unit_name = u.name if u else None
  3080. category_id = None
  3081. category_path = ""
  3082. image_url = None
  3083. measure_value = None
  3084. if product:
  3085. category_id = getattr(product, "category_id", None)
  3086. if category_id:
  3087. category_path = _category_path_display(db, str(category_id))
  3088. image_url = getattr(product, "image_url", None)
  3089. measure_value = _numeric_to_float_optional(getattr(product, "measure_value", None))
  3090. _oi_dq = float(item.delivered_quantity) if item.delivered_quantity else 0.0
  3091. _ti_dq = float(_line_delivered_from_task.get(item.id, 0.0))
  3092. _merged_dq = max(_oi_dq, _ti_dq)
  3093. qty = float(item.quantity) if item.quantity else 0
  3094. selling_u = float(item.unit_price) if item.unit_price else 0
  3095. selling_amt = float(item.amount) if item.amount else round(qty * selling_u, 2)
  3096. pli = pli_map_for_order.get((order.price_list_id, item.product_id, item.unit_id))
  3097. supplier_u = _supplier_unit_yuan_from_pli(pli)
  3098. if supplier_u is None:
  3099. supplier_u = selling_u
  3100. supplier_amt = round(qty * supplier_u, 2)
  3101. supplier_total_amount += supplier_amt
  3102. selling_total_amount += selling_amt
  3103. item_details.append({
  3104. "id": item.id,
  3105. "productId": item.product_id,
  3106. "productName": product.name if product else None,
  3107. "imageUrl": image_url,
  3108. "categoryId": str(category_id) if category_id else None,
  3109. "categoryName": category_path or None,
  3110. "measureValue": measure_value,
  3111. "unitId": item.unit_id,
  3112. "unitName": unit_name,
  3113. "supplierId": supplier_id_from_price_list,
  3114. "supplierName": supplier_name_from_price_list,
  3115. "quantity": qty,
  3116. "unitPrice": selling_u,
  3117. "amount": selling_amt,
  3118. "sellingUnitPrice": selling_u,
  3119. "sellingAmount": selling_amt,
  3120. "supplierUnitPrice": supplier_u,
  3121. "supplierAmount": supplier_amt,
  3122. "deliveredQuantity": _merged_dq,
  3123. "status": item.status
  3124. })
  3125. order_status = getattr(order, "order_status", None) or "pending_confirm"
  3126. delivery_status = getattr(order, "delivery_status", None) or "pending_dispatch"
  3127. pay_status = getattr(order, "pay_status", None) or "pending_payment"
  3128. # 处理状态日志(含配送任务、配送员分配等结构化记录)
  3129. log_details = []
  3130. for log in status_logs:
  3131. log_details.append({
  3132. "fromStatus": log.from_status,
  3133. "fromStatusText": ORDER_LOG_STATUS_MAP.get(
  3134. log.from_status, log.from_status or ""
  3135. ),
  3136. "status": log.to_status,
  3137. "statusText": ORDER_LOG_STATUS_MAP.get(log.to_status, log.to_status),
  3138. # BizOrderStatusLog 无 operator_name 字段,优先使用 create_name
  3139. "operatorName": getattr(log, "create_name", None) or getattr(log, "operator_id", None),
  3140. "operatorRole": log.operator_role,
  3141. "reason": log.reason,
  3142. "note": log.note,
  3143. "createAt": str(log.create_at) if log.create_at else None
  3144. })
  3145. deliver_id_out = None
  3146. deliver_name = None
  3147. deliver_phone = None
  3148. expected_time = None
  3149. delivery_dispatch_remark = None
  3150. delivery_timeline = []
  3151. supplier_id_for_pickup = None
  3152. supplier_name = None
  3153. supplier_phone = None
  3154. supplier_pickup = {"fullAddress": None, "contactPerson": None, "contactPhone": None}
  3155. delivery_task_no = None
  3156. delivery_task_status = None
  3157. delivery_task_deliverer_status = None
  3158. delivery_task_supplier_prepare_status = None
  3159. delivery_pickup_time = None
  3160. delivery_pickup_remark = None
  3161. delivery_delivery_time = None
  3162. delivery_delivery_remark = None
  3163. delivery_prepare_images = []
  3164. delivery_pickup_images = []
  3165. delivery_deliver_images = []
  3166. from app.crud.delivery import delivery_task_crud as _order_delivery_task_crud
  3167. dtask = _order_delivery_task_crud.get_by_order(db, order_id)
  3168. if dtask:
  3169. deliver_id_out = dtask.deliver_id
  3170. delivery_task_no = dtask.task_no
  3171. delivery_task_status = dtask.status
  3172. delivery_task_deliverer_status = getattr(dtask, "deliverer_status", None)
  3173. delivery_task_supplier_prepare_status = getattr(dtask, "supplier_prepare_status", None)
  3174. delivery_pickup_time = str(dtask.pickup_time) if dtask.pickup_time else None
  3175. delivery_pickup_remark = dtask.pickup_remark
  3176. delivery_delivery_time = str(dtask.delivery_time) if dtask.delivery_time else None
  3177. delivery_delivery_remark = dtask.delivery_remark
  3178. if dtask.deliver_id:
  3179. du = user_crud.get(db, dtask.deliver_id)
  3180. if du:
  3181. deliver_name = du.real_name
  3182. deliver_phone = du.phone
  3183. expected_time = str(dtask.effective_time) if dtask.effective_time else None
  3184. delivery_dispatch_remark = getattr(dtask, "dispatch_remark", None) or None
  3185. supplier_id_for_pickup = dtask.supplier_id
  3186. delivery_timeline = _build_order_delivery_timeline(dtask, log_details, order)
  3187. from app.crud.attachment import attachment_crud as _attachment_crud
  3188. delivery_prepare_images = [
  3189. a.file_url for a in _attachment_crud.get_by_business(db, "delivery_prepare", dtask.id) if a.file_url
  3190. ]
  3191. delivery_pickup_images = [
  3192. a.file_url for a in _attachment_crud.get_by_business(db, "delivery_pickup", dtask.id) if a.file_url
  3193. ]
  3194. delivery_deliver_images = [
  3195. a.file_url for a in _attachment_crud.get_by_business(db, "delivery_deliver", dtask.id) if a.file_url
  3196. ]
  3197. # 兼容旧数据:历史仅写在任务字段中
  3198. if not delivery_pickup_images and getattr(dtask, "pickup_image_url", None):
  3199. delivery_pickup_images = [
  3200. s.strip() for s in str(dtask.pickup_image_url).split(",") if s and str(s).strip()
  3201. ]
  3202. if not delivery_deliver_images and getattr(dtask, "delivery_image_url", None):
  3203. delivery_deliver_images = [
  3204. s.strip() for s in str(dtask.delivery_image_url).split(",") if s and str(s).strip()
  3205. ]
  3206. else:
  3207. from app.crud.price_list import price_list_crud
  3208. _pl = price_list_crud.get(db, order.price_list_id)
  3209. if _pl and getattr(_pl, "supplier_id", None):
  3210. supplier_id_for_pickup = _pl.supplier_id
  3211. delivery_timeline = _build_order_delivery_timeline(None, log_details, order)
  3212. if supplier_id_for_pickup:
  3213. _su = user_crud.get(db, supplier_id_for_pickup)
  3214. if _su:
  3215. supplier_name = _su.real_name
  3216. supplier_phone = _su.phone
  3217. supplier_pickup = _supplier_pickup_address_block(db, supplier_id_for_pickup)
  3218. return success_response({
  3219. "id": order.id,
  3220. "orderNo": order.order_no,
  3221. "regionId": order.region_id,
  3222. "regionName": region_name,
  3223. "regionExpectedDeliveryMinutes": region_expected_delivery_minutes,
  3224. "clientId": order.client_id,
  3225. "clientName": client_name,
  3226. "priceListId": order.price_list_id,
  3227. "priceVersion": order.price_version,
  3228. "status": order.status,
  3229. "orderStatus": order_status,
  3230. "deliveryStatus": delivery_status,
  3231. "payStatus": pay_status,
  3232. "paymentMethod": order_crud.normalize_payment_method(order.payment_method),
  3233. "totalAmount": float(order.total_amount) if order.total_amount else 0,
  3234. "sellingTotalAmount": round(selling_total_amount, 2),
  3235. "supplierTotalAmount": round(supplier_total_amount, 2),
  3236. "paidAmount": float(order.paid_amount) if order.paid_amount else 0,
  3237. "receivableAmount": float(order.receivable_amount) if order.receivable_amount else 0,
  3238. "refundAmount": float(order.refund_amount) if order.refund_amount else 0,
  3239. "contactPerson": order.contact_person,
  3240. "contactPhone": order.contact_phone,
  3241. "deliveryAddress": order.delivery_address,
  3242. "remark": order.remark,
  3243. "cancelReason": order.cancel_reason,
  3244. "cancelReviewNote": order.cancel_review_note,
  3245. "createAt": str(order.create_at) if order.create_at else None,
  3246. "paymentTime": str(order.payment_time) if order.payment_time else None,
  3247. "completedTime": str(order.completed_time) if order.completed_time else None,
  3248. "deliverId": deliver_id_out,
  3249. "deliverName": deliver_name,
  3250. "deliverPhone": deliver_phone,
  3251. "expectedTime": expected_time,
  3252. "deliveryDispatchRemark": delivery_dispatch_remark,
  3253. "deliveryTimeline": delivery_timeline,
  3254. "supplierId": supplier_id_for_pickup,
  3255. "supplierName": supplier_name,
  3256. "supplierPhone": supplier_phone,
  3257. "supplierPickup": {
  3258. "address": supplier_pickup.get("fullAddress"),
  3259. "contactPerson": supplier_pickup.get("contactPerson"),
  3260. "contactPhone": supplier_pickup.get("contactPhone"),
  3261. },
  3262. "deliveryTaskNo": delivery_task_no,
  3263. "deliveryTaskStatus": delivery_task_status,
  3264. "deliveryTaskDelivererStatus": delivery_task_deliverer_status,
  3265. "deliveryTaskSupplierPrepareStatus": delivery_task_supplier_prepare_status,
  3266. "deliveryPickupTime": delivery_pickup_time,
  3267. "deliveryPickupRemark": delivery_pickup_remark,
  3268. "deliveryDeliveryTime": delivery_delivery_time,
  3269. "deliveryDeliveryRemark": delivery_delivery_remark,
  3270. "deliveryPrepareImages": delivery_prepare_images,
  3271. "deliveryPickupImages": delivery_pickup_images,
  3272. "deliveryDeliverImages": delivery_deliver_images,
  3273. "items": item_details,
  3274. "statusLogs": log_details,
  3275. "lockInfo": lock_info
  3276. })
  3277. @router.post("/orders/{order_id}/unlock", response_model=dict)
  3278. def unlock_order(
  3279. order_id: str,
  3280. db: Session = Depends(get_db),
  3281. current_user: dict = Depends(require_admin)
  3282. ):
  3283. """手动解锁订单"""
  3284. from app.crud.order import order_crud
  3285. order = order_crud.get(db, order_id)
  3286. if not order:
  3287. return error_response(404, "订单不存在")
  3288. operator_id = current_user.get("user_id")
  3289. try:
  3290. order_crud.unlock_order(db, order_id, operator_id)
  3291. return success_response({"message": "解锁成功"})
  3292. except ValueError as e:
  3293. return error_response(400, str(e))
  3294. @router.post("/orders/{order_id}/review-cancel", response_model=dict)
  3295. def review_order_cancel(
  3296. order_id: str,
  3297. request: dict,
  3298. db: Session = Depends(get_db),
  3299. current_user: dict = Depends(require_admin)
  3300. ):
  3301. """审核取消订单"""
  3302. from app.crud.order import order_crud
  3303. order = order_crud.get(db, order_id)
  3304. if not order:
  3305. return error_response(404, "订单不存在")
  3306. if getattr(order, "cancel_status", "none") != "pending_review":
  3307. return error_response(400, "只有待审核取消的订单才能审核")
  3308. approved = request.get("approved", False)
  3309. review_note = request.get("reviewNote")
  3310. reviewer_id = current_user.get("user_id")
  3311. order = order_crud.review_cancel(
  3312. db,
  3313. order_id,
  3314. approved=approved,
  3315. reviewer_id=reviewer_id,
  3316. review_note=review_note
  3317. )
  3318. return success_response({
  3319. "id": order.id,
  3320. "status": order.status,
  3321. "orderStatus": getattr(order, "order_status", None),
  3322. "deliveryStatus": getattr(order, "delivery_status", None),
  3323. "payStatus": getattr(order, "pay_status", None),
  3324. "cancelStatus": getattr(order, "cancel_status", None),
  3325. "message": "审核完成"
  3326. })
  3327. @router.get("/orders/pending-cancel", response_model=dict)
  3328. def list_pending_cancel_orders(
  3329. page: int = Query(1, ge=1, description="页码"),
  3330. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  3331. db: Session = Depends(get_db),
  3332. current_user: dict = Depends(require_admin)
  3333. ):
  3334. """获取待审核取消的订单列表"""
  3335. from app.crud.order import order_crud, order_item_crud
  3336. orders, total = order_crud.get_multi_with_filters(
  3337. db,
  3338. cancel_status="pending_review",
  3339. skip=(page - 1) * pageSize,
  3340. limit=pageSize
  3341. )
  3342. region_map = {}
  3343. client_map = {}
  3344. result = []
  3345. for order in orders:
  3346. if order.region_id and order.region_id not in region_map:
  3347. region = region_crud.get(db, order.region_id)
  3348. region_map[order.region_id] = region.name if region else None
  3349. if order.client_id and order.client_id not in client_map:
  3350. client = user_crud.get(db, order.client_id)
  3351. client_map[order.client_id] = client.real_name if client else None
  3352. item_count = order_item_crud.get_count_by_order(db, order.id)
  3353. result.append({
  3354. "id": order.id,
  3355. "orderNo": order.order_no,
  3356. "clientId": order.client_id,
  3357. "clientName": client_map.get(order.client_id),
  3358. "regionId": order.region_id,
  3359. "regionName": region_map.get(order.region_id),
  3360. "totalAmount": float(order.total_amount) if order.total_amount else 0,
  3361. "paidAmount": float(order.paid_amount) if order.paid_amount else 0,
  3362. "cancelReason": order.cancel_reason,
  3363. "itemCount": item_count,
  3364. "createAt": str(order.create_at) if order.create_at else None
  3365. })
  3366. return success_response({
  3367. "list": result,
  3368. "total": total,
  3369. "page": page,
  3370. "pageSize": pageSize,
  3371. "totalPages": (total + pageSize - 1) // pageSize
  3372. })
  3373. # =========================================
  3374. # 订单锁定管理 API
  3375. # =========================================
  3376. @router.post("/orders/{order_id}/lock", response_model=dict)
  3377. def lock_order(
  3378. order_id: str,
  3379. db: Session = Depends(get_db),
  3380. current_user: dict = Depends(require_admin)
  3381. ):
  3382. """锁定订单"""
  3383. from app.crud.order import order_crud
  3384. order = order_crud.get(db, order_id)
  3385. if not order:
  3386. return error_response(404, "订单不存在")
  3387. try:
  3388. order = order_crud.lock_order(
  3389. db,
  3390. order_id=order_id,
  3391. operator_id=current_user.get("user_id")
  3392. )
  3393. return success_response({
  3394. "id": order.id,
  3395. "lockOperatorId": order.lock_operator_id,
  3396. "lockTime": str(order.lock_time) if order.lock_time else None,
  3397. "message": "锁定成功"
  3398. })
  3399. except ValueError as e:
  3400. return error_response(400, str(e))
  3401. @router.post("/orders/{order_id}/unlock", response_model=dict)
  3402. def unlock_order(
  3403. order_id: str,
  3404. db: Session = Depends(get_db),
  3405. current_user: dict = Depends(require_admin)
  3406. ):
  3407. """解锁订单"""
  3408. from app.crud.order import order_crud
  3409. order = order_crud.get(db, order_id)
  3410. if not order:
  3411. return error_response(404, "订单不存在")
  3412. try:
  3413. order = order_crud.unlock_order(
  3414. db,
  3415. order_id=order_id,
  3416. operator_id=current_user.get("user_id")
  3417. )
  3418. return success_response({
  3419. "id": order.id,
  3420. "message": "解锁成功"
  3421. })
  3422. except ValueError as e:
  3423. return error_response(400, str(e))
  3424. # =========================================
  3425. # 订单调整管理 API
  3426. # =========================================
  3427. @router.post("/orders/{order_id}/adjust", response_model=dict)
  3428. def adjust_order(
  3429. order_id: str,
  3430. request: dict,
  3431. db: Session = Depends(get_db),
  3432. current_user: dict = Depends(require_admin)
  3433. ):
  3434. """订单调整(增量/减量/删除/替代)"""
  3435. import json
  3436. from app.crud.order import order_crud, order_item_crud, order_adjust_crud
  3437. from decimal import Decimal
  3438. from app.models.models import BizDeliveryTask, BizDeliveryTaskItem
  3439. order = order_crud.get(db, order_id)
  3440. if not order:
  3441. return error_response(404, "订单不存在")
  3442. # 检查订单是否被其他操作员锁定
  3443. operator_id = current_user.get("user_id")
  3444. if order.lock_operator_id and order.lock_operator_id != operator_id:
  3445. lock_time = order.lock_time.strftime("%Y-%m-%d %H:%M:%S") if order.lock_time else "未知"
  3446. return error_response(400, f"订单已被其他操作员于 {lock_time} 锁定,请先解锁后再操作")
  3447. # 仅线下支付订单允许运营调整
  3448. if getattr(order, "payment_method", None) != "offline":
  3449. return error_response(400, "仅线下支付订单支持运营调整")
  3450. # 新状态模型:仅未完成/未取消的线下单支持调整
  3451. if getattr(order, "order_status", None) not in ["pending_payment", "pending_confirm"]:
  3452. return error_response(400, "当前状态不支持调整")
  3453. adjustments = request.get("adjustments", [])
  3454. address_update = request.get("addressUpdate") or {}
  3455. has_address_update = isinstance(address_update, dict) and len(address_update.keys()) > 0
  3456. if not adjustments and not has_address_update:
  3457. return error_response(400, "请提供调整项或地址调整信息")
  3458. operator_name = current_user.get("real_name")
  3459. adjust_results = []
  3460. for adj in adjustments:
  3461. order_item_id = adj.get("orderItemId")
  3462. adjust_type = adj.get("adjustType") # increase/reduce/delete/substitute
  3463. new_quantity = adj.get("newQuantity")
  3464. new_product_id = adj.get("newProductId")
  3465. reason = adj.get("reason")
  3466. if not order_item_id or not adjust_type:
  3467. continue
  3468. if not reason:
  3469. return error_response(400, "调整原因不能为空")
  3470. # 获取订单项
  3471. item = order_item_crud.get(db, order_item_id)
  3472. if not item or item.order_id != order_id:
  3473. continue
  3474. before_quantity = item.quantity
  3475. before_amount = item.amount
  3476. try:
  3477. if adjust_type == "increase":
  3478. # 增量
  3479. if new_quantity is None or new_quantity < 0:
  3480. return error_response(400, "增量后数量不能小于0")
  3481. if new_quantity < float(item.quantity):
  3482. return error_response(400, "增量后数量不能小于原数量")
  3483. new_amount = Decimal(str(new_quantity)) * item.unit_price
  3484. order_item_crud.update_item_adjustment(
  3485. db, order_item_id,
  3486. new_quantity=Decimal(str(new_quantity)),
  3487. new_amount=new_amount,
  3488. new_status="increased",
  3489. note=reason,
  3490. updater_id=operator_id,
  3491. updater_name=operator_name
  3492. )
  3493. snapshot_items = order_item_crud.get_by_order(db, order_id)
  3494. snapshot = [{
  3495. "orderItemId": it.id,
  3496. "productId": it.product_id,
  3497. "quantity": float(it.quantity) if it.quantity else 0,
  3498. "status": it.status,
  3499. } for it in snapshot_items if it.is_del == 0]
  3500. order_adjust_crud.create_adjust_record(
  3501. db,
  3502. order_id=order_id,
  3503. order_item_id=order_item_id,
  3504. adjust_type="increase",
  3505. operator_id=operator_id,
  3506. operator_name=operator_name,
  3507. before_quantity=before_quantity,
  3508. after_quantity=Decimal(str(new_quantity)),
  3509. before_amount=before_amount,
  3510. after_amount=new_amount,
  3511. difference_amount=new_amount - before_amount,
  3512. reason=reason,
  3513. snapshot_items_json=json.dumps(snapshot, ensure_ascii=False)
  3514. )
  3515. adjust_results.append({
  3516. "orderItemId": order_item_id,
  3517. "adjustType": "increase",
  3518. "success": True
  3519. })
  3520. elif adjust_type == "reduce":
  3521. # 减量
  3522. if new_quantity is None or new_quantity < 0:
  3523. return error_response(400, "减量后数量不能小于0")
  3524. if new_quantity > float(item.quantity):
  3525. return error_response(400, "减量后数量不能大于原数量")
  3526. new_amount = Decimal(str(new_quantity)) * item.unit_price
  3527. order_item_crud.mark_as_reduced(
  3528. db, order_item_id,
  3529. new_quantity=Decimal(str(new_quantity)),
  3530. new_amount=new_amount,
  3531. note=reason
  3532. )
  3533. snapshot_items = order_item_crud.get_by_order(db, order_id)
  3534. snapshot = [{
  3535. "orderItemId": it.id,
  3536. "productId": it.product_id,
  3537. "quantity": float(it.quantity) if it.quantity else 0,
  3538. "status": it.status,
  3539. } for it in snapshot_items if it.is_del == 0]
  3540. # 创建调整记录
  3541. order_adjust_crud.create_adjust_record(
  3542. db,
  3543. order_id=order_id,
  3544. order_item_id=order_item_id,
  3545. adjust_type="reduce",
  3546. operator_id=operator_id,
  3547. operator_name=operator_name,
  3548. before_quantity=before_quantity,
  3549. after_quantity=Decimal(str(new_quantity)),
  3550. before_amount=before_amount,
  3551. after_amount=new_amount,
  3552. difference_amount=new_amount - before_amount,
  3553. reason=reason,
  3554. snapshot_items_json=json.dumps(snapshot, ensure_ascii=False)
  3555. )
  3556. adjust_results.append({
  3557. "orderItemId": order_item_id,
  3558. "adjustType": "reduce",
  3559. "success": True
  3560. })
  3561. elif adjust_type == "delete":
  3562. # 删除
  3563. order_item_crud.mark_as_deleted(
  3564. db, order_item_id,
  3565. note=reason
  3566. )
  3567. snapshot_items = order_item_crud.get_by_order(db, order_id)
  3568. snapshot = [{
  3569. "orderItemId": it.id,
  3570. "productId": it.product_id,
  3571. "quantity": float(it.quantity) if it.quantity else 0,
  3572. "status": it.status,
  3573. } for it in snapshot_items if it.is_del == 0]
  3574. # 创建调整记录
  3575. order_adjust_crud.create_adjust_record(
  3576. db,
  3577. order_id=order_id,
  3578. order_item_id=order_item_id,
  3579. adjust_type="delete",
  3580. operator_id=operator_id,
  3581. operator_name=operator_name,
  3582. before_quantity=before_quantity,
  3583. after_quantity=Decimal("0"),
  3584. before_amount=before_amount,
  3585. after_amount=Decimal("0"),
  3586. difference_amount=-before_amount,
  3587. reason=reason,
  3588. snapshot_items_json=json.dumps(snapshot, ensure_ascii=False)
  3589. )
  3590. adjust_results.append({
  3591. "orderItemId": order_item_id,
  3592. "adjustType": "delete",
  3593. "success": True
  3594. })
  3595. elif adjust_type == "substitute":
  3596. # 替代
  3597. if not new_product_id or not new_quantity:
  3598. return error_response(400, "替代商品ID和数量不能为空")
  3599. # 获取新商品信息
  3600. new_product = product_crud.get(db, new_product_id)
  3601. if not new_product:
  3602. return error_response(404, "替代商品不存在")
  3603. # 需要获取新商品的价格
  3604. from app.crud.price_list import price_list_item_crud
  3605. price_item = price_list_item_crud.get_by_product_and_price_list(
  3606. db, new_product_id, order.price_list_id
  3607. )
  3608. if not price_item:
  3609. return error_response(400, "替代商品不在价格清单中")
  3610. new_unit_price = price_item.price
  3611. new_amount = Decimal(str(new_quantity)) * new_unit_price
  3612. order_item_crud.update_item_adjustment(
  3613. db, order_item_id,
  3614. new_quantity=Decimal(str(new_quantity)),
  3615. new_amount=new_amount,
  3616. new_status="substituted",
  3617. note=f"{reason},替代商品: {new_product.name}",
  3618. updater_id=operator_id,
  3619. updater_name=operator_name
  3620. )
  3621. snapshot_items = order_item_crud.get_by_order(db, order_id)
  3622. snapshot = [{
  3623. "orderItemId": it.id,
  3624. "productId": it.product_id,
  3625. "quantity": float(it.quantity) if it.quantity else 0,
  3626. "status": it.status,
  3627. } for it in snapshot_items if it.is_del == 0]
  3628. # 创建调整记录
  3629. order_adjust_crud.create_adjust_record(
  3630. db,
  3631. order_id=order_id,
  3632. order_item_id=order_item_id,
  3633. adjust_type="substitute",
  3634. operator_id=operator_id,
  3635. operator_name=operator_name,
  3636. before_quantity=before_quantity,
  3637. after_quantity=Decimal(str(new_quantity)),
  3638. before_amount=before_amount,
  3639. after_amount=new_amount,
  3640. difference_amount=new_amount - before_amount,
  3641. reason=reason,
  3642. substitute_product_id=new_product_id,
  3643. snapshot_items_json=json.dumps(snapshot, ensure_ascii=False)
  3644. )
  3645. adjust_results.append({
  3646. "orderItemId": order_item_id,
  3647. "adjustType": "substitute",
  3648. "newProductId": new_product_id,
  3649. "success": True
  3650. })
  3651. except Exception as e:
  3652. adjust_results.append({
  3653. "orderItemId": order_item_id,
  3654. "adjustType": adjust_type,
  3655. "success": False,
  3656. "error": str(e)
  3657. })
  3658. if has_address_update:
  3659. old_delivery_address = order.delivery_address or ""
  3660. old_contact_person = order.contact_person or ""
  3661. old_contact_phone = order.contact_phone or ""
  3662. new_delivery_address = str(address_update.get("deliveryAddress") or old_delivery_address).strip()
  3663. new_contact_person = str(address_update.get("contactPerson") or old_contact_person).strip()
  3664. new_contact_phone = str(address_update.get("contactPhone") or old_contact_phone).strip()
  3665. address_reason = str(address_update.get("reason") or "").strip()
  3666. address_changed = (
  3667. new_delivery_address != old_delivery_address
  3668. or new_contact_person != old_contact_person
  3669. or new_contact_phone != old_contact_phone
  3670. )
  3671. if address_changed:
  3672. order.delivery_address = new_delivery_address
  3673. order.contact_person = new_contact_person
  3674. order.contact_phone = new_contact_phone
  3675. active_task = db.query(BizDeliveryTask).filter(
  3676. BizDeliveryTask.order_id == order_id,
  3677. BizDeliveryTask.is_del == 0
  3678. ).first()
  3679. if active_task:
  3680. task_items = db.query(BizDeliveryTaskItem).filter(
  3681. BizDeliveryTaskItem.task_id == active_task.id,
  3682. BizDeliveryTaskItem.is_del == 0
  3683. ).all()
  3684. for task_item in task_items:
  3685. task_item.delivery_address = new_delivery_address
  3686. task_item.contact_person = new_contact_person
  3687. task_item.contact_phone = new_contact_phone
  3688. task_item.update_at = datetime.now()
  3689. snapshot_items = order_item_crud.get_by_order(db, order_id)
  3690. snapshot = [{
  3691. "orderItemId": it.id,
  3692. "productId": it.product_id,
  3693. "quantity": float(it.quantity) if it.quantity else 0,
  3694. "status": it.status,
  3695. } for it in snapshot_items if it.is_del == 0]
  3696. reason_parts = []
  3697. reason_parts.append(f"地址:{old_delivery_address or '-'} -> {new_delivery_address or '-'}")
  3698. reason_parts.append(f"联系人:{old_contact_person or '-'} -> {new_contact_person or '-'}")
  3699. reason_parts.append(f"电话:{old_contact_phone or '-'} -> {new_contact_phone or '-'}")
  3700. if address_reason:
  3701. reason_parts.append(f"备注:{address_reason}")
  3702. address_log_reason = ";".join(reason_parts)
  3703. order_adjust_crud.create_adjust_record(
  3704. db,
  3705. order_id=order_id,
  3706. order_item_id=None,
  3707. adjust_type="address",
  3708. operator_id=operator_id,
  3709. operator_name=operator_name,
  3710. before_quantity=Decimal("0"),
  3711. after_quantity=Decimal("0"),
  3712. before_amount=Decimal("0"),
  3713. after_amount=Decimal("0"),
  3714. difference_amount=Decimal("0"),
  3715. reason=address_log_reason,
  3716. snapshot_items_json=json.dumps(snapshot, ensure_ascii=False)
  3717. )
  3718. adjust_results.append({
  3719. "adjustType": "address",
  3720. "success": True
  3721. })
  3722. # 重新计算订单应收金额
  3723. all_items = order_item_crud.get_by_order(db, order_id)
  3724. new_total = sum(
  3725. float(item.amount) for item in all_items
  3726. if item.status != "deleted" and item.is_del == 0
  3727. )
  3728. new_receivable = Decimal(str(new_total))
  3729. order.total_amount = new_receivable
  3730. order.receivable_amount = new_receivable
  3731. order.update_at = datetime.now()
  3732. db.commit()
  3733. db.refresh(order)
  3734. return success_response({
  3735. "id": order.id,
  3736. "totalAmount": float(order.total_amount),
  3737. "receivableAmount": float(order.receivable_amount),
  3738. "adjustments": adjust_results,
  3739. "message": "调整成功"
  3740. })
  3741. @router.get("/orders/{order_id}/adjusts", response_model=dict)
  3742. def list_order_adjusts(
  3743. order_id: str,
  3744. db: Session = Depends(get_db),
  3745. current_user: dict = Depends(require_admin)
  3746. ):
  3747. """获取订单调整记录"""
  3748. import json
  3749. from app.crud.order import order_crud, order_adjust_crud
  3750. order = order_crud.get(db, order_id)
  3751. if not order:
  3752. return error_response(404, "订单不存在")
  3753. adjusts = order_adjust_crud.get_by_order(db, order_id)
  3754. result = []
  3755. for adj in adjusts:
  3756. result.append({
  3757. "id": adj.id,
  3758. "orderId": adj.order_id,
  3759. "orderItemId": adj.order_item_id,
  3760. "adjustType": adj.adjust_type,
  3761. "beforeQuantity": float(adj.before_quantity) if adj.before_quantity else 0,
  3762. "afterQuantity": float(adj.after_quantity) if adj.after_quantity else 0,
  3763. "beforeAmount": float(adj.before_amount) if adj.before_amount else 0,
  3764. "afterAmount": float(adj.after_amount) if adj.after_amount else 0,
  3765. "differenceAmount": float(adj.difference_amount) if adj.difference_amount else 0,
  3766. "reason": adj.reason,
  3767. "snapshotItems": json.loads(adj.snapshot_items_json) if getattr(adj, "snapshot_items_json", None) else [],
  3768. "operatorName": adj.operator_name,
  3769. "createAt": str(adj.create_at) if adj.create_at else None
  3770. })
  3771. return success_response({
  3772. "list": result,
  3773. "total": len(result)
  3774. })
  3775. @router.post("/orders/{order_id}/force-complete", response_model=dict)
  3776. def force_complete_order(
  3777. order_id: str,
  3778. request: dict,
  3779. db: Session = Depends(get_db),
  3780. current_user: dict = Depends(require_admin)
  3781. ):
  3782. """运营强制完结订单"""
  3783. from app.crud.order import order_crud
  3784. order = order_crud.get(db, order_id)
  3785. if not order:
  3786. return error_response(404, "订单不存在")
  3787. reason = request.get("reason", "运营强制完结")
  3788. try:
  3789. order = order_crud.force_complete(
  3790. db,
  3791. order_id=order_id,
  3792. operator_id=current_user.get("user_id"),
  3793. operator_role="admin",
  3794. reason=reason
  3795. )
  3796. return success_response({
  3797. "id": order.id,
  3798. "status": order.status,
  3799. "orderStatus": getattr(order, "order_status", None) or "pending_confirm",
  3800. "deliveryStatus": getattr(order, "delivery_status", None) or "pending_dispatch",
  3801. "payStatus": getattr(order, "pay_status", None) or "pending_payment",
  3802. "completedTime": str(order.completed_time) if order.completed_time else None,
  3803. "message": "强制完结成功"
  3804. })
  3805. except ValueError as e:
  3806. return error_response(400, str(e))
  3807. @router.post("/orders/{order_id}/partial-delivered", response_model=dict)
  3808. def mark_partial_delivered(
  3809. order_id: str,
  3810. request: dict,
  3811. db: Session = Depends(get_db),
  3812. current_user: dict = Depends(require_admin)
  3813. ):
  3814. """已废弃:旧的部分送达流程不再支持。"""
  3815. return error_response(410, "该接口已下线,请使用配送任务状态流转接口")
  3816. @router.post("/orders/{order_id}/confirm-partial", response_model=dict)
  3817. def confirm_partial_delivery(
  3818. order_id: str,
  3819. request: dict,
  3820. db: Session = Depends(get_db),
  3821. current_user: dict = Depends(require_admin)
  3822. ):
  3823. """已废弃:旧的部分送达确认流程不再支持。"""
  3824. return error_response(410, "该接口已下线,请使用订单确认收货流程")
  3825. @router.post("/orders/{order_id}/create-delivery-task", response_model=dict)
  3826. def create_delivery_task_from_order(
  3827. order_id: str,
  3828. db: Session = Depends(get_db),
  3829. current_user: dict = Depends(require_admin)
  3830. ):
  3831. """从订单创建配送任务"""
  3832. from app.crud.order import order_crud, order_item_crud
  3833. from app.crud.delivery import delivery_task_crud, delivery_task_item_crud
  3834. order = order_crud.get(db, order_id)
  3835. if not order:
  3836. return error_response(404, "订单不存在")
  3837. # 只有待分配配送状态可以创建配送任务
  3838. if getattr(order, "delivery_status", None) != "pending_dispatch":
  3839. return error_response(400, "只有待分配配送状态的订单可以创建配送任务")
  3840. # 检查是否已存在配送任务
  3841. existing_task = delivery_task_crud.get_by_order(db, order_id)
  3842. if existing_task:
  3843. return error_response(400, "该订单已存在配送任务")
  3844. # 获取订单关联的价格清单,以获取供应商ID
  3845. from app.crud.price_list import price_list_crud
  3846. price_list = price_list_crud.get(db, order.price_list_id)
  3847. if not price_list:
  3848. return error_response(400, "订单关联的价格清单不存在")
  3849. supplier_id = price_list.supplier_id
  3850. # 获取订单项
  3851. order_items = order_item_crud.get_by_order(db, order_id)
  3852. # 构建配送任务明细数据
  3853. task_items_data = []
  3854. for item in order_items:
  3855. if item.status == "deleted" or item.is_del != 0:
  3856. continue
  3857. task_items_data.append({
  3858. "order_item_id": item.id,
  3859. "product_id": item.product_id,
  3860. "client_id": order.client_id,
  3861. "delivery_address": order.delivery_address,
  3862. "contact_person": order.contact_person,
  3863. "contact_phone": order.contact_phone,
  3864. "quantity": float(item.quantity) if item.quantity else 0
  3865. })
  3866. creator = {
  3867. "user_id": current_user.get("user_id"),
  3868. "real_name": current_user.get("real_name")
  3869. }
  3870. # 创建配送任务及明细
  3871. task, task_items = delivery_task_crud.create_delivery_task_from_order(
  3872. db,
  3873. order_id=order_id,
  3874. order_items=task_items_data,
  3875. supplier_id=supplier_id,
  3876. region_id=order.region_id,
  3877. creator=creator
  3878. )
  3879. # 阶段D收尾:优先维护三字段,再回写旧 status
  3880. from app.core.order_status_compat import derive_legacy_status_from_three
  3881. order.order_status = "pending_confirm"
  3882. order.delivery_status = "delivering"
  3883. order.status = derive_legacy_status_from_three(
  3884. order_status=order.order_status,
  3885. delivery_status=order.delivery_status,
  3886. pay_status=order.pay_status,
  3887. )
  3888. order.delivery_assign_time = datetime.now()
  3889. order.update_at = datetime.now()
  3890. db.commit()
  3891. return success_response({
  3892. "id": task.id,
  3893. "taskNo": task.task_no,
  3894. "status": task.status,
  3895. "effectiveTime": str(task.effective_time) if task.effective_time else None,
  3896. "message": "配送任务创建成功"
  3897. })
  3898. @router.post("/orders/{order_id}/assign-deliverer", response_model=dict)
  3899. def assign_deliverer_to_order(
  3900. order_id: str,
  3901. request: dict,
  3902. db: Session = Depends(get_db),
  3903. current_user: dict = Depends(require_admin)
  3904. ):
  3905. """分配配送员并创建配送任务(一步完成)"""
  3906. from app.crud.order import order_crud, order_item_crud
  3907. from app.crud.delivery import delivery_task_crud
  3908. order = order_crud.get(db, order_id)
  3909. if not order:
  3910. return error_response(404, "订单不存在")
  3911. # 检查订单是否被其他操作员锁定
  3912. operator_id = current_user.get("user_id")
  3913. if order.lock_operator_id and order.lock_operator_id != operator_id:
  3914. lock_time = order.lock_time.strftime("%Y-%m-%d %H:%M:%S") if order.lock_time else "未知"
  3915. return error_response(400, f"订单已被其他操作员于 {lock_time} 锁定,请先解锁后再操作")
  3916. deliver_id = request.get("deliverId")
  3917. if not deliver_id:
  3918. return error_response(400, "请选择配送员")
  3919. deadline_raw = request.get("deliveryDeadlineAt") or request.get("delivery_deadline_at")
  3920. if not deadline_raw:
  3921. return error_response(400, "请选择配送时效(截止时间)")
  3922. dispatch_remark_raw = request.get("dispatchRemark") or request.get("dispatch_remark") or ""
  3923. dispatch_remark = str(dispatch_remark_raw).strip()[:500] if dispatch_remark_raw else None
  3924. effective_deadline = None
  3925. try:
  3926. ds = str(deadline_raw).strip().replace("Z", "+00:00")
  3927. effective_deadline = datetime.fromisoformat(ds)
  3928. if effective_deadline.tzinfo is not None:
  3929. effective_deadline = effective_deadline.replace(tzinfo=None)
  3930. except (TypeError, ValueError):
  3931. effective_deadline = None
  3932. if not effective_deadline:
  3933. return error_response(400, "配送时效格式不正确")
  3934. # 验证配送员
  3935. deliver = user_crud.get(db, deliver_id)
  3936. if not deliver:
  3937. return error_response(404, "配送员不存在")
  3938. if deliver.role != "deliver":
  3939. return error_response(400, "该用户不是配送员")
  3940. if not deliver.region_id or deliver.region_id != order.region_id:
  3941. return error_response(400, "只能选择订单所属区域的配送员")
  3942. prev_delivery_status = getattr(order, "delivery_status", None) or "pending_dispatch"
  3943. operator_name = (current_user.get("real_name") or "").strip() or None
  3944. updater = {"user_id": operator_id, "real_name": operator_name}
  3945. # 检查是否已存在配送任务
  3946. existing_task = delivery_task_crud.get_by_order(db, order_id)
  3947. old_deliver_id = existing_task.deliver_id if existing_task else None
  3948. if existing_task:
  3949. task = delivery_task_crud.update_with_history(
  3950. db,
  3951. existing_task.id,
  3952. {
  3953. "deliver_id": deliver_id,
  3954. "status": "assigned",
  3955. "effective_time": effective_deadline,
  3956. "dispatch_remark": dispatch_remark,
  3957. },
  3958. updater=updater,
  3959. )
  3960. if not task:
  3961. return error_response(400, "更新配送任务失败")
  3962. else:
  3963. # 获取供应商ID
  3964. from app.crud.price_list import price_list_crud
  3965. price_list = price_list_crud.get(db, order.price_list_id)
  3966. if not price_list:
  3967. return error_response(400, "订单关联的价格清单不存在")
  3968. # 获取订单项
  3969. order_items = order_item_crud.get_by_order(db, order_id)
  3970. # 构建配送任务明细数据
  3971. task_items_data = []
  3972. for item in order_items:
  3973. if item.status == "deleted" or item.is_del != 0:
  3974. continue
  3975. task_items_data.append({
  3976. "order_item_id": item.id,
  3977. "product_id": item.product_id,
  3978. "client_id": order.client_id,
  3979. "delivery_address": order.delivery_address,
  3980. "contact_person": order.contact_person,
  3981. "contact_phone": order.contact_phone,
  3982. "quantity": float(item.quantity) if item.quantity else 0
  3983. })
  3984. creator = {
  3985. "user_id": current_user.get("user_id"),
  3986. "real_name": current_user.get("real_name")
  3987. }
  3988. # 创建配送任务
  3989. task, _ = delivery_task_crud.create_delivery_task_from_order(
  3990. db,
  3991. order_id=order_id,
  3992. order_items=task_items_data,
  3993. supplier_id=price_list.supplier_id,
  3994. region_id=order.region_id,
  3995. creator=creator
  3996. )
  3997. # 分配配送员
  3998. task.deliver_id = deliver_id
  3999. task.status = "assigned"
  4000. task.effective_time = effective_deadline
  4001. task.dispatch_remark = dispatch_remark
  4002. task.update_at = datetime.now()
  4003. # 分配配送员后同步双状态;首次分配时供应商从待备货起算,更换配送员不重置备货进度
  4004. if task and task.deliver_id:
  4005. task.deliverer_status = "pending_pickup"
  4006. if not old_deliver_id:
  4007. task.supplier_prepare_status = "pending_prepare"
  4008. delivery_task_crud._sync_legacy_status_from_dual(task)
  4009. # 阶段D收尾:优先维护三字段,再回写旧 status
  4010. from app.core.order_status_compat import derive_legacy_status_from_three
  4011. order.order_status = "pending_confirm"
  4012. if not order.delivery_status or order.delivery_status == "pending_dispatch":
  4013. order.delivery_status = "delivering"
  4014. order.status = derive_legacy_status_from_three(
  4015. order_status=order.order_status,
  4016. delivery_status=order.delivery_status,
  4017. pay_status=order.pay_status,
  4018. )
  4019. order.delivery_assign_time = datetime.now()
  4020. order.update_at = datetime.now()
  4021. def _deliver_display_name(uid: Optional[str]) -> Optional[str]:
  4022. if not uid:
  4023. return None
  4024. u = user_crud.get(db, uid)
  4025. return (u.real_name if u else None) or uid
  4026. if not existing_task:
  4027. order_crud._create_status_log(
  4028. db,
  4029. order_id,
  4030. "",
  4031. "delivery.assign",
  4032. operator_id,
  4033. "admin",
  4034. reason=json.dumps(
  4035. {
  4036. "fromDeliverId": None,
  4037. "toDeliverId": deliver_id,
  4038. "fromDeliverName": None,
  4039. "toDeliverName": deliver.real_name,
  4040. },
  4041. ensure_ascii=False,
  4042. ),
  4043. create_name=operator_name,
  4044. )
  4045. elif old_deliver_id and old_deliver_id != deliver_id:
  4046. order_crud._create_status_log(
  4047. db,
  4048. order_id,
  4049. "",
  4050. "delivery.reassign",
  4051. operator_id,
  4052. "admin",
  4053. reason=json.dumps(
  4054. {
  4055. "fromDeliverId": old_deliver_id,
  4056. "toDeliverId": deliver_id,
  4057. "fromDeliverName": _deliver_display_name(old_deliver_id),
  4058. "toDeliverName": deliver.real_name,
  4059. },
  4060. ensure_ascii=False,
  4061. ),
  4062. create_name=operator_name,
  4063. )
  4064. elif not old_deliver_id and deliver_id:
  4065. order_crud._create_status_log(
  4066. db,
  4067. order_id,
  4068. "",
  4069. "delivery.assign",
  4070. operator_id,
  4071. "admin",
  4072. reason=json.dumps(
  4073. {
  4074. "fromDeliverId": None,
  4075. "toDeliverId": deliver_id,
  4076. "fromDeliverName": None,
  4077. "toDeliverName": deliver.real_name,
  4078. },
  4079. ensure_ascii=False,
  4080. ),
  4081. create_name=operator_name,
  4082. )
  4083. if prev_delivery_status != order.delivery_status:
  4084. order_crud._create_status_log(
  4085. db,
  4086. order_id,
  4087. f"ds_{prev_delivery_status}",
  4088. f"ds_{order.delivery_status}",
  4089. operator_id,
  4090. "admin",
  4091. create_name=operator_name,
  4092. )
  4093. db.commit()
  4094. db.refresh(task)
  4095. return success_response({
  4096. "id": task.id,
  4097. "taskNo": task.task_no,
  4098. "deliverId": task.deliver_id,
  4099. "deliverName": deliver.real_name,
  4100. "status": task.status,
  4101. "effectiveTime": str(task.effective_time) if task.effective_time else None,
  4102. "message": "配送员分配成功"
  4103. })
  4104. @router.post("/orders/{order_id}/assign-delivery", response_model=dict)
  4105. def assign_delivery_alias(
  4106. order_id: str,
  4107. request: dict,
  4108. db: Session = Depends(get_db),
  4109. current_user: dict = Depends(require_admin)
  4110. ):
  4111. """兼容旧路径:与 assign-deliverer 相同"""
  4112. return assign_deliverer_to_order(order_id, request, db, current_user)
  4113. # =========================================
  4114. # 结算管理 API (Web端)
  4115. # =========================================
  4116. def _build_settlement_no(prefix: str) -> str:
  4117. return f"{prefix}{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4().hex)[:6].upper()}"
  4118. def _parse_datetime_range(start_date: Optional[str], end_date: Optional[str]):
  4119. dt_start = None
  4120. dt_end = None
  4121. if start_date:
  4122. try:
  4123. dt_start = datetime.fromisoformat(start_date.replace("Z", "+00:00"))
  4124. except Exception:
  4125. dt_start = None
  4126. if end_date:
  4127. try:
  4128. dt_end = datetime.fromisoformat(end_date.replace("Z", "+00:00"))
  4129. except Exception:
  4130. dt_end = None
  4131. return dt_start, dt_end
  4132. def _supplier_unit_yuan_from_pli(pli: Optional[BizPriceListItem]) -> Optional[float]:
  4133. """价格清单行 price 为面向客户的最终单价;pricing_coefficient 为调价系数(%),供货单价 = price / (1 + 系数/100)。"""
  4134. if pli is None or getattr(pli, "price", None) is None:
  4135. return None
  4136. final_price = Decimal(str(pli.price))
  4137. raw_coeff = getattr(pli, "pricing_coefficient", None)
  4138. if raw_coeff is None:
  4139. coeff_pct = Decimal("0")
  4140. else:
  4141. try:
  4142. coeff_pct = Decimal(str(raw_coeff))
  4143. except Exception:
  4144. coeff_pct = Decimal("0")
  4145. factor = Decimal("1") + coeff_pct / Decimal("100")
  4146. if factor <= Decimal("0"):
  4147. factor = Decimal("1")
  4148. supplier_unit = (final_price / factor).quantize(Decimal("0.01"))
  4149. return float(supplier_unit)
  4150. def _price_list_item_map(db: Session, price_list_ids: List[str]) -> dict:
  4151. """(price_list_id, product_id, unit_id) -> BizPriceListItem"""
  4152. if not price_list_ids:
  4153. return {}
  4154. rows = (
  4155. db.query(BizPriceListItem)
  4156. .filter(BizPriceListItem.price_list_id.in_(price_list_ids), BizPriceListItem.is_del == 0)
  4157. .all()
  4158. )
  4159. return {(r.price_list_id, r.product_id, r.unit_id): r for r in rows}
  4160. def _batch_supplier_totals_for_orders(db: Session, order_ids: List[str]) -> dict:
  4161. """订单维度供货价合计(元),用于供应商结算。"""
  4162. if not order_ids:
  4163. return {}
  4164. orders = db.query(BizOrder).filter(BizOrder.id.in_(order_ids), BizOrder.is_del == 0).all()
  4165. om = {o.id: o for o in orders}
  4166. lines = (
  4167. db.query(BizOrderItem)
  4168. .filter(BizOrderItem.order_id.in_(order_ids), BizOrderItem.is_del == 0)
  4169. .all()
  4170. )
  4171. by_oid: dict = {}
  4172. for ln in lines:
  4173. by_oid.setdefault(ln.order_id, []).append(ln)
  4174. pl_ids = list({om[oid].price_list_id for oid in order_ids if oid in om and om[oid].price_list_id})
  4175. pli_map = _price_list_item_map(db, pl_ids)
  4176. out: dict = {}
  4177. for oid in order_ids:
  4178. o = om.get(oid)
  4179. if not o:
  4180. out[oid] = 0.0
  4181. continue
  4182. tot = Decimal("0")
  4183. for ln in by_oid.get(oid, []):
  4184. pli = pli_map.get((o.price_list_id, ln.product_id, ln.unit_id))
  4185. sup_u = _supplier_unit_yuan_from_pli(pli)
  4186. if sup_u is None:
  4187. sup_u = float(ln.unit_price or 0)
  4188. qty = Decimal(str(ln.quantity or 0))
  4189. tot += qty * Decimal(str(sup_u))
  4190. out[oid] = float(tot.quantize(Decimal("0.01")))
  4191. return out
  4192. def _build_order_line_children_for_settlement_list(
  4193. db: Session,
  4194. order: BizOrder,
  4195. lines: List[BizOrderItem],
  4196. pli_map: dict,
  4197. product_map: dict,
  4198. unit_map: dict,
  4199. ) -> List[dict]:
  4200. children: List[dict] = []
  4201. for ln in lines:
  4202. p = product_map.get(ln.product_id)
  4203. u = unit_map.get(ln.unit_id)
  4204. pli = pli_map.get((order.price_list_id, ln.product_id, ln.unit_id))
  4205. sup_u = _supplier_unit_yuan_from_pli(pli)
  4206. if sup_u is None:
  4207. sup_u = float(ln.unit_price or 0)
  4208. sell_u = float(ln.unit_price or 0)
  4209. qty = float(ln.quantity or 0)
  4210. sell_amt = float(ln.amount or 0) if ln.amount is not None else round(qty * sell_u, 2)
  4211. sup_amt = round(qty * sup_u, 2)
  4212. img = None
  4213. if p and getattr(p, "image_url", None):
  4214. img = str(p.image_url).strip() or None
  4215. mv = None
  4216. if p is not None and p.measure_value is not None:
  4217. try:
  4218. mv = float(p.measure_value)
  4219. except (TypeError, ValueError):
  4220. mv = None
  4221. children.append({
  4222. "rowType": "line",
  4223. "id": f"line-{ln.id}",
  4224. "lineId": ln.id,
  4225. "productId": ln.product_id,
  4226. "productName": p.name if p else None,
  4227. "skuCode": p.sku_code if p else None,
  4228. "imageUrl": img,
  4229. "unitName": u.name if u else None,
  4230. "measureValue": mv,
  4231. "quantity": qty,
  4232. "sellingUnitPrice": sell_u,
  4233. "sellingAmount": sell_amt,
  4234. "supplierUnitPrice": sup_u,
  4235. "supplierAmount": sup_amt,
  4236. })
  4237. return children
  4238. def _build_client_pending_settlement_tree_rows(
  4239. db: Session,
  4240. orders: List[BizOrder],
  4241. client_map: dict,
  4242. ) -> List[dict]:
  4243. if not orders:
  4244. return []
  4245. # 避免模块级循环依赖:在需要处局部导入
  4246. from app.crud.order import order_crud
  4247. order_ids = [o.id for o in orders]
  4248. region_ids = list({o.region_id for o in orders if o.region_id})
  4249. region_map: dict = {}
  4250. for rid in region_ids:
  4251. region = region_crud.get(db, rid)
  4252. region_map[rid] = region.name if region else None
  4253. lines = (
  4254. db.query(BizOrderItem)
  4255. .filter(BizOrderItem.order_id.in_(order_ids), BizOrderItem.is_del == 0)
  4256. .order_by(BizOrderItem.order_id.asc(), BizOrderItem.create_at.asc())
  4257. .all()
  4258. )
  4259. by_oid: dict = {}
  4260. for ln in lines:
  4261. by_oid.setdefault(ln.order_id, []).append(ln)
  4262. product_ids = list({ln.product_id for ln in lines})
  4263. unit_ids = list({ln.unit_id for ln in lines})
  4264. products = (
  4265. db.query(BasProduct).filter(BasProduct.id.in_(product_ids), BasProduct.is_del == 0).all()
  4266. ) if product_ids else []
  4267. product_map = {p.id: p for p in products}
  4268. units = (
  4269. db.query(BasProductUnit).filter(BasProductUnit.id.in_(unit_ids), BasProductUnit.is_del == 0).all()
  4270. ) if unit_ids else []
  4271. unit_map = {u.id: u for u in units}
  4272. pl_ids = list({o.price_list_id for o in orders if o.price_list_id})
  4273. pli_map = _price_list_item_map(db, pl_ids)
  4274. price_lists = (
  4275. db.query(BizPriceList).filter(BizPriceList.id.in_(pl_ids), BizPriceList.is_del == 0).all()
  4276. ) if pl_ids else []
  4277. supplier_id_by_price_list = {p.id: p.supplier_id for p in price_lists}
  4278. supplier_ids = list({sid for sid in supplier_id_by_price_list.values() if sid})
  4279. suppliers = (
  4280. db.query(SysUser).filter(SysUser.id.in_(supplier_ids), SysUser.is_del == 0).all()
  4281. ) if supplier_ids else []
  4282. supplier_name_map = {u.id: (u.real_name or u.username) for u in suppliers}
  4283. out: List[dict] = []
  4284. for o in orders:
  4285. ch = _build_order_line_children_for_settlement_list(
  4286. db, o, by_oid.get(o.id, []), pli_map, product_map, unit_map
  4287. )
  4288. sup_ref = sum(c["supplierAmount"] for c in ch)
  4289. normalized_payment_method = order_crud.normalize_payment_method(o.payment_method)
  4290. sel = (
  4291. o.order_status == "completed"
  4292. and normalized_payment_method == "offline"
  4293. and getattr(o, "client_settlement_status", None) == "pending"
  4294. )
  4295. out.append({
  4296. "rowType": "order",
  4297. "id": o.id,
  4298. "orderNo": o.order_no,
  4299. "clientId": o.client_id,
  4300. "clientName": client_map.get(o.client_id),
  4301. "regionId": o.region_id,
  4302. "regionName": region_map.get(o.region_id),
  4303. "supplierId": supplier_id_by_price_list.get(o.price_list_id),
  4304. "supplierName": supplier_name_map.get(supplier_id_by_price_list.get(o.price_list_id)),
  4305. "totalAmount": float(o.total_amount or 0),
  4306. "settlementAmount": float(o.total_amount or 0),
  4307. "supplierReferenceTotal": round(sup_ref, 2),
  4308. "orderStatus": o.order_status,
  4309. "settlementSelectable": sel,
  4310. "paymentMethod": normalized_payment_method,
  4311. "clientSettlementStatus": o.client_settlement_status,
  4312. "supplierSettlementStatus": o.supplier_settlement_status,
  4313. "createAt": str(o.create_at) if o.create_at else None,
  4314. "children": ch,
  4315. })
  4316. return out
  4317. def _build_supplier_pending_settlement_tree_rows(
  4318. db: Session,
  4319. order_supplier_pairs: List[Tuple[BizOrder, Optional[str]]],
  4320. supplier_map: dict,
  4321. ) -> List[dict]:
  4322. if not order_supplier_pairs:
  4323. return []
  4324. # 避免模块级循环依赖:在需要处局部导入
  4325. from app.crud.order import order_crud
  4326. orders = [p[0] for p in order_supplier_pairs]
  4327. sup_by_oid = {p[0].id: p[1] for p in order_supplier_pairs}
  4328. order_ids = [o.id for o in orders]
  4329. lines = (
  4330. db.query(BizOrderItem)
  4331. .filter(BizOrderItem.order_id.in_(order_ids), BizOrderItem.is_del == 0)
  4332. .order_by(BizOrderItem.order_id.asc(), BizOrderItem.create_at.asc())
  4333. .all()
  4334. )
  4335. by_oid: dict = {}
  4336. for ln in lines:
  4337. by_oid.setdefault(ln.order_id, []).append(ln)
  4338. product_ids = list({ln.product_id for ln in lines})
  4339. unit_ids = list({ln.unit_id for ln in lines})
  4340. products = (
  4341. db.query(BasProduct).filter(BasProduct.id.in_(product_ids), BasProduct.is_del == 0).all()
  4342. ) if product_ids else []
  4343. product_map = {p.id: p for p in products}
  4344. units = (
  4345. db.query(BasProductUnit).filter(BasProductUnit.id.in_(unit_ids), BasProductUnit.is_del == 0).all()
  4346. ) if unit_ids else []
  4347. unit_map = {u.id: u for u in units}
  4348. pl_ids = list({o.price_list_id for o in orders if o.price_list_id})
  4349. pli_map = _price_list_item_map(db, pl_ids)
  4350. client_ids = list({o.client_id for o in orders if o.client_id})
  4351. client_map: dict = {}
  4352. if client_ids:
  4353. clients = db.query(SysUser).filter(SysUser.id.in_(client_ids), SysUser.is_del == 0).all()
  4354. client_map = {u.id: (u.real_name or u.username) for u in clients}
  4355. region_ids = list({o.region_id for o in orders if o.region_id})
  4356. region_map: dict = {}
  4357. for rid in region_ids:
  4358. region = region_crud.get(db, rid)
  4359. region_map[rid] = region.name if region else None
  4360. out: List[dict] = []
  4361. for o in orders:
  4362. ch = _build_order_line_children_for_settlement_list(
  4363. db, o, by_oid.get(o.id, []), pli_map, product_map, unit_map
  4364. )
  4365. sup_order_total = sum(c["supplierAmount"] for c in ch)
  4366. normalized_payment_method = order_crud.normalize_payment_method(o.payment_method)
  4367. sel = (
  4368. o.order_status == "completed"
  4369. and normalized_payment_method == "offline"
  4370. and getattr(o, "client_settlement_status", None) == "pending"
  4371. )
  4372. sid = sup_by_oid.get(o.id)
  4373. out.append({
  4374. "rowType": "order",
  4375. "id": o.id,
  4376. "orderNo": o.order_no,
  4377. "clientId": o.client_id,
  4378. "clientName": client_map.get(o.client_id),
  4379. "regionId": o.region_id,
  4380. "regionName": region_map.get(o.region_id),
  4381. "supplierId": sid,
  4382. "supplierName": supplier_map.get(sid) if sid else None,
  4383. "settlementAmount": round(sup_order_total, 2),
  4384. "totalAmount": float(o.total_amount or 0),
  4385. "clientSellingTotal": float(o.total_amount or 0),
  4386. "orderStatus": o.order_status,
  4387. "settlementSelectable": sel,
  4388. "supplierSettlementStatus": o.supplier_settlement_status,
  4389. "clientSettlementStatus": o.client_settlement_status,
  4390. "paymentMethod": normalized_payment_method,
  4391. "createAt": str(o.create_at) if o.create_at else None,
  4392. "children": ch,
  4393. })
  4394. return out
  4395. @router.get("/client-settlements/orders", response_model=dict)
  4396. def list_client_settlement_orders(
  4397. page: int = Query(1, ge=1),
  4398. pageSize: int = Query(10, ge=1, le=100),
  4399. clientId: Optional[str] = Query(None),
  4400. keyword: Optional[str] = Query(None, description="订单号"),
  4401. startDate: Optional[str] = Query(None),
  4402. endDate: Optional[str] = Query(None),
  4403. regionId: Optional[str] = Query(None, description="区域(Tab);超级管理员可选,区域管理员忽略"),
  4404. db: Session = Depends(get_db),
  4405. current_user: dict = Depends(require_admin),
  4406. ):
  4407. admin_region_id = get_admin_region_filter(db, current_user)
  4408. eff_region_id = _effective_settlement_region_id(admin_region_id, regionId)
  4409. dt_start, dt_end = _parse_datetime_range(startDate, endDate)
  4410. q = db.query(BizOrder).filter(
  4411. BizOrder.is_del == 0,
  4412. BizOrder.order_status != "cancelled",
  4413. BizOrder.payment_method == "offline",
  4414. BizOrder.client_settlement_status == "pending",
  4415. )
  4416. if eff_region_id:
  4417. q = q.filter(BizOrder.region_id == eff_region_id)
  4418. if clientId:
  4419. q = q.filter(BizOrder.client_id == clientId)
  4420. if keyword:
  4421. q = q.filter(BizOrder.order_no.like(f"%{keyword}%"))
  4422. if dt_start:
  4423. q = q.filter(BizOrder.create_at >= dt_start)
  4424. if dt_end:
  4425. q = q.filter(BizOrder.create_at <= dt_end)
  4426. total = q.count()
  4427. settleable_order_count = q.filter(BizOrder.order_status == "completed").count()
  4428. q_done = q.filter(BizOrder.order_status == "completed")
  4429. pending_amount = float(
  4430. q_done.with_entities(func.coalesce(func.sum(BizOrder.total_amount), 0)).scalar() or 0
  4431. )
  4432. rows = q.order_by(BizOrder.create_at.desc()).offset((page - 1) * pageSize).limit(pageSize).all()
  4433. client_ids = list({r.client_id for r in rows if r.client_id})
  4434. client_map = {}
  4435. if client_ids:
  4436. for u in db.query(SysUser).filter(SysUser.id.in_(client_ids)).all():
  4437. client_map[u.id] = u.real_name or u.username
  4438. data = _build_client_pending_settlement_tree_rows(db, rows, client_map)
  4439. current_page_amount = float(sum((o.total_amount or 0) for o in rows if o.order_status == "completed"))
  4440. return success_response({
  4441. "list": data,
  4442. "total": total,
  4443. "page": page,
  4444. "pageSize": pageSize,
  4445. "totalPages": (total + pageSize - 1) // pageSize,
  4446. "summary": {
  4447. "pendingAmount": pending_amount,
  4448. "currentPageAmount": current_page_amount,
  4449. "settleableOrderCount": settleable_order_count,
  4450. },
  4451. })
  4452. @router.get("/supplier-settlements/orders", response_model=dict)
  4453. def list_supplier_settlement_orders(
  4454. page: int = Query(1, ge=1),
  4455. pageSize: int = Query(10, ge=1, le=100),
  4456. supplierId: Optional[str] = Query(None),
  4457. keyword: Optional[str] = Query(None, description="订单号"),
  4458. startDate: Optional[str] = Query(None),
  4459. endDate: Optional[str] = Query(None),
  4460. regionId: Optional[str] = Query(None, description="区域(Tab);超级管理员可选,区域管理员忽略"),
  4461. db: Session = Depends(get_db),
  4462. current_user: dict = Depends(require_admin),
  4463. ):
  4464. admin_region_id = get_admin_region_filter(db, current_user)
  4465. eff_region_id = _effective_settlement_region_id(admin_region_id, regionId)
  4466. dt_start, dt_end = _parse_datetime_range(startDate, endDate)
  4467. q = db.query(BizOrder, BizPriceList.supplier_id).join(
  4468. BizPriceList, BizPriceList.id == BizOrder.price_list_id
  4469. ).filter(
  4470. BizOrder.is_del == 0,
  4471. BizOrder.order_status != "cancelled",
  4472. BizOrder.supplier_settlement_status == "pending",
  4473. )
  4474. if eff_region_id:
  4475. q = q.filter(BizOrder.region_id == eff_region_id)
  4476. if supplierId:
  4477. q = q.filter(BizPriceList.supplier_id == supplierId)
  4478. if keyword:
  4479. q = q.filter(BizOrder.order_no.like(f"%{keyword}%"))
  4480. if dt_start:
  4481. q = q.filter(BizOrder.create_at >= dt_start)
  4482. if dt_end:
  4483. q = q.filter(BizOrder.create_at <= dt_end)
  4484. total = q.count()
  4485. settleable_order_count = q.filter(BizOrder.order_status == "completed").count()
  4486. q_done = q.filter(BizOrder.order_status == "completed")
  4487. done_pairs = q_done.with_entities(BizOrder.id).all()
  4488. done_oids = [x[0] for x in done_pairs]
  4489. totals_map = _batch_supplier_totals_for_orders(db, done_oids)
  4490. pending_amount = float(sum(totals_map.values()))
  4491. rows = q.order_by(BizOrder.create_at.desc()).offset((page - 1) * pageSize).limit(pageSize).all()
  4492. supplier_ids = list({s_id for _, s_id in rows if s_id})
  4493. supplier_map = {}
  4494. if supplier_ids:
  4495. for u in db.query(SysUser).filter(SysUser.id.in_(supplier_ids)).all():
  4496. supplier_map[u.id] = u.real_name or u.username
  4497. data = _build_supplier_pending_settlement_tree_rows(db, rows, supplier_map)
  4498. page_done_ids = [o.id for o, _ in rows if o.order_status == "completed"]
  4499. page_totals = _batch_supplier_totals_for_orders(db, page_done_ids)
  4500. current_page_amount = float(sum(page_totals.values()))
  4501. return success_response({
  4502. "list": data,
  4503. "total": total,
  4504. "page": page,
  4505. "pageSize": pageSize,
  4506. "totalPages": (total + pageSize - 1) // pageSize,
  4507. "summary": {
  4508. "pendingAmount": pending_amount,
  4509. "currentPageAmount": current_page_amount,
  4510. "settleableOrderCount": settleable_order_count,
  4511. },
  4512. })
  4513. @router.get("/client-settlements/history-summary", response_model=dict)
  4514. def get_client_settlement_history_summary(
  4515. regionId: Optional[str] = Query(None, description="区域(Tab);超级管理员可选"),
  4516. clientId: Optional[str] = Query(None, description="客户ID;不传则汇总当前区域下全部客户"),
  4517. db: Session = Depends(get_db),
  4518. current_user: dict = Depends(require_admin),
  4519. ):
  4520. """待结算页用:当前检索条件下已结算批次的历史金额与历史订单笔数。"""
  4521. admin_region_id = get_admin_region_filter(db, current_user)
  4522. eff_region_id = _effective_settlement_region_id(admin_region_id, regionId)
  4523. amt, cnt = _aggregate_client_settlement_history(db, eff_region_id, clientId)
  4524. return success_response({
  4525. "historicalSettledAmount": amt,
  4526. "historicalSettledOrderCount": cnt,
  4527. })
  4528. @router.get("/supplier-settlements/history-summary", response_model=dict)
  4529. def get_supplier_settlement_history_summary(
  4530. regionId: Optional[str] = Query(None, description="区域(Tab);超级管理员可选"),
  4531. supplierId: Optional[str] = Query(None, description="供应商ID;不传则汇总当前区域下全部供应商"),
  4532. db: Session = Depends(get_db),
  4533. current_user: dict = Depends(require_admin),
  4534. ):
  4535. """待结算页用:当前检索条件下已结算批次的历史金额与历史订单笔数。"""
  4536. admin_region_id = get_admin_region_filter(db, current_user)
  4537. eff_region_id = _effective_settlement_region_id(admin_region_id, regionId)
  4538. amt, cnt = _aggregate_supplier_settlement_history(db, eff_region_id, supplierId)
  4539. return success_response({
  4540. "historicalSettledAmount": amt,
  4541. "historicalSettledOrderCount": cnt,
  4542. })
  4543. def _resolve_client_order_ids(db: Session, body: dict, admin_region_id: Optional[str]) -> List[str]:
  4544. selection_mode = (body.get("selectionMode") or "ids").strip()
  4545. filters = body.get("filters") or {}
  4546. eff_region = _effective_settlement_region_id(admin_region_id, filters.get("regionId"))
  4547. if selection_mode == "allFiltered":
  4548. dt_start, dt_end = _parse_datetime_range(filters.get("startDate"), filters.get("endDate"))
  4549. q = db.query(BizOrder.id).filter(
  4550. BizOrder.is_del == 0,
  4551. BizOrder.order_status != "cancelled",
  4552. BizOrder.order_status == "completed",
  4553. BizOrder.payment_method == "offline",
  4554. BizOrder.client_settlement_status == "pending",
  4555. )
  4556. if eff_region:
  4557. q = q.filter(BizOrder.region_id == eff_region)
  4558. if filters.get("clientId"):
  4559. q = q.filter(BizOrder.client_id == filters["clientId"])
  4560. if filters.get("keyword"):
  4561. q = q.filter(BizOrder.order_no.like(f"%{filters['keyword']}%"))
  4562. if dt_start:
  4563. q = q.filter(BizOrder.create_at >= dt_start)
  4564. if dt_end:
  4565. q = q.filter(BizOrder.create_at <= dt_end)
  4566. order_ids = [x[0] for x in q.all()]
  4567. excluded = set(body.get("excludedOrderIds") or [])
  4568. return [oid for oid in order_ids if oid not in excluded]
  4569. return list(set(body.get("orderIds") or []))
  4570. def _resolve_supplier_order_ids(db: Session, body: dict, admin_region_id: Optional[str]) -> List[str]:
  4571. selection_mode = (body.get("selectionMode") or "ids").strip()
  4572. filters = body.get("filters") or {}
  4573. eff_region = _effective_settlement_region_id(admin_region_id, filters.get("regionId"))
  4574. if selection_mode == "allFiltered":
  4575. dt_start, dt_end = _parse_datetime_range(filters.get("startDate"), filters.get("endDate"))
  4576. q = db.query(BizOrder.id).join(
  4577. BizPriceList, BizPriceList.id == BizOrder.price_list_id
  4578. ).filter(
  4579. BizOrder.is_del == 0,
  4580. BizOrder.order_status != "cancelled",
  4581. BizOrder.order_status == "completed",
  4582. BizOrder.supplier_settlement_status == "pending",
  4583. )
  4584. if eff_region:
  4585. q = q.filter(BizOrder.region_id == eff_region)
  4586. if filters.get("supplierId"):
  4587. q = q.filter(BizPriceList.supplier_id == filters["supplierId"])
  4588. if filters.get("keyword"):
  4589. q = q.filter(BizOrder.order_no.like(f"%{filters['keyword']}%"))
  4590. if dt_start:
  4591. q = q.filter(BizOrder.create_at >= dt_start)
  4592. if dt_end:
  4593. q = q.filter(BizOrder.create_at <= dt_end)
  4594. order_ids = [x[0] for x in q.all()]
  4595. excluded = set(body.get("excludedOrderIds") or [])
  4596. return [oid for oid in order_ids if oid not in excluded]
  4597. return list(set(body.get("orderIds") or []))
  4598. @router.post("/client-settlements", response_model=dict)
  4599. def create_client_settlement(
  4600. request: dict,
  4601. db: Session = Depends(get_db),
  4602. current_user: dict = Depends(require_admin),
  4603. ):
  4604. admin_region_id = get_admin_region_filter(db, current_user)
  4605. body = dict(request or {})
  4606. voucher_urls = body.get("voucherUrls") or []
  4607. order_ids = _resolve_client_order_ids(db, body, admin_region_id)
  4608. if not order_ids:
  4609. return error_response(400, "未选择可结算订单")
  4610. orders = db.query(BizOrder).filter(
  4611. BizOrder.id.in_(order_ids),
  4612. BizOrder.is_del == 0,
  4613. BizOrder.order_status == "completed",
  4614. BizOrder.payment_method == "offline",
  4615. BizOrder.client_settlement_status == "pending",
  4616. ).all()
  4617. if not orders:
  4618. return error_response(400, "无可结算订单")
  4619. eff_region = _effective_settlement_region_id(
  4620. admin_region_id, (body.get("filters") or {}).get("regionId")
  4621. )
  4622. if eff_region and any((o.region_id or "") != eff_region for o in orders):
  4623. return error_response(400, "存在不属于当前区域的订单")
  4624. total_amount = sum((o.total_amount or 0) for o in orders)
  4625. client_id = orders[0].client_id
  4626. if any(o.client_id != client_id for o in orders):
  4627. return error_response(400, "客户结算必须选择同一客户")
  4628. client = user_crud.get(db, client_id)
  4629. now = datetime.now()
  4630. creator = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  4631. settlement = OrdClientSettlement(
  4632. id=generate_id(),
  4633. settlement_no=_build_settlement_no("CST"),
  4634. client_id=client_id,
  4635. client_name=(client.real_name if client else None),
  4636. order_count=len(orders),
  4637. total_amount=total_amount,
  4638. voucher_urls=json.dumps(voucher_urls, ensure_ascii=False),
  4639. remark=body.get("remark"),
  4640. settlement_at=now,
  4641. status="done",
  4642. create_by=creator["user_id"],
  4643. create_name=creator["real_name"],
  4644. update_by=creator["user_id"],
  4645. )
  4646. db.add(settlement)
  4647. db.flush()
  4648. for order in orders:
  4649. db.add(OrdClientSettlementItem(
  4650. id=generate_id(),
  4651. settlement_id=settlement.id,
  4652. order_id=order.id,
  4653. order_no=order.order_no,
  4654. client_id=order.client_id,
  4655. order_amount=order.total_amount or 0,
  4656. create_by=creator["user_id"],
  4657. create_name=creator["real_name"],
  4658. update_by=creator["user_id"],
  4659. ))
  4660. order.client_settlement_status = "settled"
  4661. order.client_settlement_at = now
  4662. order.update_by = creator["user_id"]
  4663. order.update_at = now
  4664. db.commit()
  4665. return success_response({
  4666. "id": settlement.id,
  4667. "settlementNo": settlement.settlement_no,
  4668. "orderCount": settlement.order_count,
  4669. "totalAmount": float(settlement.total_amount or 0),
  4670. })
  4671. @router.post("/supplier-settlements", response_model=dict)
  4672. def create_supplier_settlement(
  4673. request: dict,
  4674. db: Session = Depends(get_db),
  4675. current_user: dict = Depends(require_admin),
  4676. ):
  4677. admin_region_id = get_admin_region_filter(db, current_user)
  4678. body = dict(request or {})
  4679. voucher_urls = body.get("voucherUrls") or []
  4680. order_ids = _resolve_supplier_order_ids(db, body, admin_region_id)
  4681. if not order_ids:
  4682. return error_response(400, "未选择可结算订单")
  4683. rows = db.query(BizOrder, BizPriceList.supplier_id).join(
  4684. BizPriceList, BizPriceList.id == BizOrder.price_list_id
  4685. ).filter(
  4686. BizOrder.id.in_(order_ids),
  4687. BizOrder.is_del == 0,
  4688. BizOrder.order_status == "completed",
  4689. BizOrder.supplier_settlement_status == "pending",
  4690. ).all()
  4691. if not rows:
  4692. return error_response(400, "无可结算订单")
  4693. eff_region = _effective_settlement_region_id(
  4694. admin_region_id, (body.get("filters") or {}).get("regionId")
  4695. )
  4696. if eff_region and any((order.region_id or "") != eff_region for order, _ in rows):
  4697. return error_response(400, "存在不属于当前区域的订单")
  4698. supplier_id = rows[0][1]
  4699. if any(s_id != supplier_id for _, s_id in rows):
  4700. return error_response(400, "商家结算必须选择同一供应商")
  4701. orders = [r[0] for r in rows]
  4702. supplier_totals = _batch_supplier_totals_for_orders(db, [o.id for o in orders])
  4703. total_amount = sum(supplier_totals.get(o.id, 0) for o in orders)
  4704. supplier = user_crud.get(db, supplier_id) if supplier_id else None
  4705. now = datetime.now()
  4706. creator = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  4707. settlement = OrdSupplierSettlement(
  4708. id=generate_id(),
  4709. settlement_no=_build_settlement_no("SST"),
  4710. supplier_id=supplier_id,
  4711. supplier_name=(supplier.real_name if supplier else None),
  4712. order_count=len(orders),
  4713. total_amount=total_amount,
  4714. voucher_urls=json.dumps(voucher_urls, ensure_ascii=False),
  4715. remark=body.get("remark"),
  4716. settlement_at=now,
  4717. status="done",
  4718. create_by=creator["user_id"],
  4719. create_name=creator["real_name"],
  4720. update_by=creator["user_id"],
  4721. )
  4722. db.add(settlement)
  4723. db.flush()
  4724. for order in orders:
  4725. db.add(OrdSupplierSettlementItem(
  4726. id=generate_id(),
  4727. settlement_id=settlement.id,
  4728. order_id=order.id,
  4729. order_no=order.order_no,
  4730. supplier_id=supplier_id,
  4731. order_amount=supplier_totals.get(order.id, 0),
  4732. create_by=creator["user_id"],
  4733. create_name=creator["real_name"],
  4734. update_by=creator["user_id"],
  4735. ))
  4736. order.supplier_settlement_status = "settled"
  4737. order.supplier_settlement_at = now
  4738. order.update_by = creator["user_id"]
  4739. order.update_at = now
  4740. db.commit()
  4741. return success_response({
  4742. "id": settlement.id,
  4743. "settlementNo": settlement.settlement_no,
  4744. "orderCount": settlement.order_count,
  4745. "totalAmount": float(settlement.total_amount or 0),
  4746. })
  4747. def _sheet_voucher_urls_list(raw) -> list:
  4748. if not raw:
  4749. return []
  4750. if isinstance(raw, list):
  4751. return [str(x) for x in raw if x]
  4752. s = str(raw).strip()
  4753. if not s:
  4754. return []
  4755. try:
  4756. data = json.loads(s)
  4757. if isinstance(data, list):
  4758. return [str(x) for x in data if x]
  4759. except Exception:
  4760. pass
  4761. return [s]
  4762. def _build_settlement_detail_item_tree(db: Session, settlement_items: List[Any]) -> List[dict]:
  4763. """结算单明细:每个订单一行父节点,子行为订单商品行(与前端树表对应)。"""
  4764. from app.crud.order import order_crud
  4765. if not settlement_items:
  4766. return []
  4767. order_ids = list({it.order_id for it in settlement_items if getattr(it, "order_id", None)})
  4768. if not order_ids:
  4769. return []
  4770. orders = (
  4771. db.query(BizOrder)
  4772. .filter(BizOrder.id.in_(order_ids), BizOrder.is_del == 0)
  4773. .all()
  4774. )
  4775. order_map = {o.id: o for o in orders}
  4776. client_ids = list({o.client_id for o in orders if o.client_id})
  4777. client_map: dict = {}
  4778. if client_ids:
  4779. clients = db.query(SysUser).filter(SysUser.id.in_(client_ids), SysUser.is_del == 0).all()
  4780. client_map = {u.id: (u.real_name or u.username) for u in clients}
  4781. region_ids = list({o.region_id for o in orders if o.region_id})
  4782. region_map: dict = {}
  4783. for rid in region_ids:
  4784. r = region_crud.get(db, rid)
  4785. region_map[rid] = r.name if r else None
  4786. lines = (
  4787. db.query(BizOrderItem)
  4788. .filter(BizOrderItem.order_id.in_(order_ids), BizOrderItem.is_del == 0)
  4789. .order_by(BizOrderItem.order_id.asc(), BizOrderItem.create_at.asc())
  4790. .all()
  4791. )
  4792. by_order: dict = {}
  4793. for ln in lines:
  4794. by_order.setdefault(ln.order_id, []).append(ln)
  4795. product_ids = list({ln.product_id for ln in lines})
  4796. unit_ids = list({ln.unit_id for ln in lines})
  4797. products = (
  4798. db.query(BasProduct)
  4799. .filter(BasProduct.id.in_(product_ids), BasProduct.is_del == 0)
  4800. .all()
  4801. ) if product_ids else []
  4802. product_map = {p.id: p for p in products}
  4803. category_ids = list({p.category_id for p in products if p.category_id})
  4804. category_map: dict = {}
  4805. for cid in category_ids:
  4806. c = category_crud.get(db, cid)
  4807. category_map[cid] = c.name if c else None
  4808. units = (
  4809. db.query(BasProductUnit)
  4810. .filter(BasProductUnit.id.in_(unit_ids), BasProductUnit.is_del == 0)
  4811. .all()
  4812. ) if unit_ids else []
  4813. unit_map = {u.id: u for u in units}
  4814. pl_ids = list({o.price_list_id for o in order_map.values() if o and o.price_list_id})
  4815. pli_map = _price_list_item_map(db, pl_ids)
  4816. out: List[dict] = []
  4817. for it in settlement_items:
  4818. order = order_map.get(it.order_id)
  4819. rid = order.region_id if order else None
  4820. children: List[dict] = []
  4821. for ln in by_order.get(it.order_id, []):
  4822. p = product_map.get(ln.product_id)
  4823. u = unit_map.get(ln.unit_id)
  4824. img = None
  4825. if p and getattr(p, "image_url", None):
  4826. img = str(p.image_url).strip() or None
  4827. mv = None
  4828. if p is not None and p.measure_value is not None:
  4829. try:
  4830. mv = float(p.measure_value)
  4831. except (TypeError, ValueError):
  4832. mv = None
  4833. pli = pli_map.get((order.price_list_id, ln.product_id, ln.unit_id)) if order else None
  4834. sup_u = _supplier_unit_yuan_from_pli(pli)
  4835. if sup_u is None:
  4836. sup_u = float(ln.unit_price or 0)
  4837. sell_u = float(ln.unit_price or 0)
  4838. qty = float(ln.quantity or 0)
  4839. sell_amt = float(ln.amount or 0) if ln.amount is not None else round(qty * sell_u, 2)
  4840. sup_amt = round(qty * sup_u, 2)
  4841. children.append({
  4842. "rowType": "line",
  4843. "id": f"line-{ln.id}",
  4844. "lineId": ln.id,
  4845. "productId": ln.product_id,
  4846. "productName": p.name if p else None,
  4847. "skuCode": p.sku_code if p else None,
  4848. "imageUrl": img,
  4849. "categoryName": category_map.get(p.category_id) if p and p.category_id else None,
  4850. "unitName": u.name if u else None,
  4851. "measureValue": mv,
  4852. "quantity": qty,
  4853. "unitPrice": sell_u,
  4854. "amount": sell_amt,
  4855. "sellingUnitPrice": sell_u,
  4856. "sellingAmount": sell_amt,
  4857. "supplierUnitPrice": sup_u,
  4858. "supplierAmount": sup_amt,
  4859. "deliveredQuantity": float(ln.delivered_quantity or 0),
  4860. "note": ln.note,
  4861. })
  4862. out.append({
  4863. "rowType": "order",
  4864. "id": f"order-{it.id}",
  4865. "settlementItemId": it.id,
  4866. "orderId": it.order_id,
  4867. "orderNo": it.order_no,
  4868. "orderAmount": float(it.order_amount or 0),
  4869. "totalAmount": float(it.order_amount or 0),
  4870. "clientId": order.client_id if order else None,
  4871. "clientName": client_map.get(order.client_id) if order else None,
  4872. "regionId": rid,
  4873. "regionName": region_map.get(rid),
  4874. "orderCreateAt": str(order.create_at) if order and order.create_at else None,
  4875. "contactPerson": order.contact_person if order else None,
  4876. "contactPhone": order.contact_phone if order else None,
  4877. "deliveryAddress": order.delivery_address if order else None,
  4878. "orderStatus": order.order_status if order else None,
  4879. "paymentMethod": order_crud.normalize_payment_method(order.payment_method) if order else None,
  4880. "createAt": str(it.create_at) if it.create_at else None,
  4881. "children": children,
  4882. })
  4883. return out
  4884. @router.get("/client-settlements/sheets", response_model=dict)
  4885. def list_client_settlement_sheets(
  4886. page: int = Query(1, ge=1),
  4887. pageSize: int = Query(10, ge=1, le=100),
  4888. clientId: Optional[str] = Query(None),
  4889. settlementNo: Optional[str] = Query(None),
  4890. startDate: Optional[str] = Query(None),
  4891. endDate: Optional[str] = Query(None),
  4892. regionId: Optional[str] = Query(None, description="区域(Tab);超级管理员可选"),
  4893. db: Session = Depends(get_db),
  4894. current_user: dict = Depends(require_admin),
  4895. ):
  4896. """客户结算单(批次)列表"""
  4897. from app.crud.ord_settlement import ord_client_settlement_crud
  4898. admin_region_id = get_admin_region_filter(db, current_user)
  4899. eff_region_id = _effective_settlement_region_id(admin_region_id, regionId)
  4900. dt_start, dt_end = _parse_datetime_range(startDate, endDate)
  4901. rows, total = ord_client_settlement_crud.get_multi_with_filters(
  4902. db,
  4903. client_id=clientId,
  4904. settlement_no=settlementNo,
  4905. start_date=dt_start,
  4906. end_date=dt_end,
  4907. region_id=eff_region_id,
  4908. skip=(page - 1) * pageSize,
  4909. limit=pageSize,
  4910. )
  4911. out = []
  4912. for s in rows:
  4913. out.append({
  4914. "id": s.id,
  4915. "settlementNo": s.settlement_no,
  4916. "clientId": s.client_id,
  4917. "clientName": s.client_name,
  4918. "orderCount": s.order_count,
  4919. "totalAmount": float(s.total_amount or 0),
  4920. "settlementAt": str(s.settlement_at) if s.settlement_at else None,
  4921. "status": s.status,
  4922. "remark": s.remark,
  4923. "createAt": str(s.create_at) if s.create_at else None,
  4924. "createName": s.create_name,
  4925. })
  4926. return success_response({
  4927. "list": out,
  4928. "total": total,
  4929. "page": page,
  4930. "pageSize": pageSize,
  4931. "totalPages": (total + pageSize - 1) // pageSize,
  4932. })
  4933. @router.get("/client-settlements/sheets/{sheet_id}", response_model=dict)
  4934. def get_client_settlement_sheet_detail(
  4935. sheet_id: str,
  4936. db: Session = Depends(get_db),
  4937. current_user: dict = Depends(require_admin),
  4938. ):
  4939. """客户结算单详情(含明细订单)"""
  4940. from app.crud.ord_settlement import ord_client_settlement_crud
  4941. admin_region_id = get_admin_region_filter(db, current_user)
  4942. main, items = ord_client_settlement_crud.get_with_items(db, sheet_id)
  4943. if not main:
  4944. return error_response(404, "结算单不存在")
  4945. if admin_region_id and not ord_client_settlement_crud.belongs_to_region(db, sheet_id, admin_region_id):
  4946. return error_response(403, "无权限查看该结算单")
  4947. item_out = _build_settlement_detail_item_tree(db, items)
  4948. return success_response({
  4949. "id": main.id,
  4950. "settlementNo": main.settlement_no,
  4951. "clientId": main.client_id,
  4952. "clientName": main.client_name,
  4953. "orderCount": main.order_count,
  4954. "totalAmount": float(main.total_amount or 0),
  4955. "voucherUrls": _sheet_voucher_urls_list(main.voucher_urls),
  4956. "remark": main.remark,
  4957. "settlementAt": str(main.settlement_at) if main.settlement_at else None,
  4958. "status": main.status,
  4959. "createAt": str(main.create_at) if main.create_at else None,
  4960. "createName": main.create_name,
  4961. "items": item_out,
  4962. })
  4963. @router.put("/client-settlements/sheets/{sheet_id}", response_model=dict)
  4964. def update_client_settlement_sheet(
  4965. sheet_id: str,
  4966. request: dict,
  4967. db: Session = Depends(get_db),
  4968. current_user: dict = Depends(require_admin),
  4969. ):
  4970. """更新客户结算单(备注/凭证);UPDATE 前写入 ord_client_settlement_his"""
  4971. from app.crud.ord_settlement import ord_client_settlement_crud
  4972. admin_region_id = get_admin_region_filter(db, current_user)
  4973. if admin_region_id and not ord_client_settlement_crud.belongs_to_region(db, sheet_id, admin_region_id):
  4974. return error_response(403, "无权限操作该结算单")
  4975. body = dict(request or {})
  4976. update_data = {}
  4977. if "remark" in body:
  4978. update_data["remark"] = body.get("remark")
  4979. if "voucherUrls" in body:
  4980. urls = body.get("voucherUrls") or []
  4981. if not isinstance(urls, list):
  4982. return error_response(400, "voucherUrls 须为数组")
  4983. update_data["voucher_urls"] = json.dumps(urls, ensure_ascii=False)
  4984. if not update_data:
  4985. return error_response(400, "无可更新字段")
  4986. updater = {"user_id": current_user.get("user_id")}
  4987. row = ord_client_settlement_crud.update_with_history(db, sheet_id, update_data, updater)
  4988. if not row:
  4989. return error_response(404, "结算单不存在")
  4990. return success_response({
  4991. "id": row.id,
  4992. "settlementNo": row.settlement_no,
  4993. "remark": row.remark,
  4994. "voucherUrls": _sheet_voucher_urls_list(row.voucher_urls),
  4995. })
  4996. @router.get("/supplier-settlements/sheets", response_model=dict)
  4997. def list_supplier_settlement_sheets(
  4998. page: int = Query(1, ge=1),
  4999. pageSize: int = Query(10, ge=1, le=100),
  5000. supplierId: Optional[str] = Query(None),
  5001. settlementNo: Optional[str] = Query(None),
  5002. startDate: Optional[str] = Query(None),
  5003. endDate: Optional[str] = Query(None),
  5004. regionId: Optional[str] = Query(None, description="区域(Tab);超级管理员可选"),
  5005. db: Session = Depends(get_db),
  5006. current_user: dict = Depends(require_admin),
  5007. ):
  5008. """供应商结算单(批次)列表"""
  5009. from app.crud.ord_settlement import ord_supplier_settlement_crud
  5010. admin_region_id = get_admin_region_filter(db, current_user)
  5011. eff_region_id = _effective_settlement_region_id(admin_region_id, regionId)
  5012. dt_start, dt_end = _parse_datetime_range(startDate, endDate)
  5013. rows, total = ord_supplier_settlement_crud.get_multi_with_filters(
  5014. db,
  5015. supplier_id=supplierId,
  5016. settlement_no=settlementNo,
  5017. start_date=dt_start,
  5018. end_date=dt_end,
  5019. region_id=eff_region_id,
  5020. skip=(page - 1) * pageSize,
  5021. limit=pageSize,
  5022. )
  5023. out = []
  5024. for s in rows:
  5025. out.append({
  5026. "id": s.id,
  5027. "settlementNo": s.settlement_no,
  5028. "supplierId": s.supplier_id,
  5029. "supplierName": s.supplier_name,
  5030. "orderCount": s.order_count,
  5031. "totalAmount": float(s.total_amount or 0),
  5032. "settlementAt": str(s.settlement_at) if s.settlement_at else None,
  5033. "status": s.status,
  5034. "remark": s.remark,
  5035. "createAt": str(s.create_at) if s.create_at else None,
  5036. "createName": s.create_name,
  5037. })
  5038. return success_response({
  5039. "list": out,
  5040. "total": total,
  5041. "page": page,
  5042. "pageSize": pageSize,
  5043. "totalPages": (total + pageSize - 1) // pageSize,
  5044. })
  5045. @router.get("/supplier-settlements/sheets/{sheet_id}", response_model=dict)
  5046. def get_supplier_settlement_sheet_detail(
  5047. sheet_id: str,
  5048. db: Session = Depends(get_db),
  5049. current_user: dict = Depends(require_admin),
  5050. ):
  5051. """供应商结算单详情(含明细订单)"""
  5052. from app.crud.ord_settlement import ord_supplier_settlement_crud
  5053. admin_region_id = get_admin_region_filter(db, current_user)
  5054. main, items = ord_supplier_settlement_crud.get_with_items(db, sheet_id)
  5055. if not main:
  5056. return error_response(404, "结算单不存在")
  5057. if admin_region_id and not ord_supplier_settlement_crud.belongs_to_region(db, sheet_id, admin_region_id):
  5058. return error_response(403, "无权限查看该结算单")
  5059. item_out = _build_settlement_detail_item_tree(db, items)
  5060. return success_response({
  5061. "id": main.id,
  5062. "settlementNo": main.settlement_no,
  5063. "supplierId": main.supplier_id,
  5064. "supplierName": main.supplier_name,
  5065. "orderCount": main.order_count,
  5066. "totalAmount": float(main.total_amount or 0),
  5067. "voucherUrls": _sheet_voucher_urls_list(main.voucher_urls),
  5068. "remark": main.remark,
  5069. "settlementAt": str(main.settlement_at) if main.settlement_at else None,
  5070. "status": main.status,
  5071. "createAt": str(main.create_at) if main.create_at else None,
  5072. "createName": main.create_name,
  5073. "items": item_out,
  5074. })
  5075. @router.put("/supplier-settlements/sheets/{sheet_id}", response_model=dict)
  5076. def update_supplier_settlement_sheet(
  5077. sheet_id: str,
  5078. request: dict,
  5079. db: Session = Depends(get_db),
  5080. current_user: dict = Depends(require_admin),
  5081. ):
  5082. """更新供应商结算单(备注/凭证);UPDATE 前写入 ord_supplier_settlement_his"""
  5083. from app.crud.ord_settlement import ord_supplier_settlement_crud
  5084. admin_region_id = get_admin_region_filter(db, current_user)
  5085. if admin_region_id and not ord_supplier_settlement_crud.belongs_to_region(db, sheet_id, admin_region_id):
  5086. return error_response(403, "无权限操作该结算单")
  5087. body = dict(request or {})
  5088. update_data = {}
  5089. if "remark" in body:
  5090. update_data["remark"] = body.get("remark")
  5091. if "voucherUrls" in body:
  5092. urls = body.get("voucherUrls") or []
  5093. if not isinstance(urls, list):
  5094. return error_response(400, "voucherUrls 须为数组")
  5095. update_data["voucher_urls"] = json.dumps(urls, ensure_ascii=False)
  5096. if not update_data:
  5097. return error_response(400, "无可更新字段")
  5098. updater = {"user_id": current_user.get("user_id")}
  5099. row = ord_supplier_settlement_crud.update_with_history(db, sheet_id, update_data, updater)
  5100. if not row:
  5101. return error_response(404, "结算单不存在")
  5102. return success_response({
  5103. "id": row.id,
  5104. "settlementNo": row.settlement_no,
  5105. "remark": row.remark,
  5106. "voucherUrls": _sheet_voucher_urls_list(row.voucher_urls),
  5107. })
  5108. @router.get("/settlements", response_model=dict)
  5109. def list_settlements(
  5110. page: int = Query(1, ge=1, description="页码"),
  5111. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5112. regionId: Optional[str] = Query(None, description="区域ID"),
  5113. clientId: Optional[str] = Query(None, description="客户ID"),
  5114. status: Optional[str] = Query(None, description="状态"),
  5115. startDate: Optional[str] = Query(None, description="开始日期"),
  5116. endDate: Optional[str] = Query(None, description="结束日期"),
  5117. db: Session = Depends(get_db),
  5118. current_user: dict = Depends(require_admin)
  5119. ):
  5120. """获取线下结算订单列表"""
  5121. from app.crud.settlement import settlement_crud
  5122. settlements, total = settlement_crud.get_multi_with_filters(
  5123. db,
  5124. region_id=regionId,
  5125. client_id=clientId,
  5126. status=status,
  5127. start_date=startDate,
  5128. end_date=endDate,
  5129. skip=(page - 1) * pageSize,
  5130. limit=pageSize
  5131. )
  5132. region_map = {}
  5133. client_map = {}
  5134. result = []
  5135. for settlement in settlements:
  5136. if settlement.region_id and settlement.region_id not in region_map:
  5137. region = region_crud.get(db, settlement.region_id)
  5138. region_map[settlement.region_id] = region.name if region else None
  5139. if settlement.client_id and settlement.client_id not in client_map:
  5140. client = user_crud.get(db, settlement.client_id)
  5141. client_map[settlement.client_id] = client.real_name if client else None
  5142. result.append({
  5143. "id": settlement.id,
  5144. "orderId": settlement.order_id,
  5145. "clientId": settlement.client_id,
  5146. "clientName": client_map.get(settlement.client_id),
  5147. "regionId": settlement.region_id,
  5148. "regionName": region_map.get(settlement.region_id),
  5149. "amount": float(settlement.amount) if settlement.amount else 0,
  5150. "settlementMethod": settlement.settlement_method,
  5151. "settlementTime": str(settlement.settlement_time) if settlement.settlement_time else None,
  5152. "settlementNote": settlement.settlement_note,
  5153. "status": settlement.status,
  5154. "reviewedBy": settlement.reviewed_by,
  5155. "reviewedTime": str(settlement.reviewed_time) if settlement.reviewed_time else None,
  5156. "createAt": str(settlement.create_at) if settlement.create_at else None
  5157. })
  5158. return success_response({
  5159. "list": result,
  5160. "total": total,
  5161. "page": page,
  5162. "pageSize": pageSize,
  5163. "totalPages": (total + pageSize - 1) // pageSize
  5164. })
  5165. @router.get("/settlements/client-summary", response_model=dict)
  5166. def get_client_summary(
  5167. page: int = Query(1, ge=1, description="页码"),
  5168. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5169. regionId: Optional[str] = Query(None, description="区域ID"),
  5170. clientId: Optional[str] = Query(None, description="客户ID"),
  5171. db: Session = Depends(get_db),
  5172. current_user: dict = Depends(require_admin)
  5173. ):
  5174. """获取客户待结算汇总"""
  5175. from app.crud.settlement import settlement_crud
  5176. summaries, total = settlement_crud.get_client_summary(
  5177. db,
  5178. region_id=regionId,
  5179. client_id=clientId,
  5180. skip=(page - 1) * pageSize,
  5181. limit=pageSize
  5182. )
  5183. result = []
  5184. for summary in summaries:
  5185. client = user_crud.get(db, summary["client_id"])
  5186. result.append({
  5187. "clientId": summary["client_id"],
  5188. "clientName": client.real_name if client else None,
  5189. "orderCount": summary["order_count"],
  5190. "totalUnpaid": float(summary["total_unpaid"]) if summary["total_unpaid"] else 0
  5191. })
  5192. return success_response({
  5193. "list": result,
  5194. "total": total,
  5195. "page": page,
  5196. "pageSize": pageSize,
  5197. "totalPages": (total + pageSize - 1) // pageSize
  5198. })
  5199. @router.post("/settlements", response_model=dict)
  5200. def create_settlement(
  5201. request: dict,
  5202. db: Session = Depends(get_db),
  5203. current_user: dict = Depends(require_admin)
  5204. ):
  5205. """确认线下结算"""
  5206. from app.crud.settlement import settlement_crud
  5207. from datetime import datetime
  5208. from decimal import Decimal
  5209. order_id = request.get("orderId")
  5210. settlement_method = request.get("settlementMethod")
  5211. settlement_time_str = request.get("settlementTime")
  5212. note = request.get("settlementNote")
  5213. attachment_url = request.get("attachmentUrl")
  5214. if not order_id:
  5215. return error_response(400, "请选择订单")
  5216. if not settlement_method:
  5217. return error_response(400, "请选择结算方式")
  5218. # 获取订单信息
  5219. from app.models.models import BizOrder
  5220. order = db.query(BizOrder).filter(BizOrder.id == order_id).first()
  5221. if not order:
  5222. return error_response(404, "订单不存在")
  5223. # 计算未付金额
  5224. unpaid_amount = (order.receivable_amount or Decimal("0")) - (order.paid_amount or Decimal("0"))
  5225. if unpaid_amount <= 0:
  5226. return error_response(400, "该订单已无欠款,无需结算")
  5227. # 解析结算时间
  5228. settlement_time = None
  5229. if settlement_time_str:
  5230. try:
  5231. settlement_time = datetime.fromisoformat(settlement_time_str.replace("Z", "+00:00"))
  5232. except:
  5233. settlement_time = datetime.now()
  5234. creator = {
  5235. "user_id": current_user.get("user_id"),
  5236. "real_name": current_user.get("real_name")
  5237. }
  5238. settlement = settlement_crud.create_settlement(
  5239. db,
  5240. order_id=order_id,
  5241. client_id=order.client_id,
  5242. region_id=order.region_id,
  5243. amount=unpaid_amount,
  5244. settlement_method=settlement_method,
  5245. settlement_time=settlement_time,
  5246. attachment_url=attachment_url,
  5247. note=note,
  5248. creator=creator
  5249. )
  5250. return success_response({
  5251. "id": settlement.id,
  5252. "message": "结算成功"
  5253. })
  5254. @router.post("/settlements/batch", response_model=dict)
  5255. def batch_create_settlements(
  5256. request: dict,
  5257. db: Session = Depends(get_db),
  5258. current_user: dict = Depends(require_admin)
  5259. ):
  5260. """批量确认线下结算"""
  5261. from app.crud.settlement import settlement_crud
  5262. from datetime import datetime
  5263. order_ids = request.get("orderIds", [])
  5264. settlement_method = request.get("settlementMethod")
  5265. settlement_time_str = request.get("settlementTime")
  5266. note = request.get("settlementNote")
  5267. attachment_url = request.get("attachmentUrl")
  5268. if not order_ids:
  5269. return error_response(400, "请选择要结算的订单")
  5270. if not settlement_method:
  5271. return error_response(400, "请选择结算方式")
  5272. if len(order_ids) > 50:
  5273. return error_response(400, "单次最多结算50个订单")
  5274. # 解析结算时间
  5275. settlement_time = None
  5276. if settlement_time_str:
  5277. try:
  5278. settlement_time = datetime.fromisoformat(settlement_time_str.replace("Z", "+00:00"))
  5279. except:
  5280. settlement_time = datetime.now()
  5281. creator = {
  5282. "user_id": current_user.get("user_id"),
  5283. "real_name": current_user.get("real_name")
  5284. }
  5285. settlements = settlement_crud.batch_create_settlements(
  5286. db,
  5287. order_ids=order_ids,
  5288. settlement_method=settlement_method,
  5289. settlement_time=settlement_time,
  5290. attachment_url=attachment_url,
  5291. note=note,
  5292. creator=creator
  5293. )
  5294. return success_response({
  5295. "count": len(settlements),
  5296. "message": f"成功结算{len(settlements)}个订单"
  5297. })
  5298. @router.get("/settlements/records", response_model=dict)
  5299. def list_settlement_records(
  5300. page: int = Query(1, ge=1, description="页码"),
  5301. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5302. regionId: Optional[str] = Query(None, description="区域ID"),
  5303. clientId: Optional[str] = Query(None, description="客户ID"),
  5304. startDate: Optional[str] = Query(None, description="开始日期"),
  5305. endDate: Optional[str] = Query(None, description="结束日期"),
  5306. db: Session = Depends(get_db),
  5307. current_user: dict = Depends(require_admin)
  5308. ):
  5309. """获取结算记录列表"""
  5310. from app.crud.settlement import settlement_crud
  5311. settlements, total = settlement_crud.get_multi_with_filters(
  5312. db,
  5313. region_id=regionId,
  5314. client_id=clientId,
  5315. status="confirmed",
  5316. start_date=startDate,
  5317. end_date=endDate,
  5318. skip=(page - 1) * pageSize,
  5319. limit=pageSize
  5320. )
  5321. region_map = {}
  5322. client_map = {}
  5323. reviewer_map = {}
  5324. result = []
  5325. for settlement in settlements:
  5326. if settlement.region_id and settlement.region_id not in region_map:
  5327. region = region_crud.get(db, settlement.region_id)
  5328. region_map[settlement.region_id] = region.name if region else None
  5329. if settlement.client_id and settlement.client_id not in client_map:
  5330. client = user_crud.get(db, settlement.client_id)
  5331. client_map[settlement.client_id] = client.real_name if client else None
  5332. if settlement.reviewed_by and settlement.reviewed_by not in reviewer_map:
  5333. reviewer = user_crud.get(db, settlement.reviewed_by)
  5334. reviewer_map[settlement.reviewed_by] = reviewer.real_name if reviewer else None
  5335. result.append({
  5336. "id": settlement.id,
  5337. "orderId": settlement.order_id,
  5338. "clientId": settlement.client_id,
  5339. "clientName": client_map.get(settlement.client_id),
  5340. "regionId": settlement.region_id,
  5341. "regionName": region_map.get(settlement.region_id),
  5342. "amount": float(settlement.amount) if settlement.amount else 0,
  5343. "settlementMethod": settlement.settlement_method,
  5344. "settlementTime": str(settlement.settlement_time) if settlement.settlement_time else None,
  5345. "settlementNote": settlement.settlement_note,
  5346. "settlementFileUrl": settlement.settlement_file_url,
  5347. "reviewedBy": settlement.reviewed_by,
  5348. "reviewedByName": reviewer_map.get(settlement.reviewed_by),
  5349. "reviewedTime": str(settlement.reviewed_time) if settlement.reviewed_time else None,
  5350. "createAt": str(settlement.create_at) if settlement.create_at else None
  5351. })
  5352. return success_response({
  5353. "list": result,
  5354. "total": total,
  5355. "page": page,
  5356. "pageSize": pageSize,
  5357. "totalPages": (total + pageSize - 1) // pageSize
  5358. })
  5359. @router.get("/settlements/statistics", response_model=dict)
  5360. def get_settlement_statistics(
  5361. regionId: Optional[str] = Query(None, description="区域ID"),
  5362. startDate: Optional[str] = Query(None, description="开始日期"),
  5363. endDate: Optional[str] = Query(None, description="结束日期"),
  5364. db: Session = Depends(get_db),
  5365. current_user: dict = Depends(require_admin)
  5366. ):
  5367. """获取结算统计数据"""
  5368. from app.crud.settlement import settlement_crud
  5369. # 区域管理员只能查看自己区域的统计数据
  5370. admin_region_id = get_admin_region_filter(db, current_user)
  5371. if admin_region_id and not regionId:
  5372. regionId = admin_region_id
  5373. elif admin_region_id and regionId != admin_region_id:
  5374. return success_response({
  5375. "pendingOrderCount": 0,
  5376. "pendingAmount": 0,
  5377. "settledCount": 0,
  5378. "settledAmount": 0,
  5379. "refundPendingCount": 0
  5380. })
  5381. stats = settlement_crud.get_statistics(
  5382. db,
  5383. region_id=regionId,
  5384. start_date=startDate,
  5385. end_date=endDate
  5386. )
  5387. return success_response(stats)
  5388. # =========================================
  5389. # 退款管理 API (Web端)
  5390. # =========================================
  5391. @router.get("/refunds", response_model=dict)
  5392. def list_refunds(
  5393. page: int = Query(1, ge=1, description="页码"),
  5394. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5395. regionId: Optional[str] = Query(None, description="区域ID"),
  5396. status: Optional[str] = Query(None, description="状态"),
  5397. orderNo: Optional[str] = Query(None, description="订单号"),
  5398. refundMethod: Optional[str] = Query(None, description="退款方式"),
  5399. startDate: Optional[str] = Query(None, description="开始日期"),
  5400. endDate: Optional[str] = Query(None, description="结束日期"),
  5401. db: Session = Depends(get_db),
  5402. current_user: dict = Depends(require_admin)
  5403. ):
  5404. """获取退款记录列表"""
  5405. from app.crud.settlement import refund_crud
  5406. from app.models.models import BizOrder
  5407. refunds, total = refund_crud.get_multi_with_filters(
  5408. db,
  5409. region_id=regionId,
  5410. order_no=orderNo,
  5411. status=status,
  5412. refund_method=refundMethod,
  5413. start_date=startDate,
  5414. end_date=endDate,
  5415. skip=(page - 1) * pageSize,
  5416. limit=pageSize
  5417. )
  5418. order_map = {}
  5419. result = []
  5420. for refund in refunds:
  5421. if refund.order_id and refund.order_id not in order_map:
  5422. order = db.query(BizOrder).filter(BizOrder.id == refund.order_id).first()
  5423. if order:
  5424. client = user_crud.get(db, order.client_id)
  5425. order_map[refund.order_id] = {
  5426. "orderNo": order.order_no,
  5427. "clientId": order.client_id,
  5428. "clientName": client.real_name if client else None,
  5429. "regionId": order.region_id,
  5430. "totalAmount": float(order.total_amount) if order.total_amount else 0,
  5431. "paidAmount": float(order.paid_amount) if order.paid_amount else 0
  5432. }
  5433. order_info = order_map.get(refund.order_id, {})
  5434. result.append({
  5435. "id": refund.id,
  5436. "orderId": refund.order_id,
  5437. "orderNo": order_info.get("orderNo"),
  5438. "clientId": order_info.get("clientId"),
  5439. "clientName": order_info.get("clientName"),
  5440. "regionId": order_info.get("regionId"),
  5441. "totalAmount": order_info.get("totalAmount"),
  5442. "paidAmount": order_info.get("paidAmount"),
  5443. "refundNo": refund.refund_no,
  5444. "refundAmount": float(refund.refund_amount) if refund.refund_amount else 0,
  5445. "refundMethod": refund.refund_method,
  5446. "refundResult": refund.refund_result,
  5447. "refundTime": str(refund.refund_time) if refund.refund_time else None,
  5448. "refundNoWechat": refund.refund_no_wechat,
  5449. "refundFailReason": refund.refund_fail_reason,
  5450. "status": refund.status,
  5451. "createAt": str(refund.create_at) if refund.create_at else None
  5452. })
  5453. return success_response({
  5454. "list": result,
  5455. "total": total,
  5456. "page": page,
  5457. "pageSize": pageSize,
  5458. "totalPages": (total + pageSize - 1) // pageSize
  5459. })
  5460. @router.get("/refunds/{refund_id}", response_model=dict)
  5461. def get_refund(
  5462. refund_id: str,
  5463. db: Session = Depends(get_db),
  5464. current_user: dict = Depends(require_admin)
  5465. ):
  5466. """获取退款详情"""
  5467. from app.crud.settlement import refund_crud
  5468. from app.models.models import BizOrder
  5469. refund = refund_crud.get(db, refund_id)
  5470. if not refund:
  5471. return error_response(404, "退款记录不存在")
  5472. order = db.query(BizOrder).filter(BizOrder.id == refund.order_id).first()
  5473. client = user_crud.get(db, order.client_id) if order else None
  5474. return success_response({
  5475. "id": refund.id,
  5476. "orderId": refund.order_id,
  5477. "orderNo": order.order_no if order else None,
  5478. "clientId": order.client_id if order else None,
  5479. "clientName": client.real_name if client else None,
  5480. "totalAmount": float(order.total_amount) if order and order.total_amount else 0,
  5481. "paidAmount": float(order.paid_amount) if order and order.paid_amount else 0,
  5482. "refundNo": refund.refund_no,
  5483. "refundAmount": float(refund.refund_amount) if refund.refund_amount else 0,
  5484. "refundMethod": refund.refund_method,
  5485. "refundResult": refund.refund_result,
  5486. "refundTime": str(refund.refund_time) if refund.refund_time else None,
  5487. "refundNoWechat": refund.refund_no_wechat,
  5488. "refundFailReason": refund.refund_fail_reason,
  5489. "status": refund.status,
  5490. "createAt": str(refund.create_at) if refund.create_at else None,
  5491. "createName": refund.create_name
  5492. })
  5493. @router.post("/refunds/wechat-refund/{order_id}", response_model=dict)
  5494. def create_wechat_refund(
  5495. order_id: str,
  5496. request: dict,
  5497. db: Session = Depends(get_db),
  5498. current_user: dict = Depends(require_admin)
  5499. ):
  5500. """微信退款"""
  5501. from app.crud.settlement import refund_crud
  5502. from datetime import datetime
  5503. from decimal import Decimal
  5504. refund_amount = request.get("refundAmount")
  5505. reason = request.get("reason")
  5506. if not refund_amount or refund_amount <= 0:
  5507. return error_response(400, "退款金额必须大于0")
  5508. # 获取订单信息
  5509. from app.models.models import BizOrder
  5510. order = db.query(BizOrder).filter(BizOrder.id == order_id).first()
  5511. if not order:
  5512. return error_response(404, "订单不存在")
  5513. # 检查已支付金额
  5514. paid_amount = float(order.paid_amount) if order.paid_amount else 0
  5515. if refund_amount > paid_amount:
  5516. return error_response(400, "退款金额不能超过已支付金额")
  5517. # 检查是否有处理中的退款
  5518. existing_refunds = refund_crud.get_by_order(db, order_id)
  5519. processing_refund = any(r.status in ["pending", "processing"] for r in existing_refunds)
  5520. if processing_refund:
  5521. return error_response(400, "该订单有退款正在处理中,请勿重复提交")
  5522. creator = {
  5523. "user_id": current_user.get("user_id"),
  5524. "real_name": current_user.get("real_name")
  5525. }
  5526. refund = refund_crud.create_refund(
  5527. db,
  5528. order_id=order_id,
  5529. refund_amount=Decimal(str(refund_amount)),
  5530. refund_method="wechat",
  5531. reason=reason,
  5532. creator=creator
  5533. )
  5534. # 模拟微信退款处理(实际项目中需要调用微信支付API)
  5535. refund_crud.process_refund(
  5536. db,
  5537. refund_id=refund.id,
  5538. refund_result="success",
  5539. refund_no_wechat=f"WXREF{datetime.now().strftime('%Y%m%d%H%M%S')}"
  5540. )
  5541. return success_response({
  5542. "refundId": refund.id,
  5543. "refundNo": refund.refund_no,
  5544. "refundAmount": float(refund.refund_amount),
  5545. "refundResult": "success",
  5546. "refundTime": str(refund.refund_time)
  5547. })
  5548. @router.get("/refunds/{refund_id}/status", response_model=dict)
  5549. def get_refund_status(
  5550. refund_id: str,
  5551. db: Session = Depends(get_db),
  5552. current_user: dict = Depends(require_admin)
  5553. ):
  5554. """查询退款状态"""
  5555. from app.crud.settlement import refund_crud
  5556. refund = refund_crud.get(db, refund_id)
  5557. if not refund:
  5558. return error_response(404, "退款记录不存在")
  5559. return success_response({
  5560. "refundId": refund.id,
  5561. "refundNo": refund.refund_no,
  5562. "refundAmount": float(refund.refund_amount) if refund.refund_amount else 0,
  5563. "refundResult": refund.refund_result,
  5564. "refundTime": str(refund.refund_time) if refund.refund_time else None,
  5565. "refundNoWechat": refund.refund_no_wechat
  5566. })
  5567. @router.post("/refunds/{refund_id}/process", response_model=dict)
  5568. def process_refund(
  5569. refund_id: str,
  5570. request: dict,
  5571. db: Session = Depends(get_db),
  5572. current_user: dict = Depends(require_admin)
  5573. ):
  5574. """处理退款(成功/失败)"""
  5575. from app.crud.settlement import refund_crud
  5576. refund_result = request.get("refundResult")
  5577. refund_no_wechat = request.get("refundNoWechat")
  5578. if not refund_result or refund_result not in ["success", "failed"]:
  5579. return error_response(400, "请提供正确的退款结果")
  5580. refund = refund_crud.process_refund(
  5581. db,
  5582. refund_id=refund_id,
  5583. refund_result=refund_result,
  5584. refund_no_wechat=refund_no_wechat
  5585. )
  5586. if not refund:
  5587. return error_response(404, "退款记录不存在")
  5588. return success_response({
  5589. "refundId": refund.id,
  5590. "refundResult": refund.refund_result,
  5591. "message": "处理成功"
  5592. })
  5593. @router.post("/refunds/{refund_id}/handle-failure", response_model=dict)
  5594. def handle_refund_failure(
  5595. refund_id: str,
  5596. request: dict,
  5597. db: Session = Depends(get_db),
  5598. current_user: dict = Depends(require_admin)
  5599. ):
  5600. """处理退款失败"""
  5601. from app.crud.settlement import refund_crud
  5602. fail_reason = request.get("failReason")
  5603. if not fail_reason:
  5604. return error_response(400, "请提供失败原因")
  5605. refund = refund_crud.handle_refund_failure(
  5606. db,
  5607. refund_id=refund_id,
  5608. fail_reason=fail_reason
  5609. )
  5610. if not refund:
  5611. return error_response(404, "退款记录不存在")
  5612. return success_response({
  5613. "refundId": refund.id,
  5614. "refundResult": refund.refund_result,
  5615. "message": "处理成功"
  5616. })
  5617. @router.get("/refunds/statistics", response_model=dict)
  5618. def get_refund_statistics(
  5619. startDate: Optional[str] = Query(None, description="开始日期"),
  5620. endDate: Optional[str] = Query(None, description="结束日期"),
  5621. db: Session = Depends(get_db),
  5622. current_user: dict = Depends(require_admin)
  5623. ):
  5624. """获取退款统计数据"""
  5625. from app.crud.settlement import refund_crud
  5626. stats = refund_crud.get_refund_statistics(
  5627. db,
  5628. start_date=startDate,
  5629. end_date=endDate
  5630. )
  5631. return success_response(stats)
  5632. # =========================================
  5633. # 配送时效预警 API
  5634. # =========================================
  5635. @router.get("/delivery-warnings", response_model=dict)
  5636. def list_delivery_warnings(
  5637. page: int = Query(1, ge=1, description="页码"),
  5638. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5639. regionId: Optional[str] = Query(None, description="区域ID"),
  5640. urgencyLevel: Optional[str] = Query(None, description="紧急程度: critical/urgent/normal"),
  5641. db: Session = Depends(get_db),
  5642. current_user: dict = Depends(require_admin)
  5643. ):
  5644. """获取配送时效预警列表"""
  5645. from app.crud.delivery import delivery_task_crud
  5646. from datetime import datetime, timedelta
  5647. # 计算时间阈值
  5648. now = datetime.now()
  5649. critical_time = now + timedelta(minutes=30) # 30分钟内
  5650. urgent_time = now + timedelta(minutes=60) # 1小时内
  5651. normal_time = now + timedelta(hours=2) # 2小时内
  5652. # 获取所有待配送任务
  5653. query = db.query(delivery_task_crud.model).filter(
  5654. and_(
  5655. delivery_task_crud.model.is_del == 0,
  5656. delivery_task_crud.model.status.in_(["pending", "assigned", "picking", "picked"]),
  5657. delivery_task_crud.model.effective_time != None,
  5658. delivery_task_crud.model.effective_time >= now
  5659. )
  5660. )
  5661. if regionId:
  5662. query = query.filter(delivery_task_crud.model.region_id == regionId)
  5663. all_tasks = query.order_by(delivery_task_crud.model.effective_time.asc()).all()
  5664. # 计算紧急程度
  5665. result = []
  5666. for task in all_tasks:
  5667. time_diff = (task.effective_time - now).total_seconds() / 60 # 分钟
  5668. if time_diff <= 30:
  5669. urgency = "critical"
  5670. remaining_minutes = int(time_diff)
  5671. elif time_diff <= 60:
  5672. urgency = "urgent"
  5673. remaining_minutes = int(time_diff)
  5674. else:
  5675. urgency = "normal"
  5676. remaining_minutes = int(time_diff)
  5677. # 按紧急程度过滤
  5678. if urgencyLevel and urgency != urgencyLevel:
  5679. continue
  5680. # 获取关联信息
  5681. client_name = None
  5682. if task.order_id:
  5683. from app.crud.order import order_crud
  5684. order = order_crud.get(db, task.order_id)
  5685. if order:
  5686. client = user_crud.get(db, order.client_id)
  5687. client_name = client.real_name if client else None
  5688. region_name = None
  5689. if task.region_id:
  5690. region = region_crud.get(db, task.region_id)
  5691. region_name = region.name if region else None
  5692. deliver_name = None
  5693. if task.deliver_id:
  5694. deliver = user_crud.get(db, task.deliver_id)
  5695. deliver_name = deliver.real_name if deliver else None
  5696. supplier_name = None
  5697. if task.supplier_id:
  5698. supplier = user_crud.get(db, task.supplier_id)
  5699. supplier_name = supplier.real_name if supplier else None
  5700. result.append({
  5701. "id": task.id,
  5702. "taskNo": task.task_no,
  5703. "orderId": task.order_id,
  5704. "regionId": task.region_id,
  5705. "regionName": region_name,
  5706. "clientName": client_name,
  5707. "supplierId": task.supplier_id,
  5708. "supplierName": supplier_name,
  5709. "deliverId": task.deliver_id,
  5710. "deliverName": deliver_name,
  5711. "status": task.status,
  5712. "effectiveTime": str(task.effective_time) if task.effective_time else None,
  5713. "remainingMinutes": remaining_minutes,
  5714. "urgencyLevel": urgency,
  5715. "isAssigned": task.deliver_id is not None,
  5716. "createAt": str(task.create_at) if task.create_at else None
  5717. })
  5718. # 手动分页
  5719. total = len(result)
  5720. start_idx = (page - 1) * pageSize
  5721. end_idx = start_idx + pageSize
  5722. paginated_result = result[start_idx:end_idx]
  5723. return success_response({
  5724. "list": paginated_result,
  5725. "total": total,
  5726. "page": page,
  5727. "pageSize": pageSize,
  5728. "totalPages": (total + pageSize - 1) // pageSize
  5729. })
  5730. @router.get("/delivery-warnings/statistics", response_model=dict)
  5731. def get_delivery_warning_statistics(
  5732. regionId: Optional[str] = Query(None, description="区域ID"),
  5733. db: Session = Depends(get_db),
  5734. current_user: dict = Depends(require_admin)
  5735. ):
  5736. """获取配送时效预警统计"""
  5737. from app.crud.delivery import delivery_task_crud
  5738. from datetime import datetime, timedelta
  5739. now = datetime.now()
  5740. # 基础查询
  5741. base_query = db.query(delivery_task_crud.model).filter(
  5742. and_(
  5743. delivery_task_crud.model.is_del == 0,
  5744. delivery_task_crud.model.status.in_(["pending", "assigned", "picking", "picked"]),
  5745. delivery_task_crud.model.effective_time != None,
  5746. delivery_task_crud.model.effective_time >= now
  5747. )
  5748. )
  5749. if regionId:
  5750. base_query = base_query.filter(delivery_task_crud.model.region_id == regionId)
  5751. all_tasks = base_query.all()
  5752. critical_count = 0
  5753. urgent_count = 0
  5754. normal_count = 0
  5755. unassigned_count = 0
  5756. total_pending = len(all_tasks)
  5757. for task in all_tasks:
  5758. time_diff = (task.effective_time - now).total_seconds() / 60
  5759. if time_diff <= 30:
  5760. critical_count += 1
  5761. elif time_diff <= 60:
  5762. urgent_count += 1
  5763. else:
  5764. normal_count += 1
  5765. if not task.deliver_id:
  5766. unassigned_count += 1
  5767. return success_response({
  5768. "totalPending": total_pending,
  5769. "criticalCount": critical_count,
  5770. "urgentCount": urgent_count,
  5771. "normalCount": normal_count,
  5772. "unassignedCount": unassigned_count
  5773. })
  5774. @router.post("/delivery-warnings/{task_id}/reassign", response_model=dict)
  5775. def reassign_delivery_task(
  5776. task_id: str,
  5777. request: dict,
  5778. db: Session = Depends(get_db),
  5779. current_user: dict = Depends(require_admin)
  5780. ):
  5781. """紧急重新分配配送任务"""
  5782. from app.crud.delivery import delivery_task_crud
  5783. new_deliver_id = request.get("deliverId")
  5784. reason = request.get("reason")
  5785. if not new_deliver_id:
  5786. return error_response(400, "请选择新的配送员")
  5787. task = delivery_task_crud.get(db, task_id)
  5788. if not task:
  5789. return error_response(404, "任务不存在")
  5790. if task.status in ["completed", "cancelled"]:
  5791. return error_response(400, "已完成或已取消的任务无法重新分配")
  5792. # 验证新配送员
  5793. new_deliver = user_crud.get(db, new_deliver_id)
  5794. if not new_deliver:
  5795. return error_response(404, "配送员不存在")
  5796. if new_deliver.role != "deliver":
  5797. return error_response(400, "该用户不是配送员")
  5798. old_deliver_id = task.deliver_id
  5799. old_deliver_name = None
  5800. if old_deliver_id:
  5801. old_deliver = user_crud.get(db, old_deliver_id)
  5802. old_deliver_name = old_deliver.real_name if old_deliver else None
  5803. # 更新任务(换配送员:只重置配送员侧待取货,不重置供应商备货进度)
  5804. task.deliver_id = new_deliver_id
  5805. task.update_at = datetime.now()
  5806. task.deliverer_status = "pending_pickup"
  5807. delivery_task_crud._sync_legacy_status_from_dual(task)
  5808. # 如果之前没有分配配送员,设置新的截止时间
  5809. if not old_deliver_id:
  5810. task.effective_time = datetime.now() + timedelta(hours=4)
  5811. db.commit()
  5812. db.refresh(task)
  5813. return success_response({
  5814. "id": task.id,
  5815. "taskNo": task.task_no,
  5816. "newDeliverId": new_deliver_id,
  5817. "newDeliverName": new_deliver.real_name,
  5818. "oldDeliverId": old_deliver_id,
  5819. "oldDeliverName": old_deliver_name,
  5820. "message": "任务重新分配成功"
  5821. })
  5822. def get_client_ip(request: Request) -> str:
  5823. """获取客户端IP地址"""
  5824. forwarded = request.headers.get("X-Forwarded-For")
  5825. if forwarded:
  5826. return forwarded.split(",")[0].strip()
  5827. return request.client.host if request.client else "unknown"
  5828. # =========================================
  5829. # API 请求日志(中间件落库,此处仅查询/删除)
  5830. # =========================================
  5831. @router.get("/api-request-logs", response_model=dict)
  5832. def list_api_request_logs(
  5833. page: int = Query(1, ge=1, description="页码"),
  5834. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5835. httpMethod: Optional[str] = Query(None, description="HTTP 方法"),
  5836. statusCode: Optional[int] = Query(None, description="HTTP 状态码"),
  5837. pathPrefix: Optional[str] = Query(None, description="路径包含"),
  5838. keyword: Optional[str] = Query(None, description="关键词"),
  5839. startDate: Optional[str] = Query(None, description="开始日期"),
  5840. endDate: Optional[str] = Query(None, description="结束日期"),
  5841. db: Session = Depends(get_db),
  5842. current_user: dict = Depends(require_admin)
  5843. ):
  5844. """API 请求日志列表"""
  5845. from app.crud.api_request_log import api_request_log_crud
  5846. logs, total = api_request_log_crud.get_multi_with_filters(
  5847. db,
  5848. http_method=httpMethod,
  5849. status_code=statusCode,
  5850. path_prefix=pathPrefix,
  5851. keyword=keyword,
  5852. start_date=startDate,
  5853. end_date=endDate,
  5854. skip=(page - 1) * pageSize,
  5855. limit=pageSize,
  5856. )
  5857. return success_response({
  5858. "list": [{
  5859. "id": log.id,
  5860. "httpMethod": log.http_method,
  5861. "path": log.path,
  5862. "queryString": log.query_string,
  5863. "statusCode": log.status_code,
  5864. "durationMs": log.duration_ms,
  5865. "userId": log.user_id,
  5866. "username": log.username,
  5867. "role": log.role,
  5868. "ipAddress": log.ip_address,
  5869. "userAgent": log.user_agent,
  5870. "requestBody": log.request_body,
  5871. "responseBody": log.response_body,
  5872. "createAt": str(log.create_at) if log.create_at else None,
  5873. } for log in logs],
  5874. "total": total,
  5875. "page": page,
  5876. "pageSize": pageSize,
  5877. "totalPages": (total + pageSize - 1) // pageSize
  5878. })
  5879. @router.get("/api-request-logs/{log_id}", response_model=dict)
  5880. def get_api_request_log(
  5881. log_id: str,
  5882. db: Session = Depends(get_db),
  5883. current_user: dict = Depends(require_admin)
  5884. ):
  5885. """API 请求日志详情"""
  5886. from app.crud.api_request_log import api_request_log_crud
  5887. log = api_request_log_crud.get(db, log_id)
  5888. if not log:
  5889. return error_response(404, "日志不存在")
  5890. return success_response({
  5891. "id": log.id,
  5892. "httpMethod": log.http_method,
  5893. "path": log.path,
  5894. "queryString": log.query_string,
  5895. "statusCode": log.status_code,
  5896. "durationMs": log.duration_ms,
  5897. "userId": log.user_id,
  5898. "username": log.username,
  5899. "role": log.role,
  5900. "ipAddress": log.ip_address,
  5901. "userAgent": log.user_agent,
  5902. "requestBody": log.request_body,
  5903. "responseBody": log.response_body,
  5904. "createAt": str(log.create_at) if log.create_at else None,
  5905. })
  5906. @router.delete("/api-request-logs/{log_id}", response_model=dict)
  5907. def delete_api_request_log(
  5908. log_id: str,
  5909. db: Session = Depends(get_db),
  5910. current_user: dict = Depends(require_admin)
  5911. ):
  5912. """删除 API 请求日志(软删除)"""
  5913. from app.crud.api_request_log import api_request_log_crud
  5914. if not api_request_log_crud.delete(db, log_id):
  5915. return error_response(404, "日志不存在")
  5916. return success_response({"id": log_id})
  5917. # =========================================
  5918. # 数据统计 API
  5919. # =========================================
  5920. @router.get("/statistics/dashboard", response_model=dict)
  5921. def get_dashboard_statistics(
  5922. regionId: Optional[str] = Query(None, description="区域ID"),
  5923. db: Session = Depends(get_db),
  5924. current_user: dict = Depends(require_admin)
  5925. ):
  5926. """获取仪表盘统计数据"""
  5927. from app.crud.statistics import statistics_crud
  5928. stats = statistics_crud.get_dashboard_summary(db, region_id=regionId)
  5929. return success_response(stats)
  5930. @router.get("/statistics/orders", response_model=dict)
  5931. def get_order_statistics(
  5932. regionId: Optional[str] = Query(None, description="区域ID"),
  5933. startDate: Optional[str] = Query(None, description="开始日期"),
  5934. endDate: Optional[str] = Query(None, description="结束日期"),
  5935. db: Session = Depends(get_db),
  5936. current_user: dict = Depends(require_admin)
  5937. ):
  5938. """获取订单统计数据"""
  5939. from app.crud.statistics import statistics_crud
  5940. stats = statistics_crud.get_order_statistics(
  5941. db,
  5942. region_id=regionId,
  5943. start_date=startDate,
  5944. end_date=endDate
  5945. )
  5946. return success_response(stats)
  5947. @router.get("/statistics/orders/trend", response_model=dict)
  5948. def get_order_trend(
  5949. regionId: Optional[str] = Query(None, description="区域ID"),
  5950. days: int = Query(7, ge=1, le=30, description="统计天数"),
  5951. db: Session = Depends(get_db),
  5952. current_user: dict = Depends(require_admin)
  5953. ):
  5954. """获取订单趋势数据"""
  5955. from app.crud.statistics import statistics_crud
  5956. trend = statistics_crud.get_order_trend(
  5957. db,
  5958. region_id=regionId,
  5959. days=days
  5960. )
  5961. return success_response(trend)
  5962. @router.get("/statistics/orders/today-by-region", response_model=dict)
  5963. def get_today_orders_by_region(
  5964. regionId: Optional[str] = Query(None, description="区域ID,传入时仅返回该区域"),
  5965. db: Session = Depends(get_db),
  5966. current_user: dict = Depends(require_admin)
  5967. ):
  5968. """今日各区域营业额(元)与订单数(按区域列表,无单为 0)"""
  5969. from app.crud.statistics import statistics_crud
  5970. rows = statistics_crud.get_today_order_stats_by_region(db, region_id=regionId)
  5971. return success_response(rows)
  5972. @router.get("/statistics/orders/today-by-client", response_model=dict)
  5973. def get_today_orders_by_client(
  5974. regionId: Optional[str] = Query(None, description="区域ID"),
  5975. limit: int = Query(30, ge=1, le=100, description="最多返回客户条数"),
  5976. db: Session = Depends(get_db),
  5977. current_user: dict = Depends(require_admin)
  5978. ):
  5979. """今日下单客户:下单金额(元)、商品数量合计(按客户,金额降序)"""
  5980. from app.crud.statistics import statistics_crud
  5981. rows = statistics_crud.get_today_order_stats_by_client(
  5982. db, region_id=regionId, limit=limit
  5983. )
  5984. return success_response(rows)
  5985. @router.get("/statistics/financial", response_model=dict)
  5986. def get_financial_statistics(
  5987. regionId: Optional[str] = Query(None, description="区域ID"),
  5988. startDate: Optional[str] = Query(None, description="开始日期"),
  5989. endDate: Optional[str] = Query(None, description="结束日期"),
  5990. db: Session = Depends(get_db),
  5991. current_user: dict = Depends(require_admin)
  5992. ):
  5993. """获取财务统计数据"""
  5994. from app.crud.statistics import statistics_crud
  5995. stats = statistics_crud.get_financial_statistics(
  5996. db,
  5997. region_id=regionId,
  5998. start_date=startDate,
  5999. end_date=endDate
  6000. )
  6001. return success_response(stats)
  6002. @router.get("/statistics/financial/trend", response_model=dict)
  6003. def get_financial_trend(
  6004. regionId: Optional[str] = Query(None, description="区域ID"),
  6005. days: int = Query(7, ge=1, le=30, description="统计天数"),
  6006. db: Session = Depends(get_db),
  6007. current_user: dict = Depends(require_admin)
  6008. ):
  6009. """获取财务趋势数据"""
  6010. from app.crud.statistics import statistics_crud
  6011. trend = statistics_crud.get_financial_trend(
  6012. db,
  6013. region_id=regionId,
  6014. days=days
  6015. )
  6016. return success_response(trend)
  6017. @router.get("/statistics/delivery", response_model=dict)
  6018. def get_delivery_statistics(
  6019. regionId: Optional[str] = Query(None, description="区域ID"),
  6020. startDate: Optional[str] = Query(None, description="开始日期"),
  6021. endDate: Optional[str] = Query(None, description="结束日期"),
  6022. db: Session = Depends(get_db),
  6023. current_user: dict = Depends(require_admin)
  6024. ):
  6025. """获取配送统计数据"""
  6026. from app.crud.statistics import statistics_crud
  6027. stats = statistics_crud.get_delivery_statistics(
  6028. db,
  6029. region_id=regionId,
  6030. start_date=startDate,
  6031. end_date=endDate
  6032. )
  6033. return success_response(stats)
  6034. @router.get("/statistics/products", response_model=dict)
  6035. def get_product_statistics(
  6036. regionId: Optional[str] = Query(None, description="区域ID"),
  6037. startDate: Optional[str] = Query(None, description="开始日期"),
  6038. endDate: Optional[str] = Query(None, description="结束日期"),
  6039. limit: int = Query(10, ge=1, le=50, description="返回数量"),
  6040. db: Session = Depends(get_db),
  6041. current_user: dict = Depends(require_admin)
  6042. ):
  6043. """获取商品销售排行"""
  6044. from app.crud.statistics import statistics_crud
  6045. stats = statistics_crud.get_product_statistics(
  6046. db,
  6047. region_id=regionId,
  6048. start_date=startDate,
  6049. end_date=endDate,
  6050. limit=limit
  6051. )
  6052. return success_response(stats)
  6053. @router.get("/statistics/customers", response_model=dict)
  6054. def get_customer_statistics(
  6055. regionId: Optional[str] = Query(None, description="区域ID"),
  6056. startDate: Optional[str] = Query(None, description="开始日期"),
  6057. endDate: Optional[str] = Query(None, description="结束日期"),
  6058. limit: int = Query(10, ge=1, le=50, description="返回数量"),
  6059. db: Session = Depends(get_db),
  6060. current_user: dict = Depends(require_admin)
  6061. ):
  6062. """获取客户订单排行"""
  6063. from app.crud.statistics import statistics_crud
  6064. stats = statistics_crud.get_customer_statistics(
  6065. db,
  6066. region_id=regionId,
  6067. start_date=startDate,
  6068. end_date=endDate,
  6069. limit=limit
  6070. )
  6071. return success_response(stats)
  6072. # =========================================
  6073. # 缺失的订单相关 API
  6074. # =========================================
  6075. @router.post("/orders/{order_id}/complete", response_model=dict)
  6076. def force_complete_order(
  6077. order_id: str,
  6078. db: Session = Depends(get_db),
  6079. current_user: dict = Depends(require_admin)
  6080. ):
  6081. """完结订单"""
  6082. from app.crud.order import order_crud
  6083. order = order_crud.get(db, order_id)
  6084. if not order:
  6085. return error_response(404, "订单不存在")
  6086. # 新状态模型:待收货阶段可由运营强制完结
  6087. if getattr(order, "order_status", None) != "pending_confirm":
  6088. return error_response(400, "只有待收货订单才能完结")
  6089. try:
  6090. completed_order = order_crud.force_complete(db, order_id, current_user.get("user_id"))
  6091. return success_response({
  6092. "id": completed_order.id,
  6093. "status": completed_order.status,
  6094. "message": "订单已完结"
  6095. })
  6096. except Exception as e:
  6097. return error_response(400, str(e))
  6098. @router.post("/orders/{order_id}/cancel", response_model=dict)
  6099. def cancel_order_admin(
  6100. order_id: str,
  6101. request: dict,
  6102. db: Session = Depends(get_db),
  6103. current_user: dict = Depends(require_admin)
  6104. ):
  6105. """运营端取消订单"""
  6106. from app.crud.order import order_crud
  6107. order = order_crud.get(db, order_id)
  6108. if not order:
  6109. return error_response(404, "订单不存在")
  6110. # 新状态模型:仅未完成且未取消订单允许运营取消
  6111. if getattr(order, "order_status", None) in ["completed", "cancelled"]:
  6112. return error_response(400, "已完成或已取消订单不能再次取消")
  6113. reason = request.get("reason", "")
  6114. note = request.get("note", "")
  6115. evidence_image_urls = request.get("evidenceImageUrls", []) or []
  6116. if not reason:
  6117. return error_response(400, "请填写取消原因")
  6118. if not isinstance(evidence_image_urls, list):
  6119. return error_response(400, "evidenceImageUrls 格式不正确")
  6120. try:
  6121. cancelled_order = order_crud.admin_cancel(
  6122. db,
  6123. order_id=order_id,
  6124. operator_id=current_user.get("user_id"),
  6125. operator_name=current_user.get("real_name"),
  6126. reason=reason,
  6127. note=note,
  6128. evidence_image_urls=evidence_image_urls,
  6129. )
  6130. if evidence_image_urls:
  6131. from app.models.models import BizAttachment
  6132. from app.core.utils import generate_id
  6133. for url in evidence_image_urls:
  6134. if not isinstance(url, str) or not url.strip():
  6135. continue
  6136. db.add(BizAttachment(
  6137. id=generate_id(),
  6138. business_type="order",
  6139. business_id=order_id,
  6140. file_name=url.split("/")[-1][:200],
  6141. file_url=url,
  6142. file_type="image/*",
  6143. upload_by=current_user.get("user_id"),
  6144. upload_by_name=current_user.get("real_name"),
  6145. create_by=current_user.get("user_id"),
  6146. create_name=current_user.get("real_name"),
  6147. ))
  6148. db.commit()
  6149. return success_response({
  6150. "id": cancelled_order.id,
  6151. "status": cancelled_order.status,
  6152. "message": "订单已取消"
  6153. })
  6154. except Exception as e:
  6155. return error_response(400, str(e))
  6156. @router.get("/orders/adjustable", response_model=dict)
  6157. def list_adjustable_orders(
  6158. keyword: Optional[str] = Query(None, description="关键词搜索"),
  6159. db: Session = Depends(get_db),
  6160. current_user: dict = Depends(require_admin)
  6161. ):
  6162. """获取可调整的订单列表"""
  6163. from app.crud.order import order_crud, order_item_crud
  6164. # 可调整的订单状态:待支付、待收货(线下单)
  6165. adjustable_statuses = ["pending_payment", "pending_confirm"]
  6166. orders, total = order_crud.get_multi_with_filters(
  6167. db,
  6168. status=None, # 不按状态过滤,我们手动过滤
  6169. order_no=keyword,
  6170. skip=0,
  6171. limit=100 # 默认获取100条
  6172. )
  6173. # 过滤出可调整的订单
  6174. adjustable_orders = []
  6175. for order in orders:
  6176. if getattr(order, "order_status", None) in adjustable_statuses and order_crud.normalize_payment_method(order.payment_method) == "offline":
  6177. item_count = order_item_crud.get_count_by_order(db, order.id)
  6178. adjustable_orders.append({
  6179. "id": order.id,
  6180. "orderNo": order.order_no,
  6181. "status": order.status,
  6182. "orderStatus": getattr(order, "order_status", None) or "pending_confirm",
  6183. "deliveryStatus": getattr(order, "delivery_status", None) or "pending_dispatch",
  6184. "payStatus": getattr(order, "pay_status", None) or "pending_payment",
  6185. "statusText": ORDER_STATUS_MAP.get(order.status, order.status),
  6186. "totalAmount": float(order.total_amount) if order.total_amount else 0,
  6187. "itemCount": item_count,
  6188. "createAt": str(order.create_at) if order.create_at else None
  6189. })
  6190. return success_response({
  6191. "list": adjustable_orders,
  6192. "total": len(adjustable_orders)
  6193. })
  6194. @router.get("/orders/{order_id}/items", response_model=dict)
  6195. def get_order_items(
  6196. order_id: str,
  6197. db: Session = Depends(get_db),
  6198. current_user: dict = Depends(require_admin)
  6199. ):
  6200. """获取订单商品列表"""
  6201. from app.crud.order import order_crud, order_item_crud
  6202. order = order_crud.get(db, order_id)
  6203. if not order:
  6204. return error_response(404, "订单不存在")
  6205. items = order_item_crud.get_by_order(db, order_id)
  6206. from app.crud.price_list import price_list_crud
  6207. price_list = price_list_crud.get(db, order.price_list_id) if order.price_list_id else None
  6208. supplier_id_from_price_list = getattr(price_list, "supplier_id", None) if price_list else None
  6209. supplier_name_from_price_list = None
  6210. if supplier_id_from_price_list:
  6211. _sup_u = user_crud.get(db, supplier_id_from_price_list)
  6212. if _sup_u:
  6213. supplier_name_from_price_list = _sup_u.real_name or _sup_u.username
  6214. pl_ids_for_order = [order.price_list_id] if order.price_list_id else []
  6215. pli_map_for_order = _price_list_item_map(db, pl_ids_for_order)
  6216. from app.crud.delivery import delivery_task_item_crud as _merge_task_delivered_items
  6217. _line_delivered_from_task = _merge_task_delivered_items.get_delivered_quantity_by_order_item(db, order_id)
  6218. result = []
  6219. for item in items:
  6220. product = product_crud.get(db, item.product_id)
  6221. unit_name = None
  6222. if item.unit_id:
  6223. u = unit_crud.get(db, item.unit_id)
  6224. unit_name = u.name if u else None
  6225. category_name = None
  6226. if product and product.category_id:
  6227. cat = category_crud.get(db, product.category_id)
  6228. category_name = cat.name if cat else None
  6229. _oi_dq = float(item.delivered_quantity) if item.delivered_quantity else 0.0
  6230. _ti_dq = float(_line_delivered_from_task.get(item.id, 0.0))
  6231. _merged_dq = max(_oi_dq, _ti_dq)
  6232. qty = float(item.quantity) if item.quantity else 0
  6233. selling_u = float(item.unit_price) if item.unit_price else 0
  6234. selling_amt = float(item.amount) if item.amount else round(qty * selling_u, 2)
  6235. pli = pli_map_for_order.get((order.price_list_id, item.product_id, item.unit_id))
  6236. supplier_u = _supplier_unit_yuan_from_pli(pli)
  6237. if supplier_u is None:
  6238. supplier_u = selling_u
  6239. supplier_amt = round(qty * supplier_u, 2)
  6240. result.append({
  6241. "id": item.id,
  6242. "productId": item.product_id,
  6243. "productName": product.name if product else None,
  6244. "imageUrl": getattr(product, "image_url", None) if product else None,
  6245. "categoryName": category_name,
  6246. "unitId": item.unit_id,
  6247. "unitName": unit_name,
  6248. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)) if product else None,
  6249. "supplierId": supplier_id_from_price_list,
  6250. "supplierName": supplier_name_from_price_list,
  6251. "quantity": qty,
  6252. "unitPrice": selling_u,
  6253. "amount": selling_amt,
  6254. "sellingUnitPrice": selling_u,
  6255. "sellingAmount": selling_amt,
  6256. "supplierUnitPrice": supplier_u,
  6257. "supplierAmount": supplier_amt,
  6258. "deliveredQuantity": _merged_dq,
  6259. "status": item.status
  6260. })
  6261. return success_response({
  6262. "list": result,
  6263. "total": len(result)
  6264. })
  6265. # =========================================
  6266. # 商品简单列表 API
  6267. # =========================================
  6268. @router.get("/products/simple", response_model=dict)
  6269. def list_products_simple(
  6270. keyword: Optional[str] = Query(None, description="关键词搜索"),
  6271. categoryId: Optional[str] = Query(None, description="分类ID"),
  6272. db: Session = Depends(get_db),
  6273. current_user: dict = Depends(require_admin)
  6274. ):
  6275. """获取商品简单列表(用于订单调整选择替代商品)"""
  6276. from app.models.models import BizProduct
  6277. query = db.query(BizProduct).filter(BizProduct.is_del == 0, BizProduct.is_active == 1)
  6278. if keyword:
  6279. query = query.filter(BizProduct.name.ilike(f"%{keyword}%"))
  6280. if categoryId:
  6281. query = query.filter(BizProduct.category_id == categoryId)
  6282. products = query.order_by(BizProduct.name).limit(100).all()
  6283. result = []
  6284. for p in products:
  6285. category_name = None
  6286. if p.category_id:
  6287. cat = category_crud.get(db, p.category_id)
  6288. category_name = cat.name if cat else None
  6289. unit_name = None
  6290. if p.unit_id:
  6291. u = unit_crud.get(db, p.unit_id)
  6292. unit_name = u.name if u else None
  6293. result.append({
  6294. "id": p.id,
  6295. "name": p.name,
  6296. "categoryId": p.category_id,
  6297. "categoryName": category_name,
  6298. "unitId": p.unit_id,
  6299. "unitName": unit_name,
  6300. "imageUrl": p.image_url
  6301. })
  6302. return success_response({
  6303. "list": result,
  6304. "total": len(result)
  6305. })
  6306. # =========================================
  6307. # 询价单简单列表 API
  6308. # =========================================
  6309. @router.get("/inquiries/simple", response_model=dict)
  6310. def list_inquiries_simple(
  6311. status: Optional[str] = Query(None, description="状态"),
  6312. db: Session = Depends(get_db),
  6313. current_user: dict = Depends(require_admin)
  6314. ):
  6315. """获取询价单简单列表(用于报价对比选择)"""
  6316. from app.models.models import BizInquiry
  6317. query = db.query(BizInquiry).filter(BizInquiry.is_del == 0)
  6318. if status:
  6319. query = query.filter(BizInquiry.status == status)
  6320. inquiries = query.order_by(BizInquiry.create_at.desc()).limit(50).all()
  6321. result = []
  6322. for inquiry in inquiries:
  6323. region_name = None
  6324. if inquiry.region_id:
  6325. region = region_crud.get(db, inquiry.region_id)
  6326. region_name = region.name if region else None
  6327. result.append({
  6328. "id": inquiry.id,
  6329. "title": inquiry.title,
  6330. "status": inquiry.status,
  6331. "regionId": inquiry.region_id,
  6332. "regionName": region_name,
  6333. "createAt": str(inquiry.create_at) if inquiry.create_at else None
  6334. })
  6335. return success_response({
  6336. "list": result,
  6337. "total": len(result)
  6338. })
  6339. # =========================================
  6340. # 报价确认供应商 API
  6341. # =========================================
  6342. @router.post("/quotations/confirm-supplier", response_model=dict)
  6343. def confirm_quotation_supplier(
  6344. request: dict,
  6345. db: Session = Depends(get_db),
  6346. current_user: dict = Depends(require_admin)
  6347. ):
  6348. """确认选择供应商报价,并生成区域生效价格清单(active)
  6349. 约束:
  6350. - 同一询价单,仅允许 1 个报价单为 selected
  6351. - 报价单状态仅使用:submitted / selected
  6352. - 不改变询价单状态(仍为 published 等业务状态)
  6353. """
  6354. from app.models.models import BizInquiry, BizQuotation, BizPriceList, BizPriceListItem
  6355. from app.crud.quotation import quotation_crud, quotation_item_crud
  6356. from app.crud.inquiry import inquiry_item_crud
  6357. from app.crud.product import product_crud
  6358. from app.core.utils import generate_id
  6359. from sqlalchemy import and_
  6360. from decimal import Decimal
  6361. inquiry_id = request.get("inquiryId")
  6362. quotation_id = request.get("quotationId")
  6363. final_price_items = request.get("finalPriceItems") or []
  6364. if not inquiry_id or not quotation_id:
  6365. return error_response(400, "询价单ID和报价ID不能为空")
  6366. inquiry = db.query(BizInquiry).filter(and_(BizInquiry.id == inquiry_id, BizInquiry.is_del == 0)).first()
  6367. if not inquiry:
  6368. return error_response(404, "询价单不存在")
  6369. quotation = quotation_crud.get(db, quotation_id)
  6370. if not quotation:
  6371. return error_response(404, "报价不存在")
  6372. if quotation.inquiry_id != inquiry_id:
  6373. return error_response(400, "报价不属于该询价单")
  6374. # 询价单必须处于发布中,才允许选择供应商生成生效价格
  6375. if inquiry.status != "published":
  6376. return error_response(400, "只能对已发布状态的询价单选择供应商报价")
  6377. # 同一询价仅允许一个 selected:先将其它报价恢复为 submitted
  6378. db.query(BizQuotation).filter(
  6379. and_(
  6380. BizQuotation.inquiry_id == inquiry_id,
  6381. BizQuotation.id != quotation_id,
  6382. BizQuotation.is_del == 0
  6383. )
  6384. ).update({"status": "submitted"}, synchronize_session=False)
  6385. # 当前报价置为 selected
  6386. quotation.status = "selected"
  6387. # 生成价格清单:范围仅询价单的商品
  6388. inquiry_items = inquiry_item_crud.get_by_inquiry(db, inquiry_id)
  6389. inquiry_product_ids = {i.product_id for i in inquiry_items if i and i.product_id}
  6390. if not inquiry_product_ids:
  6391. return error_response(400, "询价单必须包含至少一个商品")
  6392. quotation_items = quotation_item_crud.get_by_quotation(db, quotation_id)
  6393. quotation_item_by_pid: dict[str, any] = {}
  6394. for qi in quotation_items or []:
  6395. pid = str(getattr(qi, "product_id", "") or "")
  6396. if not pid:
  6397. continue
  6398. if pid in inquiry_product_ids:
  6399. quotation_item_by_pid[pid] = qi
  6400. # 允许供应商某些商品未报价:只要运营端传入了最终售价(finalPriceItems)即可生成价格清单
  6401. if not quotation_item_by_pid and not final_price_items:
  6402. return error_response(400, "该报价单未包含本询价单商品报价,且未传入最终售价,无法生成价格清单")
  6403. # 计算版本号(区域维度自增)
  6404. max_version_row = db.query(BizPriceList).filter(
  6405. and_(BizPriceList.region_id == inquiry.region_id, BizPriceList.is_del == 0)
  6406. ).order_by(BizPriceList.version.desc()).first()
  6407. next_version = (max_version_row.version + 1) if max_version_row and max_version_row.version else 1
  6408. # 将该区域其他 active 价格清单置为 inactive
  6409. db.query(BizPriceList).filter(
  6410. and_(
  6411. BizPriceList.region_id == inquiry.region_id,
  6412. BizPriceList.status == "active",
  6413. BizPriceList.is_del == 0
  6414. )
  6415. ).update({"status": "inactive"}, synchronize_session=False)
  6416. # 创建新价格清单(直接生效)
  6417. price_list_id = generate_id()
  6418. now = datetime.now()
  6419. price_list = BizPriceList(
  6420. id=price_list_id,
  6421. region_id=inquiry.region_id,
  6422. supplier_id=quotation.supplier_id,
  6423. inquiry_id=inquiry_id,
  6424. quotation_id=quotation_id,
  6425. source_type="quotation_select",
  6426. version=next_version,
  6427. status="active",
  6428. effective_time=now,
  6429. published_by=current_user.get("user_id"),
  6430. published_time=now,
  6431. remark=f"由询价单选择供应商报价生成(询价={inquiry_id}, 报价={quotation_id})",
  6432. create_by=current_user.get("user_id"),
  6433. create_name=current_user.get("real_name")
  6434. )
  6435. db.add(price_list)
  6436. db.flush()
  6437. # 可选:前端传入最终售卖价 + 本次调价系数(用于回显与二次发布)
  6438. # key 统一使用 str(product_id),避免类型不一致导致匹配失败
  6439. final_price_map: dict[str, Decimal] = {}
  6440. pricing_coeff_map: dict[str, Decimal] = {}
  6441. if final_price_items:
  6442. if not isinstance(final_price_items, list):
  6443. return error_response(400, "finalPriceItems 参数格式错误")
  6444. for it in final_price_items:
  6445. if not isinstance(it, dict):
  6446. return error_response(400, "finalPriceItems 参数格式错误")
  6447. pid = it.get("productId")
  6448. price = it.get("price")
  6449. pricing_coeff = it.get("pricingCoefficient")
  6450. if not pid:
  6451. return error_response(400, "finalPriceItems.productId 不能为空")
  6452. pid_key = str(pid)
  6453. try:
  6454. price_decimal = Decimal(str(price))
  6455. except Exception:
  6456. return error_response(400, f"商品 {pid} 的价格格式不正确")
  6457. if price_decimal <= Decimal("0"):
  6458. return error_response(400, f"商品 {pid} 的价格必须大于0")
  6459. final_price_map[pid_key] = price_decimal.quantize(Decimal("0.01"))
  6460. if pricing_coeff is not None and pricing_coeff != "":
  6461. try:
  6462. coeff_decimal = Decimal(str(pricing_coeff))
  6463. except Exception:
  6464. return error_response(400, f"商品 {pid} 的调价系数格式不正确")
  6465. pricing_coeff_map[pid_key] = coeff_decimal.quantize(Decimal("0.01"))
  6466. # 写入价格清单明细:范围=询价单的商品(不要求供应商都报价)
  6467. for ii in inquiry_items:
  6468. pid_key = str(getattr(ii, "product_id", "") or "")
  6469. if not pid_key:
  6470. continue
  6471. qi = quotation_item_by_pid.get(pid_key)
  6472. final_price = final_price_map.get(pid_key)
  6473. pricing_coeff = pricing_coeff_map.get(pid_key)
  6474. # 最终售价优先取前端传入;否则回退为供应商报价
  6475. if final_price is None:
  6476. if qi is not None and getattr(qi, "price", None) is not None:
  6477. final_price = Decimal(str(qi.price)).quantize(Decimal("0.01"))
  6478. else:
  6479. return error_response(400, f"商品 {pid_key} 缺少供应商报价,且未传入最终售价,无法生成价格清单")
  6480. # 单位ID:优先报价单项;否则从商品表取
  6481. unit_id = getattr(qi, "unit_id", None) if qi is not None else None
  6482. if not unit_id:
  6483. product_for_unit = product_crud.get(db, pid_key)
  6484. unit_id = getattr(product_for_unit, "unit_id", None) if product_for_unit else None
  6485. if not unit_id:
  6486. return error_response(400, f"商品 {pid_key} 缺少单位信息,无法生成价格清单")
  6487. # 若前端未传调价系数:尝试通过(最终价, 供应商报价)反推;再兜底商品默认系数
  6488. if pricing_coeff is None:
  6489. if qi is not None and getattr(qi, "price", None) is not None:
  6490. try:
  6491. supplier_price_decimal = Decimal(str(qi.price))
  6492. except Exception:
  6493. supplier_price_decimal = Decimal("0")
  6494. if supplier_price_decimal > Decimal("0"):
  6495. try:
  6496. pricing_coeff = ((final_price / supplier_price_decimal) - Decimal("1")) * Decimal("100")
  6497. pricing_coeff = pricing_coeff.quantize(Decimal("0.01"))
  6498. except Exception:
  6499. pricing_coeff = None
  6500. if pricing_coeff is None:
  6501. product = product_crud.get(db, pid_key)
  6502. raw_default = getattr(product, "price_coefficient", None) if product else None
  6503. try:
  6504. pricing_coeff = Decimal(str(raw_default)).quantize(Decimal("0.01")) if raw_default is not None else Decimal("0.00")
  6505. except Exception:
  6506. pricing_coeff = Decimal("0.00")
  6507. pli = BizPriceListItem(
  6508. id=generate_id(),
  6509. price_list_id=price_list_id,
  6510. product_id=pid_key,
  6511. unit_id=unit_id,
  6512. price=final_price,
  6513. pricing_coefficient=pricing_coeff,
  6514. create_by=current_user.get("user_id"),
  6515. create_name=current_user.get("real_name")
  6516. )
  6517. db.add(pli)
  6518. db.commit()
  6519. return success_response({
  6520. "message": "已选择供应商报价并生成生效价格",
  6521. "inquiryId": inquiry_id,
  6522. "quotationId": quotation_id,
  6523. "priceListId": price_list_id,
  6524. "priceVersion": next_version
  6525. })
  6526. # =========================================
  6527. # 价格版本管理 API
  6528. # =========================================
  6529. @router.get("/price-versions", response_model=dict)
  6530. def list_price_versions(
  6531. page: int = Query(1, ge=1, description="页码"),
  6532. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  6533. regionId: Optional[str] = Query(None, description="区域ID"),
  6534. supplierId: Optional[str] = Query(None, description="供应商ID"),
  6535. status: Optional[str] = Query(None, description="状态"),
  6536. db: Session = Depends(get_db),
  6537. current_user: dict = Depends(require_admin)
  6538. ):
  6539. """获取价格版本列表"""
  6540. from app.models.models import BizPriceList
  6541. from sqlalchemy import or_
  6542. query = db.query(BizPriceList).filter(BizPriceList.is_del == 0)
  6543. if regionId:
  6544. query = query.filter(BizPriceList.region_id == regionId)
  6545. if supplierId:
  6546. query = query.filter(BizPriceList.supplier_id == supplierId)
  6547. if status:
  6548. query = query.filter(BizPriceList.status == status)
  6549. total = query.count()
  6550. versions = query.order_by(BizPriceList.create_at.desc()).offset((page - 1) * pageSize).limit(pageSize).all()
  6551. result = []
  6552. for v in versions:
  6553. region_name = None
  6554. if v.region_id:
  6555. region = region_crud.get(db, v.region_id)
  6556. region_name = region.name if region else None
  6557. supplier_name = None
  6558. if v.supplier_id:
  6559. supplier = user_crud.get(db, v.supplier_id)
  6560. supplier_name = supplier.real_name if supplier else None
  6561. result.append({
  6562. "id": v.id,
  6563. "versionNo": getattr(v, "version_no", None) or getattr(v, "version", None),
  6564. "regionId": v.region_id,
  6565. "regionName": region_name,
  6566. "supplierId": v.supplier_id,
  6567. "supplierName": supplier_name,
  6568. "status": v.status,
  6569. "effectiveTime": str(v.effective_time) if v.effective_time else None,
  6570. "remark": v.remark,
  6571. "createAt": str(v.create_at) if v.create_at else None
  6572. })
  6573. return success_response({
  6574. "list": result,
  6575. "total": total,
  6576. "page": page,
  6577. "pageSize": pageSize,
  6578. "totalPages": (total + pageSize - 1) // pageSize
  6579. })
  6580. @router.get("/price-versions/{version_id}", response_model=dict)
  6581. def get_price_version_detail(
  6582. version_id: str,
  6583. db: Session = Depends(get_db),
  6584. current_user: dict = Depends(require_admin)
  6585. ):
  6586. """获取价格版本详情(含供应商报价与最终售价拆解,便于订单侧只读查看)。"""
  6587. from app.models.models import BizPriceList, BizPriceListItem, BizQuotationItem
  6588. from app.crud.inquiry import inquiry_crud
  6589. version = db.query(BizPriceList).filter(BizPriceList.id == version_id, BizPriceList.is_del == 0).first()
  6590. if not version:
  6591. return error_response(404, "价格清单不存在")
  6592. region_name = None
  6593. if version.region_id:
  6594. region = region_crud.get(db, version.region_id)
  6595. region_name = region.name if region else None
  6596. supplier_name = None
  6597. if version.supplier_id:
  6598. supplier = user_crud.get(db, version.supplier_id)
  6599. supplier_name = supplier.real_name if supplier else None
  6600. inquiry_title = None
  6601. if version.inquiry_id:
  6602. iq = inquiry_crud.get(db, version.inquiry_id)
  6603. inquiry_title = iq.title if iq else None
  6604. # 来源报价单:用于还原供应商侧单价
  6605. q_item_by_pid: dict[str, object] = {}
  6606. if version.quotation_id:
  6607. q_rows = db.query(BizQuotationItem).filter(
  6608. and_(
  6609. BizQuotationItem.quotation_id == version.quotation_id,
  6610. BizQuotationItem.is_del == 0
  6611. )
  6612. ).all()
  6613. for qi in q_rows:
  6614. pid = str(getattr(qi, "product_id", "") or "")
  6615. if pid and pid not in q_item_by_pid:
  6616. q_item_by_pid[pid] = qi
  6617. # 获取版本明细
  6618. items = db.query(BizPriceListItem).filter(
  6619. BizPriceListItem.price_list_id == version_id,
  6620. BizPriceListItem.is_del == 0
  6621. ).all()
  6622. item_details = []
  6623. for item in items:
  6624. product = product_crud.get(db, item.product_id)
  6625. unit_name = None
  6626. if item.unit_id:
  6627. u = unit_crud.get(db, item.unit_id)
  6628. unit_name = u.name if u else None
  6629. pid = str(item.product_id or "")
  6630. q_item = q_item_by_pid.get(pid)
  6631. supplier_price = float(getattr(q_item, "price", 0) or 0) if q_item else 0.0
  6632. coeff = None
  6633. if getattr(item, "pricing_coefficient", None) is not None:
  6634. coeff = float(item.pricing_coefficient)
  6635. elif product and getattr(product, "price_coefficient", None) is not None:
  6636. coeff = float(product.price_coefficient)
  6637. else:
  6638. coeff = 0.0
  6639. final_price = float(item.price) if item.price else 0.0
  6640. category_id = getattr(product, "category_id", None) if product else None
  6641. category_path = _category_path_display(db, str(category_id)) if category_id else ""
  6642. item_details.append({
  6643. "id": item.id,
  6644. "productId": item.product_id,
  6645. "productName": product.name if product else None,
  6646. "imageUrl": getattr(product, "image_url", None) if product else None,
  6647. "categoryId": str(category_id) if category_id else None,
  6648. "categoryName": category_path or None,
  6649. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)) if product else None,
  6650. "unitId": item.unit_id,
  6651. "unitName": unit_name,
  6652. "supplierPrice": supplier_price,
  6653. "pricingCoefficient": coeff,
  6654. "finalPrice": final_price,
  6655. "price": final_price
  6656. })
  6657. return success_response({
  6658. "id": version.id,
  6659. "versionNo": getattr(version, "version_no", None) or getattr(version, "version", None),
  6660. "version": getattr(version, "version", None),
  6661. "regionId": version.region_id,
  6662. "regionName": region_name,
  6663. "supplierId": version.supplier_id,
  6664. "supplierName": supplier_name,
  6665. "inquiryId": version.inquiry_id,
  6666. "inquiryTitle": inquiry_title,
  6667. "quotationId": version.quotation_id,
  6668. "status": version.status,
  6669. "effectiveTime": str(version.effective_time) if version.effective_time else None,
  6670. "remark": version.remark,
  6671. "createAt": str(version.create_at) if version.create_at else None,
  6672. "items": item_details
  6673. })
  6674. @router.post("/price-versions", response_model=dict)
  6675. def create_price_version(
  6676. request: dict,
  6677. db: Session = Depends(get_db),
  6678. current_user: dict = Depends(require_admin)
  6679. ):
  6680. """创建价格版本"""
  6681. from app.models.models import BizPriceList
  6682. from app.core.utils import generate_uuid
  6683. region_id = request.get("regionId")
  6684. supplier_id = request.get("supplierId")
  6685. effective_time = request.get("effectiveTime")
  6686. remark = request.get("remark")
  6687. if not region_id or not supplier_id:
  6688. return error_response(400, "区域ID和供应商ID不能为空")
  6689. # 生成版本号
  6690. today = datetime.now().strftime("%Y%m%d")
  6691. count = db.query(BizPriceList).filter(
  6692. BizPriceList.region_id == region_id,
  6693. BizPriceList.supplier_id == supplier_id
  6694. ).count()
  6695. version_no = f"PL{today}{count + 1:04d}"
  6696. # 解析生效时间
  6697. effective_dt = None
  6698. if effective_time:
  6699. try:
  6700. effective_dt = datetime.strptime(effective_time, "%Y-%m-%d %H:%M:%S")
  6701. except:
  6702. try:
  6703. effective_dt = datetime.strptime(effective_time, "%Y-%m-%d")
  6704. except:
  6705. pass
  6706. new_version = BizPriceList(
  6707. id=generate_uuid(),
  6708. region_id=region_id,
  6709. supplier_id=supplier_id,
  6710. version_no=version_no,
  6711. status="draft",
  6712. effective_time=effective_dt,
  6713. remark=remark,
  6714. create_at=datetime.now(),
  6715. create_by=current_user.get("user_id"),
  6716. create_name=current_user.get("real_name"),
  6717. is_del=0
  6718. )
  6719. db.add(new_version)
  6720. db.commit()
  6721. return success_response({
  6722. "id": new_version.id,
  6723. "versionNo": version_no,
  6724. "message": "价格版本创建成功"
  6725. })
  6726. @router.post("/price-versions/{version_id}/publish", response_model=dict)
  6727. def publish_price_version(
  6728. version_id: str,
  6729. db: Session = Depends(get_db),
  6730. current_user: dict = Depends(require_admin)
  6731. ):
  6732. """发布价格版本"""
  6733. from app.models.models import BizPriceList
  6734. version = db.query(BizPriceList).filter(BizPriceList.id == version_id, BizPriceList.is_del == 0).first()
  6735. if not version:
  6736. return error_response(404, "价格版本不存在")
  6737. if version.status != "draft":
  6738. return error_response(400, "只有草稿状态的价格版本才能发布")
  6739. version.status = "published"
  6740. version.publish_time = datetime.now()
  6741. version.publisher_id = current_user.get("user_id")
  6742. db.commit()
  6743. return success_response({
  6744. "id": version.id,
  6745. "status": version.status,
  6746. "message": "价格版本发布成功"
  6747. })
  6748. @router.post("/price-versions/{version_id}/disable", response_model=dict)
  6749. def disable_price_version(
  6750. version_id: str,
  6751. db: Session = Depends(get_db),
  6752. current_user: dict = Depends(require_admin)
  6753. ):
  6754. """禁用价格版本"""
  6755. from app.models.models import BizPriceList
  6756. version = db.query(BizPriceList).filter(BizPriceList.id == version_id, BizPriceList.is_del == 0).first()
  6757. if not version:
  6758. return error_response(404, "价格版本不存在")
  6759. if version.status == "invalid":
  6760. return error_response(400, "该价格版本已经失效")
  6761. version.status = "invalid"
  6762. version.invalidate_time = datetime.now()
  6763. version.invalidate_operator_id = current_user.get("user_id")
  6764. db.commit()
  6765. return success_response({
  6766. "id": version.id,
  6767. "status": version.status,
  6768. "message": "价格版本已禁用"
  6769. })
  6770. @router.get("/price-versions/compare", response_model=dict)
  6771. def compare_price_versions(
  6772. versionIds: str = Query(..., description="版本ID列表,逗号分隔"),
  6773. db: Session = Depends(get_db),
  6774. current_user: dict = Depends(require_admin)
  6775. ):
  6776. """版本价格对比"""
  6777. from app.models.models import BizPriceList, BizPriceListItem
  6778. version_id_list = [v.strip() for v in versionIds.split(",") if v.strip()]
  6779. if len(version_id_list) < 2:
  6780. return error_response(400, "至少需要选择两个版本进行对比")
  6781. versions = db.query(BizPriceList).filter(
  6782. BizPriceList.id.in_(version_id_list),
  6783. BizPriceList.is_del == 0
  6784. ).all()
  6785. if len(versions) < 2:
  6786. return error_response(400, "选择的版本中有不存在的")
  6787. # 获取所有版本的价格明细
  6788. version_items = {}
  6789. all_products = set()
  6790. for version in versions:
  6791. items = db.query(BizPriceListItem).filter(
  6792. BizPriceListItem.price_list_id == version.id,
  6793. BizPriceListItem.is_del == 0
  6794. ).all()
  6795. version_items[version.id] = {item.product_id: float(item.price) if item.price else 0 for item in items}
  6796. all_products.update([item.product_id for item in items])
  6797. # 构建对比数据
  6798. compare_data = []
  6799. for product_id in all_products:
  6800. product = product_crud.get(db, product_id)
  6801. if not product:
  6802. continue
  6803. row = {
  6804. "productId": product_id,
  6805. "productName": product.name,
  6806. "prices": {}
  6807. }
  6808. for version in versions:
  6809. row["prices"][version.id] = version_items.get(version.id, {}).get(product_id, None)
  6810. if row["prices"][version.id] is not None:
  6811. if not hasattr(row, "lowestPrice") or row["lowestPrice"] > row["prices"][version.id]:
  6812. row["lowestPrice"] = row["prices"][version.id]
  6813. row["lowestVersionId"] = version.id
  6814. compare_data.append(row)
  6815. # 版本基本信息
  6816. version_info = [{
  6817. "id": v.id,
  6818. "versionNo": v.version_no,
  6819. "status": v.status
  6820. } for v in versions]
  6821. return success_response({
  6822. "versions": version_info,
  6823. "products": compare_data
  6824. })