admin.py 283 KB

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