admin.py 282 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709
  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. "items": item_details
  1921. })
  1922. supplier = user_crud.get(db, q.supplier_id) if q.supplier_id else None
  1923. # 兜底分支也补齐询价单商品行:supplierPrice 从报价项拿,最终售价未知则为 0
  1924. supplier_price_map: dict[str, float] = {}
  1925. q_items = db.query(BizQuotationItem).filter(
  1926. and_(BizQuotationItem.quotation_id == q.id, BizQuotationItem.is_del == 0)
  1927. ).all()
  1928. for qi in q_items:
  1929. if not qi.product_id:
  1930. continue
  1931. supplier_price_map[str(qi.product_id)] = float(qi.price) if qi.price else 0
  1932. item_details = []
  1933. for inq_item in inquiry_items:
  1934. pid = str(getattr(inq_item, "product_id", "") or "")
  1935. product = product_crud.get(db, pid) if pid else None
  1936. default_coeff = _numeric_to_float_optional(getattr(product, "price_coefficient", None)) if product else None
  1937. default_coeff = float(default_coeff) if default_coeff is not None else 0.0
  1938. category_name = None
  1939. if product and getattr(product, "category_id", None):
  1940. cat = category_crud.get(db, product.category_id)
  1941. category_name = cat.name if cat else None
  1942. unit_id = getattr(product, "unit_id", None) if product else None
  1943. unit_name = None
  1944. if unit_id:
  1945. u = unit_crud.get(db, unit_id)
  1946. unit_name = u.name if u else None
  1947. item_details.append({
  1948. "productId": pid,
  1949. "productName": product.name if product else None,
  1950. "skuCode": getattr(product, "sku_code", None) if product else None,
  1951. "description": getattr(product, "description", None) if product else None,
  1952. "imageUrl": getattr(product, "image_url", None) if product else None,
  1953. "categoryName": category_name,
  1954. "unitId": unit_id,
  1955. "unitName": unit_name,
  1956. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)) if product else None,
  1957. # 未报价商品返回 0(兜底分支无法区分 null/0;主流程会更准确)
  1958. "supplierPrice": supplier_price_map.get(pid, 0),
  1959. "price": 0,
  1960. "pricingCoefficient": default_coeff
  1961. })
  1962. return success_response({
  1963. "quotationId": q.id,
  1964. "quotationCreateAt": str(q.create_at) if getattr(q, "create_at", None) else None,
  1965. "quotationSubmitTime": str(q.submit_time) if getattr(q, "submit_time", None) else None,
  1966. "supplierId": q.supplier_id,
  1967. "supplierName": supplier.real_name if supplier else None,
  1968. "items": item_details
  1969. })
  1970. supplier = user_crud.get(db, pl.supplier_id) if pl.supplier_id else None
  1971. quotation_create_at = None
  1972. quotation_submit_time = None
  1973. if pl.quotation_id:
  1974. q = db.query(BizQuotation).filter(
  1975. and_(
  1976. BizQuotation.id == pl.quotation_id,
  1977. BizQuotation.is_del == 0
  1978. )
  1979. ).first()
  1980. if q:
  1981. quotation_create_at = str(q.create_at) if getattr(q, "create_at", None) else None
  1982. quotation_submit_time = str(q.submit_time) if getattr(q, "submit_time", None) else None
  1983. items = db.query(BizPriceListItem).filter(
  1984. and_(BizPriceListItem.price_list_id == pl.id, BizPriceListItem.is_del == 0)
  1985. ).all()
  1986. # price list item 按 product_id 映射(LEFT JOIN)
  1987. pl_item_by_pid: dict[str, object] = {}
  1988. for it in items:
  1989. pid = str(getattr(it, "product_id", "") or "")
  1990. if pid and pid not in pl_item_by_pid:
  1991. pl_item_by_pid[pid] = it
  1992. supplier_price_map: dict[str, float] = {}
  1993. if pl.quotation_id:
  1994. q_items = db.query(BizQuotationItem).filter(
  1995. and_(BizQuotationItem.quotation_id == pl.quotation_id, BizQuotationItem.is_del == 0)
  1996. ).all()
  1997. for qi in q_items:
  1998. if not qi.product_id:
  1999. continue
  2000. supplier_price_map[str(qi.product_id)] = float(qi.price) if qi.price else 0
  2001. item_details = []
  2002. for inq_item in inquiry_items:
  2003. pid = str(getattr(inq_item, "product_id", "") or "")
  2004. it = pl_item_by_pid.get(pid)
  2005. product = product_crud.get(db, pid) if pid else None
  2006. default_coeff = _numeric_to_float_optional(getattr(product, "price_coefficient", None)) if product else None
  2007. default_coeff = float(default_coeff) if default_coeff is not None else 0.0
  2008. category_name = None
  2009. if product and getattr(product, "category_id", None):
  2010. cat = category_crud.get(db, product.category_id)
  2011. category_name = cat.name if cat else None
  2012. unit_id = None
  2013. unit_name = None
  2014. if it and getattr(it, "unit_id", None):
  2015. unit_id = getattr(it, "unit_id", None)
  2016. elif product and getattr(product, "unit_id", None):
  2017. unit_id = getattr(product, "unit_id", None)
  2018. if unit_id:
  2019. u = unit_crud.get(db, unit_id)
  2020. unit_name = u.name if u else None
  2021. item_details.append({
  2022. "productId": pid,
  2023. "productName": product.name if product else None,
  2024. "skuCode": getattr(product, "sku_code", None) if product else None,
  2025. "description": getattr(product, "description", None) if product else None,
  2026. "imageUrl": getattr(product, "image_url", None) if product else None,
  2027. "categoryName": category_name,
  2028. "unitId": unit_id,
  2029. "unitName": unit_name,
  2030. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)) if product else None,
  2031. "supplierPrice": supplier_price_map.get(pid, 0),
  2032. # 最终售价来自 price list item;未生成/不存在时返回 0
  2033. "price": float(getattr(it, "price", 0) or 0) if it else 0,
  2034. "pricingCoefficient": float(getattr(it, "pricing_coefficient", 0)) if (it and getattr(it, "pricing_coefficient", None) is not None) else default_coeff
  2035. })
  2036. return success_response({
  2037. "priceListId": pl.id,
  2038. "priceVersion": pl.version,
  2039. "quotationId": pl.quotation_id,
  2040. "quotationCreateAt": quotation_create_at,
  2041. "quotationSubmitTime": quotation_submit_time,
  2042. "supplierId": pl.supplier_id,
  2043. "supplierName": supplier.real_name if supplier else None,
  2044. "items": item_details
  2045. })
  2046. @router.get("/quotation-compare", response_model=dict)
  2047. def compare_quotations(
  2048. inquiryId: str = Query(..., description="询价单ID"),
  2049. supplierIds: str = Query(..., description="供应商ID,逗号分隔"),
  2050. db: Session = Depends(get_db),
  2051. current_user: dict = Depends(require_admin)
  2052. ):
  2053. """报价对比(按询价单+供应商)"""
  2054. from app.crud.quotation import quotation_crud, quotation_item_crud
  2055. supplier_id_list = [x.strip() for x in supplierIds.split(",") if x.strip()]
  2056. if len(supplier_id_list) < 2:
  2057. return error_response(400, "至少选择两个供应商")
  2058. quotations, _ = quotation_crud.get_multi_with_filters(
  2059. db,
  2060. inquiry_id=inquiryId,
  2061. skip=0,
  2062. limit=500
  2063. )
  2064. quotations = [q for q in quotations if q.supplier_id in supplier_id_list]
  2065. if not quotations:
  2066. return success_response([])
  2067. # 汇总每个商品在不同供应商下的价格
  2068. compare_map = {}
  2069. for q in quotations:
  2070. items = quotation_item_crud.get_by_quotation(db, q.id)
  2071. for item in items:
  2072. product = product_crud.get(db, item.product_id)
  2073. unit_name = None
  2074. if item.unit_id:
  2075. u = unit_crud.get(db, item.unit_id)
  2076. unit_name = u.name if u else None
  2077. key = f"{item.product_id}:{item.unit_id or ''}"
  2078. row = compare_map.get(key)
  2079. if not row:
  2080. row = {
  2081. "productId": item.product_id,
  2082. "productName": product.name if product else item.product_id,
  2083. "unitId": item.unit_id,
  2084. "unitName": unit_name,
  2085. "prices": {},
  2086. "lowestPrice": None,
  2087. "highestPrice": None
  2088. }
  2089. compare_map[key] = row
  2090. price_value = float(item.price) if item.price is not None else 0
  2091. row["prices"][q.supplier_id] = price_value
  2092. result = []
  2093. for _, row in compare_map.items():
  2094. price_values = [v for v in row["prices"].values() if v is not None]
  2095. if price_values:
  2096. row["lowestPrice"] = min(price_values)
  2097. row["highestPrice"] = max(price_values)
  2098. else:
  2099. row["lowestPrice"] = 0
  2100. row["highestPrice"] = 0
  2101. result.append(row)
  2102. result.sort(key=lambda x: (x.get("productName") or "", x.get("unitName") or ""))
  2103. return success_response(result)
  2104. @router.post("/quotations/{quotation_id}/approve", response_model=dict)
  2105. def approve_quotation(
  2106. quotation_id: str,
  2107. request: dict,
  2108. db: Session = Depends(get_db),
  2109. current_user: dict = Depends(require_admin)
  2110. ):
  2111. """报价无需审核(接口已停用)"""
  2112. return error_response(410, "报价无需审核:请在“询价报价管理-最新报价对比”中直接选中供应商生效价格")
  2113. @router.post("/quotations/{quotation_id}/reject", response_model=dict)
  2114. def reject_quotation(
  2115. quotation_id: str,
  2116. request: dict,
  2117. db: Session = Depends(get_db),
  2118. current_user: dict = Depends(require_admin)
  2119. ):
  2120. """报价无需审核(接口已停用)"""
  2121. return error_response(410, "报价无需审核:请在“询价报价管理-最新报价对比”中直接选中供应商生效价格")
  2122. # =========================================
  2123. # 价格清单管理 API (Web端)
  2124. # =========================================
  2125. @router.get("/price-lists", response_model=dict)
  2126. def list_price_lists(
  2127. page: int = Query(1, ge=1, description="页码"),
  2128. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  2129. regionId: Optional[str] = Query(None, description="区域ID"),
  2130. status: Optional[str] = Query(None, description="状态: draft/pending/active/expired"),
  2131. db: Session = Depends(get_db),
  2132. current_user: dict = Depends(require_admin)
  2133. ):
  2134. """获取价格清单列表"""
  2135. from app.crud.price_list import price_list_crud
  2136. from app.crud.user import user_crud
  2137. # 区域管理员只能查看自己区域的价格清单
  2138. admin_region_id = get_admin_region_filter(db, current_user)
  2139. if admin_region_id and not regionId:
  2140. regionId = admin_region_id
  2141. elif admin_region_id and regionId != admin_region_id:
  2142. return success_response({
  2143. "list": [],
  2144. "total": 0,
  2145. "page": page,
  2146. "pageSize": pageSize,
  2147. "totalPages": 0
  2148. })
  2149. price_lists, total = price_list_crud.get_multi_with_filters(
  2150. db,
  2151. region_id=regionId,
  2152. status=status,
  2153. skip=(page - 1) * pageSize,
  2154. limit=pageSize
  2155. )
  2156. region_map = {}
  2157. supplier_map = {}
  2158. publisher_map = {}
  2159. for pl in price_lists:
  2160. if pl.region_id and pl.region_id not in region_map:
  2161. region = region_crud.get(db, pl.region_id)
  2162. region_map[pl.region_id] = region.name if region else None
  2163. if pl.supplier_id and pl.supplier_id not in supplier_map:
  2164. supplier = user_crud.get(db, pl.supplier_id)
  2165. supplier_map[pl.supplier_id] = supplier.real_name if supplier else None
  2166. if pl.published_by and pl.published_by not in publisher_map:
  2167. publisher = user_crud.get(db, pl.published_by)
  2168. publisher_map[pl.published_by] = publisher.real_name if publisher else None
  2169. return success_response({
  2170. "list": [{
  2171. "id": pl.id,
  2172. "regionId": pl.region_id,
  2173. "regionName": region_map.get(pl.region_id),
  2174. "supplierId": pl.supplier_id,
  2175. "supplierName": supplier_map.get(pl.supplier_id),
  2176. "version": pl.version,
  2177. "status": pl.status,
  2178. "effectiveTime": str(pl.effective_time) if pl.effective_time else None,
  2179. "publishedBy": pl.published_by,
  2180. "publishedByName": publisher_map.get(pl.published_by),
  2181. "publishedTime": str(pl.published_time) if pl.published_time else None,
  2182. "remark": pl.remark,
  2183. "createAt": str(pl.create_at) if pl.create_at else None
  2184. } for pl in price_lists],
  2185. "total": total,
  2186. "page": page,
  2187. "pageSize": pageSize,
  2188. "totalPages": (total + pageSize - 1) // pageSize
  2189. })
  2190. @router.post("/price-lists", response_model=dict)
  2191. def create_price_list(
  2192. request: dict,
  2193. db: Session = Depends(get_db),
  2194. current_user: dict = Depends(require_admin)
  2195. ):
  2196. """创建价格清单"""
  2197. from app.crud.price_list import price_list_crud
  2198. from datetime import datetime
  2199. region_id = request.get("regionId")
  2200. supplier_id = request.get("supplierId")
  2201. items = request.get("items", [])
  2202. effective_type = request.get("effectiveType", "immediate")
  2203. effective_time_str = request.get("effectiveTime")
  2204. remark = request.get("remark")
  2205. if not region_id:
  2206. return error_response(400, "请选择区域")
  2207. if not supplier_id:
  2208. return error_response(400, "请选择供应商")
  2209. if not items:
  2210. return error_response(400, "请添加价格项")
  2211. effective_time = None
  2212. if effective_time_str:
  2213. try:
  2214. effective_time = datetime.fromisoformat(effective_time_str.replace("Z", "+00:00"))
  2215. except:
  2216. effective_time = None
  2217. creator = {
  2218. "user_id": current_user.get("user_id"),
  2219. "real_name": current_user.get("real_name")
  2220. }
  2221. price_list = price_list_crud.create_with_items(
  2222. db,
  2223. obj_in={
  2224. "region_id": region_id,
  2225. "supplier_id": supplier_id,
  2226. "effective_time": effective_time,
  2227. "remark": remark
  2228. },
  2229. items=items,
  2230. creator=creator
  2231. )
  2232. # 如果是立即生效,直接发布
  2233. if effective_type == "immediate":
  2234. price_list_crud.publish(
  2235. db,
  2236. price_list.id,
  2237. current_user.get("user_id"),
  2238. effective_type="immediate"
  2239. )
  2240. return success_response({
  2241. "id": price_list.id,
  2242. "message": "创建成功"
  2243. })
  2244. @router.get("/price-lists/{price_list_id}", response_model=dict)
  2245. def get_price_list(
  2246. price_list_id: str,
  2247. db: Session = Depends(get_db),
  2248. current_user: dict = Depends(require_admin)
  2249. ):
  2250. """获取价格清单详情"""
  2251. from app.crud.price_list import price_list_crud, price_list_item_crud
  2252. from app.crud.user import user_crud
  2253. price_list = price_list_crud.get(db, price_list_id)
  2254. if not price_list:
  2255. return error_response(404, "价格清单不存在")
  2256. items = price_list_item_crud.get_by_price_list(db, price_list_id)
  2257. # 获取关联信息
  2258. region_name = None
  2259. if price_list.region_id:
  2260. region = region_crud.get(db, price_list.region_id)
  2261. region_name = region.name if region else None
  2262. supplier_name = None
  2263. if price_list.supplier_id:
  2264. supplier = user_crud.get(db, price_list.supplier_id)
  2265. supplier_name = supplier.real_name if supplier else None
  2266. publisher_name = None
  2267. if price_list.published_by:
  2268. publisher = user_crud.get(db, price_list.published_by)
  2269. publisher_name = publisher.real_name if publisher else None
  2270. # 订单关联供应商(来自订单价格清单)
  2271. from app.crud.price_list import price_list_crud
  2272. price_list = price_list_crud.get(db, order.price_list_id) if order.price_list_id else None
  2273. supplier_id_from_price_list = getattr(price_list, "supplier_id", None) if price_list else None
  2274. supplier_name_from_price_list = None
  2275. if supplier_id_from_price_list:
  2276. _sup_u = user_crud.get(db, supplier_id_from_price_list)
  2277. if _sup_u:
  2278. supplier_name_from_price_list = _sup_u.real_name or _sup_u.username
  2279. pl_ids_for_order = [order.price_list_id] if order.price_list_id else []
  2280. pli_map_for_order = _price_list_item_map(db, pl_ids_for_order)
  2281. # 获取商品和单位信息
  2282. item_details = []
  2283. supplier_total_amount = 0.0
  2284. selling_total_amount = 0.0
  2285. for item in items:
  2286. product = product_crud.get(db, item.product_id)
  2287. category_name = None
  2288. if product and product.category_id:
  2289. cat = category_crud.get(db, product.category_id)
  2290. category_name = cat.name if cat else None
  2291. unit_name = None
  2292. if item.unit_id:
  2293. u = unit_crud.get(db, item.unit_id)
  2294. unit_name = u.name if u else None
  2295. qty = float(item.quantity) if item.quantity else 0
  2296. selling_u = float(item.unit_price) if item.unit_price else 0
  2297. selling_amt = float(item.amount) if item.amount else round(qty * selling_u, 2)
  2298. pli = pli_map_for_order.get((order.price_list_id, item.product_id, item.unit_id))
  2299. supplier_u = _supplier_unit_yuan_from_pli(pli)
  2300. if supplier_u is None:
  2301. supplier_u = selling_u
  2302. supplier_amt = round(qty * supplier_u, 2)
  2303. supplier_total_amount += supplier_amt
  2304. selling_total_amount += selling_amt
  2305. item_details.append({
  2306. "id": item.id,
  2307. "productId": item.product_id,
  2308. "productName": product.name if product else None,
  2309. "categoryName": category_name,
  2310. "unitId": item.unit_id,
  2311. "unitName": unit_name,
  2312. "price": float(item.price) if item.price else 0,
  2313. "imageUrl": product.image_url if product else None
  2314. })
  2315. return success_response({
  2316. "id": price_list.id,
  2317. "regionId": price_list.region_id,
  2318. "regionName": region_name,
  2319. "supplierId": price_list.supplier_id,
  2320. "supplierName": supplier_name,
  2321. "version": price_list.version,
  2322. "status": price_list.status,
  2323. "effectiveTime": str(price_list.effective_time) if price_list.effective_time else None,
  2324. "publishedBy": price_list.published_by,
  2325. "publishedByName": publisher_name,
  2326. "publishedTime": str(price_list.published_time) if price_list.published_time else None,
  2327. "remark": price_list.remark,
  2328. "createAt": str(price_list.create_at) if price_list.create_at else None,
  2329. "items": item_details
  2330. })
  2331. @router.put("/price-lists/{price_list_id}", response_model=dict)
  2332. def update_price_list(
  2333. price_list_id: str,
  2334. request: dict,
  2335. db: Session = Depends(get_db),
  2336. current_user: dict = Depends(require_admin)
  2337. ):
  2338. """更新价格清单(只有草稿状态可编辑)"""
  2339. from app.crud.price_list import price_list_crud
  2340. from datetime import datetime
  2341. price_list = price_list_crud.get(db, price_list_id)
  2342. if not price_list:
  2343. return error_response(404, "价格清单不存在")
  2344. if price_list.status != "draft":
  2345. return error_response(400, "只有草稿状态的价格清单可以编辑")
  2346. items = request.get("items")
  2347. effective_time_str = request.get("effectiveTime")
  2348. remark = request.get("remark")
  2349. obj_in = {}
  2350. if effective_time_str:
  2351. try:
  2352. obj_in["effective_time"] = datetime.fromisoformat(effective_time_str.replace("Z", "+00:00"))
  2353. except:
  2354. pass
  2355. if remark is not None:
  2356. obj_in["remark"] = remark
  2357. updater = {
  2358. "user_id": current_user.get("user_id"),
  2359. "real_name": current_user.get("real_name")
  2360. }
  2361. price_list_crud.update_with_items(
  2362. db,
  2363. price_list_id,
  2364. obj_in,
  2365. items=items,
  2366. updater=updater
  2367. )
  2368. return success_response({
  2369. "id": price_list_id,
  2370. "message": "更新成功"
  2371. })
  2372. @router.post("/price-lists/{price_list_id}/publish", response_model=dict)
  2373. def publish_price_list(
  2374. price_list_id: str,
  2375. request: dict,
  2376. db: Session = Depends(get_db),
  2377. current_user: dict = Depends(require_admin)
  2378. ):
  2379. """发布价格清单"""
  2380. from app.crud.price_list import price_list_crud
  2381. from datetime import datetime
  2382. price_list = price_list_crud.get(db, price_list_id)
  2383. if not price_list:
  2384. return error_response(404, "价格清单不存在")
  2385. if price_list.status != "draft":
  2386. return error_response(400, "只有草稿状态的价格清单可以发布")
  2387. effective_type = request.get("effectiveType", "immediate")
  2388. effective_time_str = request.get("effectiveTime")
  2389. effective_time = None
  2390. if effective_time_str:
  2391. try:
  2392. effective_time = datetime.fromisoformat(effective_time_str.replace("Z", "+00:00"))
  2393. except:
  2394. pass
  2395. price_list_crud.publish(
  2396. db,
  2397. price_list_id,
  2398. current_user.get("user_id"),
  2399. effective_time=effective_time,
  2400. effective_type=effective_type
  2401. )
  2402. return success_response({
  2403. "id": price_list_id,
  2404. "message": "发布成功"
  2405. })
  2406. @router.post("/price-lists/{price_list_id}/invalidate", response_model=dict)
  2407. def invalidate_price_list(
  2408. price_list_id: str,
  2409. db: Session = Depends(get_db),
  2410. current_user: dict = Depends(require_admin)
  2411. ):
  2412. """使价格清单失效"""
  2413. from app.crud.price_list import price_list_crud
  2414. price_list = price_list_crud.get(db, price_list_id)
  2415. if not price_list:
  2416. return error_response(404, "价格清单不存在")
  2417. if price_list.status not in ["active", "pending"]:
  2418. return error_response(400, "只有生效中或待生效的价格清单可以失效")
  2419. price_list_crud.invalidate(db, price_list_id)
  2420. return success_response({
  2421. "id": price_list_id,
  2422. "message": "操作成功"
  2423. })
  2424. @router.delete("/price-lists/{price_list_id}", response_model=dict)
  2425. def delete_price_list(
  2426. price_list_id: str,
  2427. db: Session = Depends(get_db),
  2428. current_user: dict = Depends(require_admin)
  2429. ):
  2430. """删除价格清单(只有草稿状态可删除)"""
  2431. from app.crud.price_list import price_list_crud
  2432. price_list = price_list_crud.get(db, price_list_id)
  2433. if not price_list:
  2434. return error_response(404, "价格清单不存在")
  2435. if price_list.status != "draft":
  2436. return error_response(400, "只有草稿状态的价格清单可以删除")
  2437. price_list_crud.delete(db, price_list_id)
  2438. return success_response({
  2439. "message": "删除成功"
  2440. })
  2441. @router.get("/price-lists/product-history", response_model=dict)
  2442. def get_product_price_history(
  2443. regionId: str = Query(..., description="区域ID"),
  2444. productId: str = Query(..., description="商品ID"),
  2445. page: int = Query(1, ge=1, description="页码"),
  2446. pageSize: int = Query(20, ge=1, le=100, description="每页条数"),
  2447. db: Session = Depends(get_db),
  2448. current_user: dict = Depends(require_admin)
  2449. ):
  2450. """按商品维度查询价格历史"""
  2451. from app.crud.price_list import price_list_crud, price_list_item_crud
  2452. product = product_crud.get(db, productId)
  2453. if not product:
  2454. return error_response(404, "商品不存在")
  2455. items, total = price_list_item_crud.get_product_price_history(
  2456. db,
  2457. region_id=regionId,
  2458. product_id=productId,
  2459. skip=(page - 1) * pageSize,
  2460. limit=pageSize
  2461. )
  2462. # 获取单位信息
  2463. for item in items:
  2464. if item.get("unit_id"):
  2465. u = unit_crud.get(db, item["unit_id"])
  2466. item["unitName"] = u.name if u else None
  2467. return success_response({
  2468. "productId": productId,
  2469. "productName": product.name,
  2470. "history": items,
  2471. "total": total,
  2472. "page": page,
  2473. "pageSize": pageSize
  2474. })
  2475. @router.get("/price-lists/generate-options", response_model=dict)
  2476. def get_generate_price_list_options(
  2477. regionId: str = Query(..., description="区域ID"),
  2478. db: Session = Depends(get_db),
  2479. current_user: dict = Depends(require_admin)
  2480. ):
  2481. """获取生成价格清单的选项(该区域已提交、尚未被选中的报价单,报价无审核流程)"""
  2482. from app.crud.quotation import quotation_crud, quotation_item_crud
  2483. from app.crud.user import user_crud
  2484. quotations, total = quotation_crud.get_multi_with_filters(
  2485. db,
  2486. region_id=regionId,
  2487. status="submitted",
  2488. skip=0,
  2489. limit=100
  2490. )
  2491. result = []
  2492. for q in quotations:
  2493. supplier = user_crud.get(db, q.supplier_id)
  2494. items = quotation_item_crud.get_by_quotation(db, q.id)
  2495. item_details = []
  2496. for item in items:
  2497. product = product_crud.get(db, item.product_id)
  2498. unit_name = None
  2499. if item.unit_id:
  2500. u = unit_crud.get(db, item.unit_id)
  2501. unit_name = u.name if u else None
  2502. item_details.append({
  2503. "productId": item.product_id,
  2504. "productName": product.name if product else None,
  2505. "unitId": item.unit_id,
  2506. "unitName": unit_name,
  2507. "price": float(item.price) if item.price else 0
  2508. })
  2509. result.append({
  2510. "quotationId": q.id,
  2511. "quotationNo": f"QT{q.create_at.strftime('%Y%m%d%H%M%S') if q.create_at else ''}",
  2512. "supplierId": q.supplier_id,
  2513. "supplierName": supplier.real_name if supplier else None,
  2514. "totalAmount": float(q.total_amount) if q.total_amount else 0,
  2515. "items": item_details
  2516. })
  2517. return success_response({
  2518. "list": result,
  2519. "total": len(result)
  2520. })
  2521. @router.get("/price-lists/compare", response_model=dict)
  2522. def compare_price_list_versions(
  2523. regionId: str = Query(..., description="区域ID"),
  2524. version1Id: str = Query(..., description="版本1ID"),
  2525. version2Id: str = Query(..., description="版本2ID"),
  2526. db: Session = Depends(get_db),
  2527. current_user: dict = Depends(require_admin)
  2528. ):
  2529. """对比两个价格版本"""
  2530. from app.crud.price_list import price_list_crud, price_list_item_crud
  2531. # 获取两个版本的价格清单
  2532. price_list1 = price_list_crud.get(db, version1Id)
  2533. price_list2 = price_list_crud.get(db, version2Id)
  2534. if not price_list1 or not price_list2:
  2535. return error_response(404, "价格版本不存在")
  2536. if price_list1.region_id != regionId or price_list2.region_id != regionId:
  2537. return error_response(400, "价格版本不属于该区域")
  2538. # 获取两个版本的价格项
  2539. items1 = price_list_item_crud.get_by_price_list(db, version1Id)
  2540. items2 = price_list_item_crud.get_by_price_list(db, version2Id)
  2541. # 构建价格映射
  2542. price_map1 = {item.product_id: item for item in items1}
  2543. price_map2 = {item.product_id: item for item in items2}
  2544. # 获取所有涉及的商品
  2545. all_product_ids = set(price_map1.keys()) | set(price_map2.keys())
  2546. # 构建对比数据
  2547. comparison = []
  2548. for product_id in all_product_ids:
  2549. item1 = price_map1.get(product_id)
  2550. item2 = price_map2.get(product_id)
  2551. product = product_crud.get(db, product_id)
  2552. unit_name = None
  2553. if item1 and item1.unit_id:
  2554. u = unit_crud.get(db, item1.unit_id)
  2555. unit_name = u.name if u else None
  2556. elif item2 and item2.unit_id:
  2557. u = unit_crud.get(db, item2.unit_id)
  2558. unit_name = u.name if u else None
  2559. price1 = float(item1.price) if item1 and item1.price else None
  2560. price2 = float(item2.price) if item2 and item2.price else None
  2561. # 计算差异
  2562. price_diff = None
  2563. price_change = None
  2564. change_rate = None
  2565. if price1 is not None and price2 is not None:
  2566. price_diff = price2 - price1
  2567. if price1 > 0:
  2568. change_rate = round((price_diff / price1) * 100, 2)
  2569. if price_diff > 0:
  2570. price_change = "up"
  2571. elif price_diff < 0:
  2572. price_change = "down"
  2573. else:
  2574. price_change = "same"
  2575. comparison.append({
  2576. "productId": product_id,
  2577. "productName": product.name if product else None,
  2578. "categoryId": product.category_id if product else None,
  2579. "unitId": item1.unit_id if item1 else (item2.unit_id if item2 else None),
  2580. "unitName": unit_name,
  2581. "price1": price1,
  2582. "price2": price2,
  2583. "priceDiff": price_diff,
  2584. "priceChange": price_change,
  2585. "changeRate": change_rate,
  2586. "existIn1": item1 is not None,
  2587. "existIn2": item2 is not None
  2588. })
  2589. # 计算汇总统计
  2590. total_products = len(comparison)
  2591. price_up_count = sum(1 for c in comparison if c["priceChange"] == "up")
  2592. price_down_count = sum(1 for c in comparison if c["priceChange"] == "down")
  2593. price_same_count = sum(1 for c in comparison if c["priceChange"] == "same")
  2594. new_product_count = sum(1 for c in comparison if not c["existIn1"] and c["existIn2"])
  2595. removed_product_count = sum(1 for c in comparison if c["existIn1"] and not c["existIn2"])
  2596. return success_response({
  2597. "version1": {
  2598. "id": price_list1.id,
  2599. "version": price_list1.version,
  2600. "status": price_list1.status,
  2601. "publishedTime": str(price_list1.published_time) if price_list1.published_time else None
  2602. },
  2603. "version2": {
  2604. "id": price_list2.id,
  2605. "version": price_list2.version,
  2606. "status": price_list2.status,
  2607. "publishedTime": str(price_list2.published_time) if price_list2.published_time else None
  2608. },
  2609. "statistics": {
  2610. "totalProducts": total_products,
  2611. "priceUp": price_up_count,
  2612. "priceDown": price_down_count,
  2613. "priceSame": price_same_count,
  2614. "newProducts": new_product_count,
  2615. "removedProducts": removed_product_count
  2616. },
  2617. "comparison": comparison
  2618. })
  2619. @router.get("/price-lists/history", response_model=dict)
  2620. def get_price_list_history(
  2621. regionId: str = Query(..., description="区域ID"),
  2622. page: int = Query(1, ge=1, description="页码"),
  2623. pageSize: int = Query(10, ge=1, le=50, description="每页条数"),
  2624. db: Session = Depends(get_db),
  2625. current_user: dict = Depends(require_admin)
  2626. ):
  2627. """获取价格清单历史版本列表"""
  2628. from app.crud.price_list import price_list_crud
  2629. from app.crud.user import user_crud
  2630. price_lists, total = price_list_crud.get_multi_with_filters(
  2631. db,
  2632. region_id=regionId,
  2633. skip=(page - 1) * pageSize,
  2634. limit=pageSize
  2635. )
  2636. result = []
  2637. for pl in price_lists:
  2638. supplier = user_crud.get(db, pl.supplier_id)
  2639. region = region_crud.get(db, pl.region_id)
  2640. result.append({
  2641. "id": pl.id,
  2642. "version": pl.version,
  2643. "status": pl.status,
  2644. "statusText": "生效中" if pl.status == "active" else "待生效" if pl.status == "pending" else "已失效" if pl.status == "expired" else "草稿",
  2645. "supplierId": pl.supplier_id,
  2646. "supplierName": supplier.real_name if supplier else None,
  2647. "regionName": region.name if region else None,
  2648. "effectiveTime": str(pl.effective_time) if pl.effective_time else None,
  2649. "publishedTime": str(pl.published_time) if pl.published_time else None,
  2650. "remark": pl.remark,
  2651. "createAt": str(pl.create_at) if pl.create_at else None
  2652. })
  2653. return success_response({
  2654. "list": result,
  2655. "total": total,
  2656. "page": page,
  2657. "pageSize": pageSize
  2658. })
  2659. # =========================================
  2660. # 订单管理 API (Web端)
  2661. # =========================================
  2662. # 订单状态映射
  2663. ORDER_STATUS_MAP = {
  2664. "pending_payment": "待支付",
  2665. "pending_review_cancel": "待审核取消",
  2666. "pending_dispatch": "待分配配送",
  2667. "delivering": "配送中",
  2668. "pending_confirm": "待确认收货",
  2669. "completed": "已完结",
  2670. "cancelled": "已取消"
  2671. }
  2672. # 订单状态日志展示(含配送/支付维度的结构化 to_status)
  2673. DELIVERY_STATUS_LOG_LABELS = {
  2674. "pending_dispatch": "待分配配送",
  2675. "delivering": "配送中",
  2676. "delivered": "配送完成",
  2677. }
  2678. def _order_log_status_display_map() -> dict:
  2679. m = dict(ORDER_STATUS_MAP)
  2680. m["delivery.assign"] = "分配配送员"
  2681. m["delivery.reassign"] = "更换配送员"
  2682. for k, v in DELIVERY_STATUS_LOG_LABELS.items():
  2683. m[f"ds_{k}"] = f"配送状态:{v}"
  2684. m["pay_pending_payment"] = "支付状态:待支付"
  2685. m["pay_paid"] = "支付状态:已支付"
  2686. m["pay_refunding"] = "支付状态:退款中"
  2687. m["pay_refunded"] = "支付状态:已退款"
  2688. _task_lbl = {
  2689. "pending": "待分配",
  2690. "assigned": "已分配",
  2691. "supplier_stocking": "供应商备货中",
  2692. "supplier_ready": "备货完成(待取货)",
  2693. "picking": "取货中",
  2694. "delivering": "配送中",
  2695. "completed": "已完成",
  2696. "cancelled": "已取消",
  2697. }
  2698. for k, v in _task_lbl.items():
  2699. m[f"dt_{k}"] = f"配送任务:{v}"
  2700. return m
  2701. ORDER_LOG_STATUS_MAP = _order_log_status_display_map()
  2702. def _status_log_timeline_description(entry: dict) -> str:
  2703. """与 web-admin 订单详情「操作记录」中对 reason/note 的展示规则保持一致。"""
  2704. note = (entry.get("note") or "").strip()
  2705. raw_reason = entry.get("reason")
  2706. description = note or ""
  2707. if raw_reason and str(raw_reason).strip().startswith("{"):
  2708. try:
  2709. o = json.loads(raw_reason)
  2710. if isinstance(o, dict) and (
  2711. o.get("toDeliverName") is not None or o.get("fromDeliverName") is not None
  2712. ):
  2713. description = f"配送员:{o.get('fromDeliverName') or '—'} → {o.get('toDeliverName') or '—'}"
  2714. if note:
  2715. description += f";{note}"
  2716. except json.JSONDecodeError:
  2717. if not description:
  2718. description = str(raw_reason)
  2719. elif raw_reason and not description:
  2720. description = str(raw_reason)
  2721. return description
  2722. def _delivery_timeline_type(to_status: str) -> str:
  2723. if to_status == "dt_completed":
  2724. return "success"
  2725. if to_status == "dt_cancelled":
  2726. return "danger"
  2727. return "primary"
  2728. def _log_entry_in_delivery_timeline(entry: dict) -> bool:
  2729. ts = entry.get("status") or ""
  2730. if ts in ("delivery.assign", "delivery.reassign"):
  2731. return True
  2732. if ts.startswith("dt_") or ts.startswith("ds_"):
  2733. return True
  2734. return False
  2735. def _build_order_delivery_timeline(dtask, log_details: List[dict], order) -> List[dict]:
  2736. """
  2737. 配送进度以订单状态日志为权威来源(配送任务 dt_*、配送状态 ds_*、分配配送员等),
  2738. 与「操作记录」同源,避免两套拼接逻辑长期漂移。
  2739. """
  2740. events: List[dict] = []
  2741. if dtask is not None and dtask.create_at:
  2742. dr = (getattr(dtask, "dispatch_remark", None) or "").strip() or None
  2743. events.append({
  2744. "time": str(dtask.create_at),
  2745. "title": "配送任务已创建",
  2746. "description": dr or "",
  2747. "type": "info",
  2748. "hollow": False,
  2749. })
  2750. timeline_statuses: set = set()
  2751. for entry in log_details:
  2752. if not _log_entry_in_delivery_timeline(entry):
  2753. continue
  2754. ts_key = entry.get("status") or ""
  2755. timeline_statuses.add(ts_key)
  2756. t = entry.get("createAt")
  2757. if not t:
  2758. continue
  2759. from_t = (entry.get("fromStatusText") or "").strip()
  2760. to_t = (entry.get("statusText") or "").strip() or ts_key or "-"
  2761. title = f"{from_t} → {to_t}" if from_t else to_t
  2762. events.append({
  2763. "time": t,
  2764. "title": title,
  2765. "description": _status_log_timeline_description(entry),
  2766. "type": _delivery_timeline_type(ts_key),
  2767. "hollow": False,
  2768. })
  2769. if dtask is not None:
  2770. if dtask.pickup_time and "dt_picking" not in timeline_statuses:
  2771. pr = (dtask.pickup_remark or "").strip() or ""
  2772. events.append({
  2773. "time": str(dtask.pickup_time),
  2774. "title": "配送任务:取货中",
  2775. "description": pr,
  2776. "type": "primary",
  2777. "hollow": False,
  2778. })
  2779. if "dt_completed" not in timeline_statuses and (
  2780. dtask.status == "completed"
  2781. or (getattr(dtask, "deliverer_status", None) == "delivered")
  2782. ):
  2783. t_end = dtask.delivery_time or getattr(order, "delivered_time", None)
  2784. if t_end:
  2785. dr = (dtask.delivery_remark or "").strip() or ""
  2786. events.append({
  2787. "time": str(t_end),
  2788. "title": "配送任务:已完成",
  2789. "description": dr,
  2790. "type": "success",
  2791. "hollow": False,
  2792. })
  2793. events = [e for e in events if e.get("time")]
  2794. events.sort(key=lambda x: str(x.get("time") or ""))
  2795. return events
  2796. @router.get("/orders", response_model=dict)
  2797. def list_orders(
  2798. page: int = Query(1, ge=1, description="页码"),
  2799. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  2800. regionId: Optional[str] = Query(None, description="区域ID"),
  2801. status: Optional[str] = Query(None, description="订单状态"),
  2802. orderStatus: Optional[str] = Query(None, description="订单主状态"),
  2803. deliveryStatus: Optional[str] = Query(None, description="配送状态"),
  2804. payStatus: Optional[str] = Query(None, description="支付状态"),
  2805. paymentMethod: Optional[str] = Query(None, description="支付方式: online/offline"),
  2806. clientId: Optional[str] = Query(None, description="客户ID"),
  2807. orderNo: Optional[str] = Query(None, description="订单号"),
  2808. startDate: Optional[str] = Query(None, description="开始日期"),
  2809. endDate: Optional[str] = Query(None, description="结束日期"),
  2810. db: Session = Depends(get_db),
  2811. current_user: dict = Depends(require_admin)
  2812. ):
  2813. """获取订单列表"""
  2814. from app.crud.order import order_crud, order_item_crud
  2815. # 区域管理员只能查看自己区域的订单
  2816. admin_region_id = get_admin_region_filter(db, current_user)
  2817. if admin_region_id and not regionId:
  2818. # 如果是区域管理员且未指定区域,默认使用其所属区域
  2819. regionId = admin_region_id
  2820. elif admin_region_id and regionId != admin_region_id:
  2821. # 区域管理员不能查看其他区域的订单
  2822. return success_response({
  2823. "list": [],
  2824. "total": 0,
  2825. "page": page,
  2826. "pageSize": pageSize,
  2827. "totalPages": 0
  2828. })
  2829. orders, total = order_crud.get_multi_with_filters(
  2830. db,
  2831. region_id=regionId,
  2832. status=status,
  2833. order_status=orderStatus,
  2834. delivery_status=deliveryStatus,
  2835. pay_status=payStatus,
  2836. payment_method=paymentMethod,
  2837. client_id=clientId,
  2838. order_no=orderNo,
  2839. start_date=startDate,
  2840. end_date=endDate,
  2841. skip=(page - 1) * pageSize,
  2842. limit=pageSize
  2843. )
  2844. # 列表页:按订单行汇总供货总金额 / 售出总金额(与订单详情口径一致)
  2845. order_ids_page = [o.id for o in orders]
  2846. oid_to_order = {o.id: o for o in orders}
  2847. items_by_oid: dict = {}
  2848. if order_ids_page:
  2849. for ln in (
  2850. db.query(BizOrderItem)
  2851. .filter(BizOrderItem.order_id.in_(order_ids_page), BizOrderItem.is_del == 0)
  2852. .all()
  2853. ):
  2854. items_by_oid.setdefault(ln.order_id, []).append(ln)
  2855. pl_ids_page = list({o.price_list_id for o in orders if o.price_list_id})
  2856. pli_map_page = _price_list_item_map(db, pl_ids_page) if pl_ids_page else {}
  2857. order_supplier_selling_totals: dict = {}
  2858. for oid, lines in items_by_oid.items():
  2859. o = oid_to_order.get(oid)
  2860. pl_id = o.price_list_id if o else None
  2861. sup_acc = 0.0
  2862. sel_acc = 0.0
  2863. for item in lines:
  2864. qty = float(item.quantity or 0)
  2865. selling_u = float(item.unit_price or 0)
  2866. selling_amt = (
  2867. float(item.amount) if item.amount is not None else round(qty * selling_u, 2)
  2868. )
  2869. pli = pli_map_page.get((pl_id, item.product_id, item.unit_id)) if pl_id else None
  2870. supplier_u = _supplier_unit_yuan_from_pli(pli)
  2871. if supplier_u is None:
  2872. supplier_u = selling_u
  2873. sup_acc += round(qty * supplier_u, 2)
  2874. sel_acc += selling_amt
  2875. order_supplier_selling_totals[oid] = (round(sup_acc, 2), round(sel_acc, 2))
  2876. region_map = {}
  2877. region_delivery_minutes_map = {}
  2878. client_map = {}
  2879. result = []
  2880. for order in orders:
  2881. order_status = getattr(order, "order_status", None) or "pending_confirm"
  2882. delivery_status = getattr(order, "delivery_status", None) or "pending_dispatch"
  2883. pay_status = getattr(order, "pay_status", None) or "pending_payment"
  2884. # 获取区域名称、预计配送时长
  2885. if order.region_id and order.region_id not in region_map:
  2886. region = region_crud.get(db, order.region_id)
  2887. region_map[order.region_id] = region.name if region else None
  2888. region_delivery_minutes_map[order.region_id] = (
  2889. getattr(region, "expected_delivery_minutes", None) if region else None
  2890. )
  2891. # 获取客户名称
  2892. if order.client_id and order.client_id not in client_map:
  2893. client = user_crud.get(db, order.client_id)
  2894. client_map[order.client_id] = client.real_name if client else None
  2895. # 获取订单项数量
  2896. item_count = order_item_crud.get_count_by_order(db, order.id)
  2897. _sup_total, _sel_total = order_supplier_selling_totals.get(order.id, (0.0, 0.0))
  2898. result.append({
  2899. "id": order.id,
  2900. "orderNo": order.order_no,
  2901. "clientId": order.client_id,
  2902. "clientName": client_map.get(order.client_id),
  2903. "regionId": order.region_id,
  2904. "regionName": region_map.get(order.region_id),
  2905. "regionExpectedDeliveryMinutes": region_delivery_minutes_map.get(order.region_id),
  2906. "totalAmount": float(order.total_amount) if order.total_amount else 0,
  2907. "supplierTotalAmount": _sup_total,
  2908. "sellingTotalAmount": _sel_total,
  2909. "paidAmount": float(order.paid_amount) if order.paid_amount else 0,
  2910. "receivableAmount": float(order.receivable_amount) if order.receivable_amount else 0,
  2911. "status": order.status,
  2912. "orderStatus": order_status,
  2913. "deliveryStatus": delivery_status,
  2914. "payStatus": pay_status,
  2915. "cancelStatus": getattr(order, "cancel_status", None),
  2916. "paymentMethod": order_crud.normalize_payment_method(order.payment_method),
  2917. "paymentStatus": "paid" if order.paid_amount and order.paid_amount > 0 else "unpaid",
  2918. "itemCount": item_count,
  2919. "createAt": str(order.create_at) if order.create_at else None,
  2920. "paymentTime": str(order.payment_time) if order.payment_time else None
  2921. })
  2922. return success_response({
  2923. "list": result,
  2924. "total": total,
  2925. "page": page,
  2926. "pageSize": pageSize,
  2927. "totalPages": (total + pageSize - 1) // pageSize
  2928. })
  2929. @router.get("/orders/{order_id}", response_model=dict)
  2930. def get_order(
  2931. order_id: str,
  2932. db: Session = Depends(get_db),
  2933. current_user: dict = Depends(require_admin)
  2934. ):
  2935. """获取订单详情"""
  2936. from app.crud.order import order_crud, order_item_crud, order_status_log_crud
  2937. order = order_crud.get(db, order_id)
  2938. if not order:
  2939. return error_response(404, "订单不存在")
  2940. # 获取订单项
  2941. items = order_item_crud.get_by_order(db, order_id)
  2942. from app.crud.price_list import price_list_crud
  2943. price_list = price_list_crud.get(db, order.price_list_id) if order.price_list_id else None
  2944. supplier_id_from_price_list = getattr(price_list, "supplier_id", None) if price_list else None
  2945. supplier_name_from_price_list = None
  2946. if supplier_id_from_price_list:
  2947. _sup_u = user_crud.get(db, supplier_id_from_price_list)
  2948. if _sup_u:
  2949. supplier_name_from_price_list = _sup_u.real_name or _sup_u.username
  2950. pl_ids_for_order = [order.price_list_id] if order.price_list_id else []
  2951. pli_map_for_order = _price_list_item_map(db, pl_ids_for_order)
  2952. from app.crud.price_list import price_list_crud
  2953. price_list = price_list_crud.get(db, order.price_list_id) if order.price_list_id else None
  2954. supplier_id_from_price_list = getattr(price_list, "supplier_id", None) if price_list else None
  2955. supplier_name_from_price_list = None
  2956. if supplier_id_from_price_list:
  2957. _sup_u = user_crud.get(db, supplier_id_from_price_list)
  2958. if _sup_u:
  2959. supplier_name_from_price_list = _sup_u.real_name or _sup_u.username
  2960. pl_ids_for_order = [order.price_list_id] if order.price_list_id else []
  2961. pli_map_for_order = _price_list_item_map(db, pl_ids_for_order)
  2962. from app.crud.price_list import price_list_crud
  2963. price_list = price_list_crud.get(db, order.price_list_id) if order.price_list_id else None
  2964. supplier_id_from_price_list = getattr(price_list, "supplier_id", None) if price_list else None
  2965. supplier_name_from_price_list = None
  2966. if supplier_id_from_price_list:
  2967. _sup_u = user_crud.get(db, supplier_id_from_price_list)
  2968. if _sup_u:
  2969. supplier_name_from_price_list = _sup_u.real_name or _sup_u.username
  2970. pl_ids_for_order = [order.price_list_id] if order.price_list_id else []
  2971. pli_map_for_order = _price_list_item_map(db, pl_ids_for_order)
  2972. # 获取状态日志
  2973. status_logs = order_status_log_crud.get_by_order(db, order_id)
  2974. # 尝试锁定订单(防止并发操作)
  2975. lock_info = None
  2976. operator_id = current_user.get("user_id")
  2977. try:
  2978. order_crud.lock_order(db, order_id, operator_id)
  2979. except ValueError as e:
  2980. # 已被其他用户锁定,返回锁定信息但不阻止查看
  2981. lock_info = {
  2982. "isLocked": True,
  2983. "lockedBy": order.lock_operator_id,
  2984. "lockedTime": str(order.lock_time) if order.lock_time else None,
  2985. "message": str(e)
  2986. }
  2987. else:
  2988. lock_info = {"isLocked": False}
  2989. # 获取关联信息
  2990. region_name = None
  2991. region_expected_delivery_minutes = None
  2992. if order.region_id:
  2993. region = region_crud.get(db, order.region_id)
  2994. region_name = region.name if region else None
  2995. region_expected_delivery_minutes = (
  2996. getattr(region, "expected_delivery_minutes", None) if region else None
  2997. )
  2998. client_name = None
  2999. if order.client_id:
  3000. client = user_crud.get(db, order.client_id)
  3001. client_name = client.real_name if client else None
  3002. # 配送任务明细上的已送达量(订单行 delivered_quantity 可能未同步,展示时与任务明细取大)
  3003. from app.crud.delivery import delivery_task_item_crud as _merge_task_delivered
  3004. _line_delivered_from_task = _merge_task_delivered.get_delivered_quantity_by_order_item(db, order_id)
  3005. # 获取商品和单位信息
  3006. item_details = []
  3007. supplier_total_amount = 0.0
  3008. selling_total_amount = 0.0
  3009. for item in items:
  3010. product = product_crud.get(db, item.product_id)
  3011. unit_name = None
  3012. if item.unit_id:
  3013. u = unit_crud.get(db, item.unit_id)
  3014. unit_name = u.name if u else None
  3015. category_id = None
  3016. category_path = ""
  3017. image_url = None
  3018. measure_value = None
  3019. if product:
  3020. category_id = getattr(product, "category_id", None)
  3021. if category_id:
  3022. category_path = _category_path_display(db, str(category_id))
  3023. image_url = getattr(product, "image_url", None)
  3024. measure_value = _numeric_to_float_optional(getattr(product, "measure_value", None))
  3025. _oi_dq = float(item.delivered_quantity) if item.delivered_quantity else 0.0
  3026. _ti_dq = float(_line_delivered_from_task.get(item.id, 0.0))
  3027. _merged_dq = max(_oi_dq, _ti_dq)
  3028. qty = float(item.quantity) if item.quantity else 0
  3029. selling_u = float(item.unit_price) if item.unit_price else 0
  3030. selling_amt = float(item.amount) if item.amount else round(qty * selling_u, 2)
  3031. pli = pli_map_for_order.get((order.price_list_id, item.product_id, item.unit_id))
  3032. supplier_u = _supplier_unit_yuan_from_pli(pli)
  3033. if supplier_u is None:
  3034. supplier_u = selling_u
  3035. supplier_amt = round(qty * supplier_u, 2)
  3036. supplier_total_amount += supplier_amt
  3037. selling_total_amount += selling_amt
  3038. item_details.append({
  3039. "id": item.id,
  3040. "productId": item.product_id,
  3041. "productName": product.name if product else None,
  3042. "imageUrl": image_url,
  3043. "categoryId": str(category_id) if category_id else None,
  3044. "categoryName": category_path or None,
  3045. "measureValue": measure_value,
  3046. "unitId": item.unit_id,
  3047. "unitName": unit_name,
  3048. "supplierId": supplier_id_from_price_list,
  3049. "supplierName": supplier_name_from_price_list,
  3050. "quantity": qty,
  3051. "unitPrice": selling_u,
  3052. "amount": selling_amt,
  3053. "sellingUnitPrice": selling_u,
  3054. "sellingAmount": selling_amt,
  3055. "supplierUnitPrice": supplier_u,
  3056. "supplierAmount": supplier_amt,
  3057. "deliveredQuantity": _merged_dq,
  3058. "status": item.status
  3059. })
  3060. order_status = getattr(order, "order_status", None) or "pending_confirm"
  3061. delivery_status = getattr(order, "delivery_status", None) or "pending_dispatch"
  3062. pay_status = getattr(order, "pay_status", None) or "pending_payment"
  3063. # 处理状态日志(含配送任务、配送员分配等结构化记录)
  3064. log_details = []
  3065. for log in status_logs:
  3066. log_details.append({
  3067. "fromStatus": log.from_status,
  3068. "fromStatusText": ORDER_LOG_STATUS_MAP.get(
  3069. log.from_status, log.from_status or ""
  3070. ),
  3071. "status": log.to_status,
  3072. "statusText": ORDER_LOG_STATUS_MAP.get(log.to_status, log.to_status),
  3073. # BizOrderStatusLog 无 operator_name 字段,优先使用 create_name
  3074. "operatorName": getattr(log, "create_name", None) or getattr(log, "operator_id", None),
  3075. "operatorRole": log.operator_role,
  3076. "reason": log.reason,
  3077. "note": log.note,
  3078. "createAt": str(log.create_at) if log.create_at else None
  3079. })
  3080. deliver_id_out = None
  3081. deliver_name = None
  3082. deliver_phone = None
  3083. expected_time = None
  3084. delivery_dispatch_remark = None
  3085. delivery_timeline = []
  3086. supplier_id_for_pickup = None
  3087. supplier_name = None
  3088. supplier_phone = None
  3089. supplier_pickup = {"fullAddress": None, "contactPerson": None, "contactPhone": None}
  3090. delivery_task_no = None
  3091. delivery_task_status = None
  3092. delivery_task_deliverer_status = None
  3093. delivery_task_supplier_prepare_status = None
  3094. delivery_pickup_time = None
  3095. delivery_pickup_remark = None
  3096. delivery_delivery_time = None
  3097. delivery_delivery_remark = None
  3098. delivery_prepare_images = []
  3099. delivery_pickup_images = []
  3100. delivery_deliver_images = []
  3101. from app.crud.delivery import delivery_task_crud as _order_delivery_task_crud
  3102. dtask = _order_delivery_task_crud.get_by_order(db, order_id)
  3103. if dtask:
  3104. deliver_id_out = dtask.deliver_id
  3105. delivery_task_no = dtask.task_no
  3106. delivery_task_status = dtask.status
  3107. delivery_task_deliverer_status = getattr(dtask, "deliverer_status", None)
  3108. delivery_task_supplier_prepare_status = getattr(dtask, "supplier_prepare_status", None)
  3109. delivery_pickup_time = str(dtask.pickup_time) if dtask.pickup_time else None
  3110. delivery_pickup_remark = dtask.pickup_remark
  3111. delivery_delivery_time = str(dtask.delivery_time) if dtask.delivery_time else None
  3112. delivery_delivery_remark = dtask.delivery_remark
  3113. if dtask.deliver_id:
  3114. du = user_crud.get(db, dtask.deliver_id)
  3115. if du:
  3116. deliver_name = du.real_name
  3117. deliver_phone = du.phone
  3118. expected_time = str(dtask.effective_time) if dtask.effective_time else None
  3119. delivery_dispatch_remark = getattr(dtask, "dispatch_remark", None) or None
  3120. supplier_id_for_pickup = dtask.supplier_id
  3121. delivery_timeline = _build_order_delivery_timeline(dtask, log_details, order)
  3122. from app.crud.attachment import attachment_crud as _attachment_crud
  3123. delivery_prepare_images = [
  3124. a.file_url for a in _attachment_crud.get_by_business(db, "delivery_prepare", dtask.id) if a.file_url
  3125. ]
  3126. delivery_pickup_images = [
  3127. a.file_url for a in _attachment_crud.get_by_business(db, "delivery_pickup", dtask.id) if a.file_url
  3128. ]
  3129. delivery_deliver_images = [
  3130. a.file_url for a in _attachment_crud.get_by_business(db, "delivery_deliver", dtask.id) if a.file_url
  3131. ]
  3132. # 兼容旧数据:历史仅写在任务字段中
  3133. if not delivery_pickup_images and getattr(dtask, "pickup_image_url", None):
  3134. delivery_pickup_images = [
  3135. s.strip() for s in str(dtask.pickup_image_url).split(",") if s and str(s).strip()
  3136. ]
  3137. if not delivery_deliver_images and getattr(dtask, "delivery_image_url", None):
  3138. delivery_deliver_images = [
  3139. s.strip() for s in str(dtask.delivery_image_url).split(",") if s and str(s).strip()
  3140. ]
  3141. else:
  3142. from app.crud.price_list import price_list_crud
  3143. _pl = price_list_crud.get(db, order.price_list_id)
  3144. if _pl and getattr(_pl, "supplier_id", None):
  3145. supplier_id_for_pickup = _pl.supplier_id
  3146. delivery_timeline = _build_order_delivery_timeline(None, log_details, order)
  3147. if supplier_id_for_pickup:
  3148. _su = user_crud.get(db, supplier_id_for_pickup)
  3149. if _su:
  3150. supplier_name = _su.real_name
  3151. supplier_phone = _su.phone
  3152. supplier_pickup = _supplier_pickup_address_block(db, supplier_id_for_pickup)
  3153. return success_response({
  3154. "id": order.id,
  3155. "orderNo": order.order_no,
  3156. "regionId": order.region_id,
  3157. "regionName": region_name,
  3158. "regionExpectedDeliveryMinutes": region_expected_delivery_minutes,
  3159. "clientId": order.client_id,
  3160. "clientName": client_name,
  3161. "priceListId": order.price_list_id,
  3162. "priceVersion": order.price_version,
  3163. "status": order.status,
  3164. "orderStatus": order_status,
  3165. "deliveryStatus": delivery_status,
  3166. "payStatus": pay_status,
  3167. "paymentMethod": order_crud.normalize_payment_method(order.payment_method),
  3168. "totalAmount": float(order.total_amount) if order.total_amount else 0,
  3169. "sellingTotalAmount": round(selling_total_amount, 2),
  3170. "supplierTotalAmount": round(supplier_total_amount, 2),
  3171. "paidAmount": float(order.paid_amount) if order.paid_amount else 0,
  3172. "receivableAmount": float(order.receivable_amount) if order.receivable_amount else 0,
  3173. "refundAmount": float(order.refund_amount) if order.refund_amount else 0,
  3174. "contactPerson": order.contact_person,
  3175. "contactPhone": order.contact_phone,
  3176. "deliveryAddress": order.delivery_address,
  3177. "remark": order.remark,
  3178. "cancelReason": order.cancel_reason,
  3179. "cancelReviewNote": order.cancel_review_note,
  3180. "createAt": str(order.create_at) if order.create_at else None,
  3181. "paymentTime": str(order.payment_time) if order.payment_time else None,
  3182. "completedTime": str(order.completed_time) if order.completed_time else None,
  3183. "deliverId": deliver_id_out,
  3184. "deliverName": deliver_name,
  3185. "deliverPhone": deliver_phone,
  3186. "expectedTime": expected_time,
  3187. "deliveryDispatchRemark": delivery_dispatch_remark,
  3188. "deliveryTimeline": delivery_timeline,
  3189. "supplierId": supplier_id_for_pickup,
  3190. "supplierName": supplier_name,
  3191. "supplierPhone": supplier_phone,
  3192. "supplierPickup": {
  3193. "address": supplier_pickup.get("fullAddress"),
  3194. "contactPerson": supplier_pickup.get("contactPerson"),
  3195. "contactPhone": supplier_pickup.get("contactPhone"),
  3196. },
  3197. "deliveryTaskNo": delivery_task_no,
  3198. "deliveryTaskStatus": delivery_task_status,
  3199. "deliveryTaskDelivererStatus": delivery_task_deliverer_status,
  3200. "deliveryTaskSupplierPrepareStatus": delivery_task_supplier_prepare_status,
  3201. "deliveryPickupTime": delivery_pickup_time,
  3202. "deliveryPickupRemark": delivery_pickup_remark,
  3203. "deliveryDeliveryTime": delivery_delivery_time,
  3204. "deliveryDeliveryRemark": delivery_delivery_remark,
  3205. "deliveryPrepareImages": delivery_prepare_images,
  3206. "deliveryPickupImages": delivery_pickup_images,
  3207. "deliveryDeliverImages": delivery_deliver_images,
  3208. "items": item_details,
  3209. "statusLogs": log_details,
  3210. "lockInfo": lock_info
  3211. })
  3212. @router.post("/orders/{order_id}/unlock", response_model=dict)
  3213. def unlock_order(
  3214. order_id: str,
  3215. db: Session = Depends(get_db),
  3216. current_user: dict = Depends(require_admin)
  3217. ):
  3218. """手动解锁订单"""
  3219. from app.crud.order import order_crud
  3220. order = order_crud.get(db, order_id)
  3221. if not order:
  3222. return error_response(404, "订单不存在")
  3223. operator_id = current_user.get("user_id")
  3224. try:
  3225. order_crud.unlock_order(db, order_id, operator_id)
  3226. return success_response({"message": "解锁成功"})
  3227. except ValueError as e:
  3228. return error_response(400, str(e))
  3229. @router.post("/orders/{order_id}/review-cancel", response_model=dict)
  3230. def review_order_cancel(
  3231. order_id: str,
  3232. request: dict,
  3233. db: Session = Depends(get_db),
  3234. current_user: dict = Depends(require_admin)
  3235. ):
  3236. """审核取消订单"""
  3237. from app.crud.order import order_crud
  3238. order = order_crud.get(db, order_id)
  3239. if not order:
  3240. return error_response(404, "订单不存在")
  3241. if getattr(order, "cancel_status", "none") != "pending_review":
  3242. return error_response(400, "只有待审核取消的订单才能审核")
  3243. approved = request.get("approved", False)
  3244. review_note = request.get("reviewNote")
  3245. reviewer_id = current_user.get("user_id")
  3246. order = order_crud.review_cancel(
  3247. db,
  3248. order_id,
  3249. approved=approved,
  3250. reviewer_id=reviewer_id,
  3251. review_note=review_note
  3252. )
  3253. return success_response({
  3254. "id": order.id,
  3255. "status": order.status,
  3256. "orderStatus": getattr(order, "order_status", None),
  3257. "deliveryStatus": getattr(order, "delivery_status", None),
  3258. "payStatus": getattr(order, "pay_status", None),
  3259. "cancelStatus": getattr(order, "cancel_status", None),
  3260. "message": "审核完成"
  3261. })
  3262. @router.get("/orders/pending-cancel", response_model=dict)
  3263. def list_pending_cancel_orders(
  3264. page: int = Query(1, ge=1, description="页码"),
  3265. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  3266. db: Session = Depends(get_db),
  3267. current_user: dict = Depends(require_admin)
  3268. ):
  3269. """获取待审核取消的订单列表"""
  3270. from app.crud.order import order_crud, order_item_crud
  3271. orders, total = order_crud.get_multi_with_filters(
  3272. db,
  3273. cancel_status="pending_review",
  3274. skip=(page - 1) * pageSize,
  3275. limit=pageSize
  3276. )
  3277. region_map = {}
  3278. client_map = {}
  3279. result = []
  3280. for order in orders:
  3281. if order.region_id and order.region_id not in region_map:
  3282. region = region_crud.get(db, order.region_id)
  3283. region_map[order.region_id] = region.name if region else None
  3284. if order.client_id and order.client_id not in client_map:
  3285. client = user_crud.get(db, order.client_id)
  3286. client_map[order.client_id] = client.real_name if client else None
  3287. item_count = order_item_crud.get_count_by_order(db, order.id)
  3288. result.append({
  3289. "id": order.id,
  3290. "orderNo": order.order_no,
  3291. "clientId": order.client_id,
  3292. "clientName": client_map.get(order.client_id),
  3293. "regionId": order.region_id,
  3294. "regionName": region_map.get(order.region_id),
  3295. "totalAmount": float(order.total_amount) if order.total_amount else 0,
  3296. "paidAmount": float(order.paid_amount) if order.paid_amount else 0,
  3297. "cancelReason": order.cancel_reason,
  3298. "itemCount": item_count,
  3299. "createAt": str(order.create_at) if order.create_at else None
  3300. })
  3301. return success_response({
  3302. "list": result,
  3303. "total": total,
  3304. "page": page,
  3305. "pageSize": pageSize,
  3306. "totalPages": (total + pageSize - 1) // pageSize
  3307. })
  3308. # =========================================
  3309. # 订单锁定管理 API
  3310. # =========================================
  3311. @router.post("/orders/{order_id}/lock", response_model=dict)
  3312. def lock_order(
  3313. order_id: str,
  3314. db: Session = Depends(get_db),
  3315. current_user: dict = Depends(require_admin)
  3316. ):
  3317. """锁定订单"""
  3318. from app.crud.order import order_crud
  3319. order = order_crud.get(db, order_id)
  3320. if not order:
  3321. return error_response(404, "订单不存在")
  3322. try:
  3323. order = order_crud.lock_order(
  3324. db,
  3325. order_id=order_id,
  3326. operator_id=current_user.get("user_id")
  3327. )
  3328. return success_response({
  3329. "id": order.id,
  3330. "lockOperatorId": order.lock_operator_id,
  3331. "lockTime": str(order.lock_time) if order.lock_time else None,
  3332. "message": "锁定成功"
  3333. })
  3334. except ValueError as e:
  3335. return error_response(400, str(e))
  3336. @router.post("/orders/{order_id}/unlock", response_model=dict)
  3337. def unlock_order(
  3338. order_id: str,
  3339. db: Session = Depends(get_db),
  3340. current_user: dict = Depends(require_admin)
  3341. ):
  3342. """解锁订单"""
  3343. from app.crud.order import order_crud
  3344. order = order_crud.get(db, order_id)
  3345. if not order:
  3346. return error_response(404, "订单不存在")
  3347. try:
  3348. order = order_crud.unlock_order(
  3349. db,
  3350. order_id=order_id,
  3351. operator_id=current_user.get("user_id")
  3352. )
  3353. return success_response({
  3354. "id": order.id,
  3355. "message": "解锁成功"
  3356. })
  3357. except ValueError as e:
  3358. return error_response(400, str(e))
  3359. # =========================================
  3360. # 订单调整管理 API
  3361. # =========================================
  3362. @router.post("/orders/{order_id}/adjust", response_model=dict)
  3363. def adjust_order(
  3364. order_id: str,
  3365. request: dict,
  3366. db: Session = Depends(get_db),
  3367. current_user: dict = Depends(require_admin)
  3368. ):
  3369. """订单调整(增量/减量/删除/替代)"""
  3370. import json
  3371. from app.crud.order import order_crud, order_item_crud, order_adjust_crud
  3372. from decimal import Decimal
  3373. from app.models.models import BizDeliveryTask, BizDeliveryTaskItem
  3374. order = order_crud.get(db, order_id)
  3375. if not order:
  3376. return error_response(404, "订单不存在")
  3377. # 检查订单是否被其他操作员锁定
  3378. operator_id = current_user.get("user_id")
  3379. if order.lock_operator_id and order.lock_operator_id != operator_id:
  3380. lock_time = order.lock_time.strftime("%Y-%m-%d %H:%M:%S") if order.lock_time else "未知"
  3381. return error_response(400, f"订单已被其他操作员于 {lock_time} 锁定,请先解锁后再操作")
  3382. # 仅线下支付订单允许运营调整
  3383. if getattr(order, "payment_method", None) != "offline":
  3384. return error_response(400, "仅线下支付订单支持运营调整")
  3385. # 新状态模型:仅未完成/未取消的线下单支持调整
  3386. if getattr(order, "order_status", None) not in ["pending_payment", "pending_confirm"]:
  3387. return error_response(400, "当前状态不支持调整")
  3388. adjustments = request.get("adjustments", [])
  3389. address_update = request.get("addressUpdate") or {}
  3390. has_address_update = isinstance(address_update, dict) and len(address_update.keys()) > 0
  3391. if not adjustments and not has_address_update:
  3392. return error_response(400, "请提供调整项或地址调整信息")
  3393. operator_name = current_user.get("real_name")
  3394. adjust_results = []
  3395. for adj in adjustments:
  3396. order_item_id = adj.get("orderItemId")
  3397. adjust_type = adj.get("adjustType") # increase/reduce/delete/substitute
  3398. new_quantity = adj.get("newQuantity")
  3399. new_product_id = adj.get("newProductId")
  3400. reason = adj.get("reason")
  3401. if not order_item_id or not adjust_type:
  3402. continue
  3403. if not reason:
  3404. return error_response(400, "调整原因不能为空")
  3405. # 获取订单项
  3406. item = order_item_crud.get(db, order_item_id)
  3407. if not item or item.order_id != order_id:
  3408. continue
  3409. before_quantity = item.quantity
  3410. before_amount = item.amount
  3411. try:
  3412. if adjust_type == "increase":
  3413. # 增量
  3414. if new_quantity is None or new_quantity < 0:
  3415. return error_response(400, "增量后数量不能小于0")
  3416. if new_quantity < float(item.quantity):
  3417. return error_response(400, "增量后数量不能小于原数量")
  3418. new_amount = Decimal(str(new_quantity)) * item.unit_price
  3419. order_item_crud.update_item_adjustment(
  3420. db, order_item_id,
  3421. new_quantity=Decimal(str(new_quantity)),
  3422. new_amount=new_amount,
  3423. new_status="increased",
  3424. note=reason,
  3425. updater_id=operator_id,
  3426. updater_name=operator_name
  3427. )
  3428. snapshot_items = order_item_crud.get_by_order(db, order_id)
  3429. snapshot = [{
  3430. "orderItemId": it.id,
  3431. "productId": it.product_id,
  3432. "quantity": float(it.quantity) if it.quantity else 0,
  3433. "status": it.status,
  3434. } for it in snapshot_items if it.is_del == 0]
  3435. order_adjust_crud.create_adjust_record(
  3436. db,
  3437. order_id=order_id,
  3438. order_item_id=order_item_id,
  3439. adjust_type="increase",
  3440. operator_id=operator_id,
  3441. operator_name=operator_name,
  3442. before_quantity=before_quantity,
  3443. after_quantity=Decimal(str(new_quantity)),
  3444. before_amount=before_amount,
  3445. after_amount=new_amount,
  3446. difference_amount=new_amount - before_amount,
  3447. reason=reason,
  3448. snapshot_items_json=json.dumps(snapshot, ensure_ascii=False)
  3449. )
  3450. adjust_results.append({
  3451. "orderItemId": order_item_id,
  3452. "adjustType": "increase",
  3453. "success": True
  3454. })
  3455. elif adjust_type == "reduce":
  3456. # 减量
  3457. if new_quantity is None or new_quantity < 0:
  3458. return error_response(400, "减量后数量不能小于0")
  3459. if new_quantity > float(item.quantity):
  3460. return error_response(400, "减量后数量不能大于原数量")
  3461. new_amount = Decimal(str(new_quantity)) * item.unit_price
  3462. order_item_crud.mark_as_reduced(
  3463. db, order_item_id,
  3464. new_quantity=Decimal(str(new_quantity)),
  3465. new_amount=new_amount,
  3466. note=reason
  3467. )
  3468. snapshot_items = order_item_crud.get_by_order(db, order_id)
  3469. snapshot = [{
  3470. "orderItemId": it.id,
  3471. "productId": it.product_id,
  3472. "quantity": float(it.quantity) if it.quantity else 0,
  3473. "status": it.status,
  3474. } for it in snapshot_items if it.is_del == 0]
  3475. # 创建调整记录
  3476. order_adjust_crud.create_adjust_record(
  3477. db,
  3478. order_id=order_id,
  3479. order_item_id=order_item_id,
  3480. adjust_type="reduce",
  3481. operator_id=operator_id,
  3482. operator_name=operator_name,
  3483. before_quantity=before_quantity,
  3484. after_quantity=Decimal(str(new_quantity)),
  3485. before_amount=before_amount,
  3486. after_amount=new_amount,
  3487. difference_amount=new_amount - before_amount,
  3488. reason=reason,
  3489. snapshot_items_json=json.dumps(snapshot, ensure_ascii=False)
  3490. )
  3491. adjust_results.append({
  3492. "orderItemId": order_item_id,
  3493. "adjustType": "reduce",
  3494. "success": True
  3495. })
  3496. elif adjust_type == "delete":
  3497. # 删除
  3498. order_item_crud.mark_as_deleted(
  3499. db, order_item_id,
  3500. note=reason
  3501. )
  3502. snapshot_items = order_item_crud.get_by_order(db, order_id)
  3503. snapshot = [{
  3504. "orderItemId": it.id,
  3505. "productId": it.product_id,
  3506. "quantity": float(it.quantity) if it.quantity else 0,
  3507. "status": it.status,
  3508. } for it in snapshot_items if it.is_del == 0]
  3509. # 创建调整记录
  3510. order_adjust_crud.create_adjust_record(
  3511. db,
  3512. order_id=order_id,
  3513. order_item_id=order_item_id,
  3514. adjust_type="delete",
  3515. operator_id=operator_id,
  3516. operator_name=operator_name,
  3517. before_quantity=before_quantity,
  3518. after_quantity=Decimal("0"),
  3519. before_amount=before_amount,
  3520. after_amount=Decimal("0"),
  3521. difference_amount=-before_amount,
  3522. reason=reason,
  3523. snapshot_items_json=json.dumps(snapshot, ensure_ascii=False)
  3524. )
  3525. adjust_results.append({
  3526. "orderItemId": order_item_id,
  3527. "adjustType": "delete",
  3528. "success": True
  3529. })
  3530. elif adjust_type == "substitute":
  3531. # 替代
  3532. if not new_product_id or not new_quantity:
  3533. return error_response(400, "替代商品ID和数量不能为空")
  3534. # 获取新商品信息
  3535. new_product = product_crud.get(db, new_product_id)
  3536. if not new_product:
  3537. return error_response(404, "替代商品不存在")
  3538. # 需要获取新商品的价格
  3539. from app.crud.price_list import price_list_item_crud
  3540. price_item = price_list_item_crud.get_by_product_and_price_list(
  3541. db, new_product_id, order.price_list_id
  3542. )
  3543. if not price_item:
  3544. return error_response(400, "替代商品不在价格清单中")
  3545. new_unit_price = price_item.price
  3546. new_amount = Decimal(str(new_quantity)) * new_unit_price
  3547. order_item_crud.update_item_adjustment(
  3548. db, order_item_id,
  3549. new_quantity=Decimal(str(new_quantity)),
  3550. new_amount=new_amount,
  3551. new_status="substituted",
  3552. note=f"{reason},替代商品: {new_product.name}",
  3553. updater_id=operator_id,
  3554. updater_name=operator_name
  3555. )
  3556. snapshot_items = order_item_crud.get_by_order(db, order_id)
  3557. snapshot = [{
  3558. "orderItemId": it.id,
  3559. "productId": it.product_id,
  3560. "quantity": float(it.quantity) if it.quantity else 0,
  3561. "status": it.status,
  3562. } for it in snapshot_items if it.is_del == 0]
  3563. # 创建调整记录
  3564. order_adjust_crud.create_adjust_record(
  3565. db,
  3566. order_id=order_id,
  3567. order_item_id=order_item_id,
  3568. adjust_type="substitute",
  3569. operator_id=operator_id,
  3570. operator_name=operator_name,
  3571. before_quantity=before_quantity,
  3572. after_quantity=Decimal(str(new_quantity)),
  3573. before_amount=before_amount,
  3574. after_amount=new_amount,
  3575. difference_amount=new_amount - before_amount,
  3576. reason=reason,
  3577. substitute_product_id=new_product_id,
  3578. snapshot_items_json=json.dumps(snapshot, ensure_ascii=False)
  3579. )
  3580. adjust_results.append({
  3581. "orderItemId": order_item_id,
  3582. "adjustType": "substitute",
  3583. "newProductId": new_product_id,
  3584. "success": True
  3585. })
  3586. except Exception as e:
  3587. adjust_results.append({
  3588. "orderItemId": order_item_id,
  3589. "adjustType": adjust_type,
  3590. "success": False,
  3591. "error": str(e)
  3592. })
  3593. if has_address_update:
  3594. old_delivery_address = order.delivery_address or ""
  3595. old_contact_person = order.contact_person or ""
  3596. old_contact_phone = order.contact_phone or ""
  3597. new_delivery_address = str(address_update.get("deliveryAddress") or old_delivery_address).strip()
  3598. new_contact_person = str(address_update.get("contactPerson") or old_contact_person).strip()
  3599. new_contact_phone = str(address_update.get("contactPhone") or old_contact_phone).strip()
  3600. address_reason = str(address_update.get("reason") or "").strip()
  3601. address_changed = (
  3602. new_delivery_address != old_delivery_address
  3603. or new_contact_person != old_contact_person
  3604. or new_contact_phone != old_contact_phone
  3605. )
  3606. if address_changed:
  3607. order.delivery_address = new_delivery_address
  3608. order.contact_person = new_contact_person
  3609. order.contact_phone = new_contact_phone
  3610. active_task = db.query(BizDeliveryTask).filter(
  3611. BizDeliveryTask.order_id == order_id,
  3612. BizDeliveryTask.is_del == 0
  3613. ).first()
  3614. if active_task:
  3615. task_items = db.query(BizDeliveryTaskItem).filter(
  3616. BizDeliveryTaskItem.task_id == active_task.id,
  3617. BizDeliveryTaskItem.is_del == 0
  3618. ).all()
  3619. for task_item in task_items:
  3620. task_item.delivery_address = new_delivery_address
  3621. task_item.contact_person = new_contact_person
  3622. task_item.contact_phone = new_contact_phone
  3623. task_item.update_at = datetime.now()
  3624. snapshot_items = order_item_crud.get_by_order(db, order_id)
  3625. snapshot = [{
  3626. "orderItemId": it.id,
  3627. "productId": it.product_id,
  3628. "quantity": float(it.quantity) if it.quantity else 0,
  3629. "status": it.status,
  3630. } for it in snapshot_items if it.is_del == 0]
  3631. reason_parts = []
  3632. reason_parts.append(f"地址:{old_delivery_address or '-'} -> {new_delivery_address or '-'}")
  3633. reason_parts.append(f"联系人:{old_contact_person or '-'} -> {new_contact_person or '-'}")
  3634. reason_parts.append(f"电话:{old_contact_phone or '-'} -> {new_contact_phone or '-'}")
  3635. if address_reason:
  3636. reason_parts.append(f"备注:{address_reason}")
  3637. address_log_reason = ";".join(reason_parts)
  3638. order_adjust_crud.create_adjust_record(
  3639. db,
  3640. order_id=order_id,
  3641. order_item_id=None,
  3642. adjust_type="address",
  3643. operator_id=operator_id,
  3644. operator_name=operator_name,
  3645. before_quantity=Decimal("0"),
  3646. after_quantity=Decimal("0"),
  3647. before_amount=Decimal("0"),
  3648. after_amount=Decimal("0"),
  3649. difference_amount=Decimal("0"),
  3650. reason=address_log_reason,
  3651. snapshot_items_json=json.dumps(snapshot, ensure_ascii=False)
  3652. )
  3653. adjust_results.append({
  3654. "adjustType": "address",
  3655. "success": True
  3656. })
  3657. # 重新计算订单应收金额
  3658. all_items = order_item_crud.get_by_order(db, order_id)
  3659. new_total = sum(
  3660. float(item.amount) for item in all_items
  3661. if item.status != "deleted" and item.is_del == 0
  3662. )
  3663. new_receivable = Decimal(str(new_total))
  3664. order.total_amount = new_receivable
  3665. order.receivable_amount = new_receivable
  3666. order.update_at = datetime.now()
  3667. db.commit()
  3668. db.refresh(order)
  3669. return success_response({
  3670. "id": order.id,
  3671. "totalAmount": float(order.total_amount),
  3672. "receivableAmount": float(order.receivable_amount),
  3673. "adjustments": adjust_results,
  3674. "message": "调整成功"
  3675. })
  3676. @router.get("/orders/{order_id}/adjusts", response_model=dict)
  3677. def list_order_adjusts(
  3678. order_id: str,
  3679. db: Session = Depends(get_db),
  3680. current_user: dict = Depends(require_admin)
  3681. ):
  3682. """获取订单调整记录"""
  3683. import json
  3684. from app.crud.order import order_crud, order_adjust_crud
  3685. order = order_crud.get(db, order_id)
  3686. if not order:
  3687. return error_response(404, "订单不存在")
  3688. adjusts = order_adjust_crud.get_by_order(db, order_id)
  3689. result = []
  3690. for adj in adjusts:
  3691. result.append({
  3692. "id": adj.id,
  3693. "orderId": adj.order_id,
  3694. "orderItemId": adj.order_item_id,
  3695. "adjustType": adj.adjust_type,
  3696. "beforeQuantity": float(adj.before_quantity) if adj.before_quantity else 0,
  3697. "afterQuantity": float(adj.after_quantity) if adj.after_quantity else 0,
  3698. "beforeAmount": float(adj.before_amount) if adj.before_amount else 0,
  3699. "afterAmount": float(adj.after_amount) if adj.after_amount else 0,
  3700. "differenceAmount": float(adj.difference_amount) if adj.difference_amount else 0,
  3701. "reason": adj.reason,
  3702. "snapshotItems": json.loads(adj.snapshot_items_json) if getattr(adj, "snapshot_items_json", None) else [],
  3703. "operatorName": adj.operator_name,
  3704. "createAt": str(adj.create_at) if adj.create_at else None
  3705. })
  3706. return success_response({
  3707. "list": result,
  3708. "total": len(result)
  3709. })
  3710. @router.post("/orders/{order_id}/force-complete", response_model=dict)
  3711. def force_complete_order(
  3712. order_id: str,
  3713. request: dict,
  3714. db: Session = Depends(get_db),
  3715. current_user: dict = Depends(require_admin)
  3716. ):
  3717. """运营强制完结订单"""
  3718. from app.crud.order import order_crud
  3719. order = order_crud.get(db, order_id)
  3720. if not order:
  3721. return error_response(404, "订单不存在")
  3722. reason = request.get("reason", "运营强制完结")
  3723. try:
  3724. order = order_crud.force_complete(
  3725. db,
  3726. order_id=order_id,
  3727. operator_id=current_user.get("user_id"),
  3728. operator_role="admin",
  3729. reason=reason
  3730. )
  3731. return success_response({
  3732. "id": order.id,
  3733. "status": order.status,
  3734. "orderStatus": getattr(order, "order_status", None) or "pending_confirm",
  3735. "deliveryStatus": getattr(order, "delivery_status", None) or "pending_dispatch",
  3736. "payStatus": getattr(order, "pay_status", None) or "pending_payment",
  3737. "completedTime": str(order.completed_time) if order.completed_time else None,
  3738. "message": "强制完结成功"
  3739. })
  3740. except ValueError as e:
  3741. return error_response(400, str(e))
  3742. @router.post("/orders/{order_id}/partial-delivered", response_model=dict)
  3743. def mark_partial_delivered(
  3744. order_id: str,
  3745. request: dict,
  3746. db: Session = Depends(get_db),
  3747. current_user: dict = Depends(require_admin)
  3748. ):
  3749. """已废弃:旧的部分送达流程不再支持。"""
  3750. return error_response(410, "该接口已下线,请使用配送任务状态流转接口")
  3751. @router.post("/orders/{order_id}/confirm-partial", response_model=dict)
  3752. def confirm_partial_delivery(
  3753. order_id: str,
  3754. request: dict,
  3755. db: Session = Depends(get_db),
  3756. current_user: dict = Depends(require_admin)
  3757. ):
  3758. """已废弃:旧的部分送达确认流程不再支持。"""
  3759. return error_response(410, "该接口已下线,请使用订单确认收货流程")
  3760. @router.post("/orders/{order_id}/create-delivery-task", response_model=dict)
  3761. def create_delivery_task_from_order(
  3762. order_id: str,
  3763. db: Session = Depends(get_db),
  3764. current_user: dict = Depends(require_admin)
  3765. ):
  3766. """从订单创建配送任务"""
  3767. from app.crud.order import order_crud, order_item_crud
  3768. from app.crud.delivery import delivery_task_crud, delivery_task_item_crud
  3769. order = order_crud.get(db, order_id)
  3770. if not order:
  3771. return error_response(404, "订单不存在")
  3772. # 只有待分配配送状态可以创建配送任务
  3773. if getattr(order, "delivery_status", None) != "pending_dispatch":
  3774. return error_response(400, "只有待分配配送状态的订单可以创建配送任务")
  3775. # 检查是否已存在配送任务
  3776. existing_task = delivery_task_crud.get_by_order(db, order_id)
  3777. if existing_task:
  3778. return error_response(400, "该订单已存在配送任务")
  3779. # 获取订单关联的价格清单,以获取供应商ID
  3780. from app.crud.price_list import price_list_crud
  3781. price_list = price_list_crud.get(db, order.price_list_id)
  3782. if not price_list:
  3783. return error_response(400, "订单关联的价格清单不存在")
  3784. supplier_id = price_list.supplier_id
  3785. # 获取订单项
  3786. order_items = order_item_crud.get_by_order(db, order_id)
  3787. # 构建配送任务明细数据
  3788. task_items_data = []
  3789. for item in order_items:
  3790. if item.status == "deleted" or item.is_del != 0:
  3791. continue
  3792. task_items_data.append({
  3793. "order_item_id": item.id,
  3794. "product_id": item.product_id,
  3795. "client_id": order.client_id,
  3796. "delivery_address": order.delivery_address,
  3797. "contact_person": order.contact_person,
  3798. "contact_phone": order.contact_phone,
  3799. "quantity": float(item.quantity) if item.quantity else 0
  3800. })
  3801. creator = {
  3802. "user_id": current_user.get("user_id"),
  3803. "real_name": current_user.get("real_name")
  3804. }
  3805. # 创建配送任务及明细
  3806. task, task_items = delivery_task_crud.create_delivery_task_from_order(
  3807. db,
  3808. order_id=order_id,
  3809. order_items=task_items_data,
  3810. supplier_id=supplier_id,
  3811. region_id=order.region_id,
  3812. creator=creator
  3813. )
  3814. # 阶段D收尾:优先维护三字段,再回写旧 status
  3815. from app.core.order_status_compat import derive_legacy_status_from_three
  3816. order.order_status = "pending_confirm"
  3817. order.delivery_status = "delivering"
  3818. order.status = derive_legacy_status_from_three(
  3819. order_status=order.order_status,
  3820. delivery_status=order.delivery_status,
  3821. pay_status=order.pay_status,
  3822. )
  3823. order.delivery_assign_time = datetime.now()
  3824. order.update_at = datetime.now()
  3825. db.commit()
  3826. return success_response({
  3827. "id": task.id,
  3828. "taskNo": task.task_no,
  3829. "status": task.status,
  3830. "effectiveTime": str(task.effective_time) if task.effective_time else None,
  3831. "message": "配送任务创建成功"
  3832. })
  3833. @router.post("/orders/{order_id}/assign-deliverer", response_model=dict)
  3834. def assign_deliverer_to_order(
  3835. order_id: str,
  3836. request: dict,
  3837. db: Session = Depends(get_db),
  3838. current_user: dict = Depends(require_admin)
  3839. ):
  3840. """分配配送员并创建配送任务(一步完成)"""
  3841. from app.crud.order import order_crud, order_item_crud
  3842. from app.crud.delivery import delivery_task_crud
  3843. order = order_crud.get(db, order_id)
  3844. if not order:
  3845. return error_response(404, "订单不存在")
  3846. # 检查订单是否被其他操作员锁定
  3847. operator_id = current_user.get("user_id")
  3848. if order.lock_operator_id and order.lock_operator_id != operator_id:
  3849. lock_time = order.lock_time.strftime("%Y-%m-%d %H:%M:%S") if order.lock_time else "未知"
  3850. return error_response(400, f"订单已被其他操作员于 {lock_time} 锁定,请先解锁后再操作")
  3851. deliver_id = request.get("deliverId")
  3852. if not deliver_id:
  3853. return error_response(400, "请选择配送员")
  3854. deadline_raw = request.get("deliveryDeadlineAt") or request.get("delivery_deadline_at")
  3855. if not deadline_raw:
  3856. return error_response(400, "请选择配送时效(截止时间)")
  3857. dispatch_remark_raw = request.get("dispatchRemark") or request.get("dispatch_remark") or ""
  3858. dispatch_remark = str(dispatch_remark_raw).strip()[:500] if dispatch_remark_raw else None
  3859. effective_deadline = None
  3860. try:
  3861. ds = str(deadline_raw).strip().replace("Z", "+00:00")
  3862. effective_deadline = datetime.fromisoformat(ds)
  3863. if effective_deadline.tzinfo is not None:
  3864. effective_deadline = effective_deadline.replace(tzinfo=None)
  3865. except (TypeError, ValueError):
  3866. effective_deadline = None
  3867. if not effective_deadline:
  3868. return error_response(400, "配送时效格式不正确")
  3869. # 验证配送员
  3870. deliver = user_crud.get(db, deliver_id)
  3871. if not deliver:
  3872. return error_response(404, "配送员不存在")
  3873. if deliver.role != "deliver":
  3874. return error_response(400, "该用户不是配送员")
  3875. if not deliver.region_id or deliver.region_id != order.region_id:
  3876. return error_response(400, "只能选择订单所属区域的配送员")
  3877. prev_delivery_status = getattr(order, "delivery_status", None) or "pending_dispatch"
  3878. operator_name = (current_user.get("real_name") or "").strip() or None
  3879. updater = {"user_id": operator_id, "real_name": operator_name}
  3880. # 检查是否已存在配送任务
  3881. existing_task = delivery_task_crud.get_by_order(db, order_id)
  3882. old_deliver_id = existing_task.deliver_id if existing_task else None
  3883. if existing_task:
  3884. task = delivery_task_crud.update_with_history(
  3885. db,
  3886. existing_task.id,
  3887. {
  3888. "deliver_id": deliver_id,
  3889. "status": "assigned",
  3890. "effective_time": effective_deadline,
  3891. "dispatch_remark": dispatch_remark,
  3892. },
  3893. updater=updater,
  3894. )
  3895. if not task:
  3896. return error_response(400, "更新配送任务失败")
  3897. else:
  3898. # 获取供应商ID
  3899. from app.crud.price_list import price_list_crud
  3900. price_list = price_list_crud.get(db, order.price_list_id)
  3901. if not price_list:
  3902. return error_response(400, "订单关联的价格清单不存在")
  3903. # 获取订单项
  3904. order_items = order_item_crud.get_by_order(db, order_id)
  3905. # 构建配送任务明细数据
  3906. task_items_data = []
  3907. for item in order_items:
  3908. if item.status == "deleted" or item.is_del != 0:
  3909. continue
  3910. task_items_data.append({
  3911. "order_item_id": item.id,
  3912. "product_id": item.product_id,
  3913. "client_id": order.client_id,
  3914. "delivery_address": order.delivery_address,
  3915. "contact_person": order.contact_person,
  3916. "contact_phone": order.contact_phone,
  3917. "quantity": float(item.quantity) if item.quantity else 0
  3918. })
  3919. creator = {
  3920. "user_id": current_user.get("user_id"),
  3921. "real_name": current_user.get("real_name")
  3922. }
  3923. # 创建配送任务
  3924. task, _ = delivery_task_crud.create_delivery_task_from_order(
  3925. db,
  3926. order_id=order_id,
  3927. order_items=task_items_data,
  3928. supplier_id=price_list.supplier_id,
  3929. region_id=order.region_id,
  3930. creator=creator
  3931. )
  3932. # 分配配送员
  3933. task.deliver_id = deliver_id
  3934. task.status = "assigned"
  3935. task.effective_time = effective_deadline
  3936. task.dispatch_remark = dispatch_remark
  3937. task.update_at = datetime.now()
  3938. # 分配配送员后同步双状态;首次分配时供应商从待备货起算,更换配送员不重置备货进度
  3939. if task and task.deliver_id:
  3940. task.deliverer_status = "pending_pickup"
  3941. if not old_deliver_id:
  3942. task.supplier_prepare_status = "pending_prepare"
  3943. delivery_task_crud._sync_legacy_status_from_dual(task)
  3944. # 阶段D收尾:优先维护三字段,再回写旧 status
  3945. from app.core.order_status_compat import derive_legacy_status_from_three
  3946. order.order_status = "pending_confirm"
  3947. if not order.delivery_status or order.delivery_status == "pending_dispatch":
  3948. order.delivery_status = "delivering"
  3949. order.status = derive_legacy_status_from_three(
  3950. order_status=order.order_status,
  3951. delivery_status=order.delivery_status,
  3952. pay_status=order.pay_status,
  3953. )
  3954. order.delivery_assign_time = datetime.now()
  3955. order.update_at = datetime.now()
  3956. def _deliver_display_name(uid: Optional[str]) -> Optional[str]:
  3957. if not uid:
  3958. return None
  3959. u = user_crud.get(db, uid)
  3960. return (u.real_name if u else None) or uid
  3961. if not existing_task:
  3962. order_crud._create_status_log(
  3963. db,
  3964. order_id,
  3965. "",
  3966. "delivery.assign",
  3967. operator_id,
  3968. "admin",
  3969. reason=json.dumps(
  3970. {
  3971. "fromDeliverId": None,
  3972. "toDeliverId": deliver_id,
  3973. "fromDeliverName": None,
  3974. "toDeliverName": deliver.real_name,
  3975. },
  3976. ensure_ascii=False,
  3977. ),
  3978. create_name=operator_name,
  3979. )
  3980. elif old_deliver_id and old_deliver_id != deliver_id:
  3981. order_crud._create_status_log(
  3982. db,
  3983. order_id,
  3984. "",
  3985. "delivery.reassign",
  3986. operator_id,
  3987. "admin",
  3988. reason=json.dumps(
  3989. {
  3990. "fromDeliverId": old_deliver_id,
  3991. "toDeliverId": deliver_id,
  3992. "fromDeliverName": _deliver_display_name(old_deliver_id),
  3993. "toDeliverName": deliver.real_name,
  3994. },
  3995. ensure_ascii=False,
  3996. ),
  3997. create_name=operator_name,
  3998. )
  3999. elif not old_deliver_id and deliver_id:
  4000. order_crud._create_status_log(
  4001. db,
  4002. order_id,
  4003. "",
  4004. "delivery.assign",
  4005. operator_id,
  4006. "admin",
  4007. reason=json.dumps(
  4008. {
  4009. "fromDeliverId": None,
  4010. "toDeliverId": deliver_id,
  4011. "fromDeliverName": None,
  4012. "toDeliverName": deliver.real_name,
  4013. },
  4014. ensure_ascii=False,
  4015. ),
  4016. create_name=operator_name,
  4017. )
  4018. if prev_delivery_status != order.delivery_status:
  4019. order_crud._create_status_log(
  4020. db,
  4021. order_id,
  4022. f"ds_{prev_delivery_status}",
  4023. f"ds_{order.delivery_status}",
  4024. operator_id,
  4025. "admin",
  4026. create_name=operator_name,
  4027. )
  4028. db.commit()
  4029. db.refresh(task)
  4030. return success_response({
  4031. "id": task.id,
  4032. "taskNo": task.task_no,
  4033. "deliverId": task.deliver_id,
  4034. "deliverName": deliver.real_name,
  4035. "status": task.status,
  4036. "effectiveTime": str(task.effective_time) if task.effective_time else None,
  4037. "message": "配送员分配成功"
  4038. })
  4039. @router.post("/orders/{order_id}/assign-delivery", response_model=dict)
  4040. def assign_delivery_alias(
  4041. order_id: str,
  4042. request: dict,
  4043. db: Session = Depends(get_db),
  4044. current_user: dict = Depends(require_admin)
  4045. ):
  4046. """兼容旧路径:与 assign-deliverer 相同"""
  4047. return assign_deliverer_to_order(order_id, request, db, current_user)
  4048. # =========================================
  4049. # 结算管理 API (Web端)
  4050. # =========================================
  4051. def _build_settlement_no(prefix: str) -> str:
  4052. return f"{prefix}{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4().hex)[:6].upper()}"
  4053. def _parse_datetime_range(start_date: Optional[str], end_date: Optional[str]):
  4054. dt_start = None
  4055. dt_end = None
  4056. if start_date:
  4057. try:
  4058. dt_start = datetime.fromisoformat(start_date.replace("Z", "+00:00"))
  4059. except Exception:
  4060. dt_start = None
  4061. if end_date:
  4062. try:
  4063. dt_end = datetime.fromisoformat(end_date.replace("Z", "+00:00"))
  4064. except Exception:
  4065. dt_end = None
  4066. return dt_start, dt_end
  4067. def _supplier_unit_yuan_from_pli(pli: Optional[BizPriceListItem]) -> Optional[float]:
  4068. """价格清单行 price 为面向客户的最终单价;pricing_coefficient 为调价系数(%),供货单价 = price / (1 + 系数/100)。"""
  4069. if pli is None or getattr(pli, "price", None) is None:
  4070. return None
  4071. final_price = Decimal(str(pli.price))
  4072. raw_coeff = getattr(pli, "pricing_coefficient", None)
  4073. if raw_coeff is None:
  4074. coeff_pct = Decimal("0")
  4075. else:
  4076. try:
  4077. coeff_pct = Decimal(str(raw_coeff))
  4078. except Exception:
  4079. coeff_pct = Decimal("0")
  4080. factor = Decimal("1") + coeff_pct / Decimal("100")
  4081. if factor <= Decimal("0"):
  4082. factor = Decimal("1")
  4083. supplier_unit = (final_price / factor).quantize(Decimal("0.01"))
  4084. return float(supplier_unit)
  4085. def _price_list_item_map(db: Session, price_list_ids: List[str]) -> dict:
  4086. """(price_list_id, product_id, unit_id) -> BizPriceListItem"""
  4087. if not price_list_ids:
  4088. return {}
  4089. rows = (
  4090. db.query(BizPriceListItem)
  4091. .filter(BizPriceListItem.price_list_id.in_(price_list_ids), BizPriceListItem.is_del == 0)
  4092. .all()
  4093. )
  4094. return {(r.price_list_id, r.product_id, r.unit_id): r for r in rows}
  4095. def _batch_supplier_totals_for_orders(db: Session, order_ids: List[str]) -> dict:
  4096. """订单维度供货价合计(元),用于供应商结算。"""
  4097. if not order_ids:
  4098. return {}
  4099. orders = db.query(BizOrder).filter(BizOrder.id.in_(order_ids), BizOrder.is_del == 0).all()
  4100. om = {o.id: o for o in orders}
  4101. lines = (
  4102. db.query(BizOrderItem)
  4103. .filter(BizOrderItem.order_id.in_(order_ids), BizOrderItem.is_del == 0)
  4104. .all()
  4105. )
  4106. by_oid: dict = {}
  4107. for ln in lines:
  4108. by_oid.setdefault(ln.order_id, []).append(ln)
  4109. pl_ids = list({om[oid].price_list_id for oid in order_ids if oid in om and om[oid].price_list_id})
  4110. pli_map = _price_list_item_map(db, pl_ids)
  4111. out: dict = {}
  4112. for oid in order_ids:
  4113. o = om.get(oid)
  4114. if not o:
  4115. out[oid] = 0.0
  4116. continue
  4117. tot = Decimal("0")
  4118. for ln in by_oid.get(oid, []):
  4119. pli = pli_map.get((o.price_list_id, ln.product_id, ln.unit_id))
  4120. sup_u = _supplier_unit_yuan_from_pli(pli)
  4121. if sup_u is None:
  4122. sup_u = float(ln.unit_price or 0)
  4123. qty = Decimal(str(ln.quantity or 0))
  4124. tot += qty * Decimal(str(sup_u))
  4125. out[oid] = float(tot.quantize(Decimal("0.01")))
  4126. return out
  4127. def _build_order_line_children_for_settlement_list(
  4128. db: Session,
  4129. order: BizOrder,
  4130. lines: List[BizOrderItem],
  4131. pli_map: dict,
  4132. product_map: dict,
  4133. unit_map: dict,
  4134. ) -> List[dict]:
  4135. children: List[dict] = []
  4136. for ln in lines:
  4137. p = product_map.get(ln.product_id)
  4138. u = unit_map.get(ln.unit_id)
  4139. pli = pli_map.get((order.price_list_id, ln.product_id, ln.unit_id))
  4140. sup_u = _supplier_unit_yuan_from_pli(pli)
  4141. if sup_u is None:
  4142. sup_u = float(ln.unit_price or 0)
  4143. sell_u = float(ln.unit_price or 0)
  4144. qty = float(ln.quantity or 0)
  4145. sell_amt = float(ln.amount or 0) if ln.amount is not None else round(qty * sell_u, 2)
  4146. sup_amt = round(qty * sup_u, 2)
  4147. img = None
  4148. if p and getattr(p, "image_url", None):
  4149. img = str(p.image_url).strip() or None
  4150. mv = None
  4151. if p is not None and p.measure_value is not None:
  4152. try:
  4153. mv = float(p.measure_value)
  4154. except (TypeError, ValueError):
  4155. mv = None
  4156. children.append({
  4157. "rowType": "line",
  4158. "id": f"line-{ln.id}",
  4159. "lineId": ln.id,
  4160. "productId": ln.product_id,
  4161. "productName": p.name if p else None,
  4162. "skuCode": p.sku_code if p else None,
  4163. "imageUrl": img,
  4164. "unitName": u.name if u else None,
  4165. "measureValue": mv,
  4166. "quantity": qty,
  4167. "sellingUnitPrice": sell_u,
  4168. "sellingAmount": sell_amt,
  4169. "supplierUnitPrice": sup_u,
  4170. "supplierAmount": sup_amt,
  4171. })
  4172. return children
  4173. def _build_client_pending_settlement_tree_rows(
  4174. db: Session,
  4175. orders: List[BizOrder],
  4176. client_map: dict,
  4177. ) -> List[dict]:
  4178. if not orders:
  4179. return []
  4180. # 避免模块级循环依赖:在需要处局部导入
  4181. from app.crud.order import order_crud
  4182. order_ids = [o.id for o in orders]
  4183. region_ids = list({o.region_id for o in orders if o.region_id})
  4184. region_map: dict = {}
  4185. for rid in region_ids:
  4186. region = region_crud.get(db, rid)
  4187. region_map[rid] = region.name if region else None
  4188. lines = (
  4189. db.query(BizOrderItem)
  4190. .filter(BizOrderItem.order_id.in_(order_ids), BizOrderItem.is_del == 0)
  4191. .order_by(BizOrderItem.order_id.asc(), BizOrderItem.create_at.asc())
  4192. .all()
  4193. )
  4194. by_oid: dict = {}
  4195. for ln in lines:
  4196. by_oid.setdefault(ln.order_id, []).append(ln)
  4197. product_ids = list({ln.product_id for ln in lines})
  4198. unit_ids = list({ln.unit_id for ln in lines})
  4199. products = (
  4200. db.query(BasProduct).filter(BasProduct.id.in_(product_ids), BasProduct.is_del == 0).all()
  4201. ) if product_ids else []
  4202. product_map = {p.id: p for p in products}
  4203. units = (
  4204. db.query(BasProductUnit).filter(BasProductUnit.id.in_(unit_ids), BasProductUnit.is_del == 0).all()
  4205. ) if unit_ids else []
  4206. unit_map = {u.id: u for u in units}
  4207. pl_ids = list({o.price_list_id for o in orders if o.price_list_id})
  4208. pli_map = _price_list_item_map(db, pl_ids)
  4209. price_lists = (
  4210. db.query(BizPriceList).filter(BizPriceList.id.in_(pl_ids), BizPriceList.is_del == 0).all()
  4211. ) if pl_ids else []
  4212. supplier_id_by_price_list = {p.id: p.supplier_id for p in price_lists}
  4213. supplier_ids = list({sid for sid in supplier_id_by_price_list.values() if sid})
  4214. suppliers = (
  4215. db.query(SysUser).filter(SysUser.id.in_(supplier_ids), SysUser.is_del == 0).all()
  4216. ) if supplier_ids else []
  4217. supplier_name_map = {u.id: (u.real_name or u.username) for u in suppliers}
  4218. out: List[dict] = []
  4219. for o in orders:
  4220. ch = _build_order_line_children_for_settlement_list(
  4221. db, o, by_oid.get(o.id, []), pli_map, product_map, unit_map
  4222. )
  4223. sup_ref = sum(c["supplierAmount"] for c in ch)
  4224. sel = o.order_status == "completed"
  4225. out.append({
  4226. "rowType": "order",
  4227. "id": o.id,
  4228. "orderNo": o.order_no,
  4229. "clientId": o.client_id,
  4230. "clientName": client_map.get(o.client_id),
  4231. "regionId": o.region_id,
  4232. "regionName": region_map.get(o.region_id),
  4233. "supplierId": supplier_id_by_price_list.get(o.price_list_id),
  4234. "supplierName": supplier_name_map.get(supplier_id_by_price_list.get(o.price_list_id)),
  4235. "totalAmount": float(o.total_amount or 0),
  4236. "settlementAmount": float(o.total_amount or 0),
  4237. "supplierReferenceTotal": round(sup_ref, 2),
  4238. "orderStatus": o.order_status,
  4239. "settlementSelectable": sel,
  4240. "paymentMethod": order_crud.normalize_payment_method(o.payment_method),
  4241. "clientSettlementStatus": o.client_settlement_status,
  4242. "supplierSettlementStatus": o.supplier_settlement_status,
  4243. "createAt": str(o.create_at) if o.create_at else None,
  4244. "children": ch,
  4245. })
  4246. return out
  4247. def _build_supplier_pending_settlement_tree_rows(
  4248. db: Session,
  4249. order_supplier_pairs: List[Tuple[BizOrder, Optional[str]]],
  4250. supplier_map: dict,
  4251. ) -> List[dict]:
  4252. if not order_supplier_pairs:
  4253. return []
  4254. # 避免模块级循环依赖:在需要处局部导入
  4255. from app.crud.order import order_crud
  4256. orders = [p[0] for p in order_supplier_pairs]
  4257. sup_by_oid = {p[0].id: p[1] for p in order_supplier_pairs}
  4258. order_ids = [o.id for o in orders]
  4259. lines = (
  4260. db.query(BizOrderItem)
  4261. .filter(BizOrderItem.order_id.in_(order_ids), BizOrderItem.is_del == 0)
  4262. .order_by(BizOrderItem.order_id.asc(), BizOrderItem.create_at.asc())
  4263. .all()
  4264. )
  4265. by_oid: dict = {}
  4266. for ln in lines:
  4267. by_oid.setdefault(ln.order_id, []).append(ln)
  4268. product_ids = list({ln.product_id for ln in lines})
  4269. unit_ids = list({ln.unit_id for ln in lines})
  4270. products = (
  4271. db.query(BasProduct).filter(BasProduct.id.in_(product_ids), BasProduct.is_del == 0).all()
  4272. ) if product_ids else []
  4273. product_map = {p.id: p for p in products}
  4274. units = (
  4275. db.query(BasProductUnit).filter(BasProductUnit.id.in_(unit_ids), BasProductUnit.is_del == 0).all()
  4276. ) if unit_ids else []
  4277. unit_map = {u.id: u for u in units}
  4278. pl_ids = list({o.price_list_id for o in orders if o.price_list_id})
  4279. pli_map = _price_list_item_map(db, pl_ids)
  4280. client_ids = list({o.client_id for o in orders if o.client_id})
  4281. client_map: dict = {}
  4282. if client_ids:
  4283. clients = db.query(SysUser).filter(SysUser.id.in_(client_ids), SysUser.is_del == 0).all()
  4284. client_map = {u.id: (u.real_name or u.username) for u in clients}
  4285. region_ids = list({o.region_id for o in orders if o.region_id})
  4286. region_map: dict = {}
  4287. for rid in region_ids:
  4288. region = region_crud.get(db, rid)
  4289. region_map[rid] = region.name if region else None
  4290. out: List[dict] = []
  4291. for o in orders:
  4292. ch = _build_order_line_children_for_settlement_list(
  4293. db, o, by_oid.get(o.id, []), pli_map, product_map, unit_map
  4294. )
  4295. sup_order_total = sum(c["supplierAmount"] for c in ch)
  4296. sel = o.order_status == "completed"
  4297. sid = sup_by_oid.get(o.id)
  4298. out.append({
  4299. "rowType": "order",
  4300. "id": o.id,
  4301. "orderNo": o.order_no,
  4302. "clientId": o.client_id,
  4303. "clientName": client_map.get(o.client_id),
  4304. "regionId": o.region_id,
  4305. "regionName": region_map.get(o.region_id),
  4306. "supplierId": sid,
  4307. "supplierName": supplier_map.get(sid) if sid else None,
  4308. "settlementAmount": round(sup_order_total, 2),
  4309. "totalAmount": float(o.total_amount or 0),
  4310. "clientSellingTotal": float(o.total_amount or 0),
  4311. "orderStatus": o.order_status,
  4312. "settlementSelectable": sel,
  4313. "supplierSettlementStatus": o.supplier_settlement_status,
  4314. "clientSettlementStatus": o.client_settlement_status,
  4315. "paymentMethod": order_crud.normalize_payment_method(o.payment_method),
  4316. "createAt": str(o.create_at) if o.create_at else None,
  4317. "children": ch,
  4318. })
  4319. return out
  4320. @router.get("/client-settlements/orders", response_model=dict)
  4321. def list_client_settlement_orders(
  4322. page: int = Query(1, ge=1),
  4323. pageSize: int = Query(10, ge=1, le=100),
  4324. clientId: Optional[str] = Query(None),
  4325. keyword: Optional[str] = Query(None, description="订单号"),
  4326. startDate: Optional[str] = Query(None),
  4327. endDate: Optional[str] = Query(None),
  4328. regionId: Optional[str] = Query(None, description="区域(Tab);超级管理员可选,区域管理员忽略"),
  4329. db: Session = Depends(get_db),
  4330. current_user: dict = Depends(require_admin),
  4331. ):
  4332. admin_region_id = get_admin_region_filter(db, current_user)
  4333. eff_region_id = _effective_settlement_region_id(admin_region_id, regionId)
  4334. dt_start, dt_end = _parse_datetime_range(startDate, endDate)
  4335. q = db.query(BizOrder).filter(
  4336. BizOrder.is_del == 0,
  4337. BizOrder.order_status != "cancelled",
  4338. BizOrder.payment_method == "offline",
  4339. BizOrder.client_settlement_status == "pending",
  4340. )
  4341. if eff_region_id:
  4342. q = q.filter(BizOrder.region_id == eff_region_id)
  4343. if clientId:
  4344. q = q.filter(BizOrder.client_id == clientId)
  4345. if keyword:
  4346. q = q.filter(BizOrder.order_no.like(f"%{keyword}%"))
  4347. if dt_start:
  4348. q = q.filter(BizOrder.create_at >= dt_start)
  4349. if dt_end:
  4350. q = q.filter(BizOrder.create_at <= dt_end)
  4351. total = q.count()
  4352. settleable_order_count = q.filter(BizOrder.order_status == "completed").count()
  4353. q_done = q.filter(BizOrder.order_status == "completed")
  4354. pending_amount = float(
  4355. q_done.with_entities(func.coalesce(func.sum(BizOrder.total_amount), 0)).scalar() or 0
  4356. )
  4357. rows = q.order_by(BizOrder.create_at.desc()).offset((page - 1) * pageSize).limit(pageSize).all()
  4358. client_ids = list({r.client_id for r in rows if r.client_id})
  4359. client_map = {}
  4360. if client_ids:
  4361. for u in db.query(SysUser).filter(SysUser.id.in_(client_ids)).all():
  4362. client_map[u.id] = u.real_name or u.username
  4363. data = _build_client_pending_settlement_tree_rows(db, rows, client_map)
  4364. current_page_amount = float(sum((o.total_amount or 0) for o in rows if o.order_status == "completed"))
  4365. return success_response({
  4366. "list": data,
  4367. "total": total,
  4368. "page": page,
  4369. "pageSize": pageSize,
  4370. "totalPages": (total + pageSize - 1) // pageSize,
  4371. "summary": {
  4372. "pendingAmount": pending_amount,
  4373. "currentPageAmount": current_page_amount,
  4374. "settleableOrderCount": settleable_order_count,
  4375. },
  4376. })
  4377. @router.get("/supplier-settlements/orders", response_model=dict)
  4378. def list_supplier_settlement_orders(
  4379. page: int = Query(1, ge=1),
  4380. pageSize: int = Query(10, ge=1, le=100),
  4381. supplierId: Optional[str] = Query(None),
  4382. keyword: Optional[str] = Query(None, description="订单号"),
  4383. startDate: Optional[str] = Query(None),
  4384. endDate: Optional[str] = Query(None),
  4385. regionId: Optional[str] = Query(None, description="区域(Tab);超级管理员可选,区域管理员忽略"),
  4386. db: Session = Depends(get_db),
  4387. current_user: dict = Depends(require_admin),
  4388. ):
  4389. admin_region_id = get_admin_region_filter(db, current_user)
  4390. eff_region_id = _effective_settlement_region_id(admin_region_id, regionId)
  4391. dt_start, dt_end = _parse_datetime_range(startDate, endDate)
  4392. q = db.query(BizOrder, BizPriceList.supplier_id).join(
  4393. BizPriceList, BizPriceList.id == BizOrder.price_list_id
  4394. ).filter(
  4395. BizOrder.is_del == 0,
  4396. BizOrder.order_status != "cancelled",
  4397. BizOrder.supplier_settlement_status == "pending",
  4398. )
  4399. if eff_region_id:
  4400. q = q.filter(BizOrder.region_id == eff_region_id)
  4401. if supplierId:
  4402. q = q.filter(BizPriceList.supplier_id == supplierId)
  4403. if keyword:
  4404. q = q.filter(BizOrder.order_no.like(f"%{keyword}%"))
  4405. if dt_start:
  4406. q = q.filter(BizOrder.create_at >= dt_start)
  4407. if dt_end:
  4408. q = q.filter(BizOrder.create_at <= dt_end)
  4409. total = q.count()
  4410. settleable_order_count = q.filter(BizOrder.order_status == "completed").count()
  4411. q_done = q.filter(BizOrder.order_status == "completed")
  4412. done_pairs = q_done.with_entities(BizOrder.id).all()
  4413. done_oids = [x[0] for x in done_pairs]
  4414. totals_map = _batch_supplier_totals_for_orders(db, done_oids)
  4415. pending_amount = float(sum(totals_map.values()))
  4416. rows = q.order_by(BizOrder.create_at.desc()).offset((page - 1) * pageSize).limit(pageSize).all()
  4417. supplier_ids = list({s_id for _, s_id in rows if s_id})
  4418. supplier_map = {}
  4419. if supplier_ids:
  4420. for u in db.query(SysUser).filter(SysUser.id.in_(supplier_ids)).all():
  4421. supplier_map[u.id] = u.real_name or u.username
  4422. data = _build_supplier_pending_settlement_tree_rows(db, rows, supplier_map)
  4423. page_done_ids = [o.id for o, _ in rows if o.order_status == "completed"]
  4424. page_totals = _batch_supplier_totals_for_orders(db, page_done_ids)
  4425. current_page_amount = float(sum(page_totals.values()))
  4426. return success_response({
  4427. "list": data,
  4428. "total": total,
  4429. "page": page,
  4430. "pageSize": pageSize,
  4431. "totalPages": (total + pageSize - 1) // pageSize,
  4432. "summary": {
  4433. "pendingAmount": pending_amount,
  4434. "currentPageAmount": current_page_amount,
  4435. "settleableOrderCount": settleable_order_count,
  4436. },
  4437. })
  4438. def _resolve_client_order_ids(db: Session, body: dict, admin_region_id: Optional[str]) -> List[str]:
  4439. selection_mode = (body.get("selectionMode") or "ids").strip()
  4440. filters = body.get("filters") or {}
  4441. eff_region = _effective_settlement_region_id(admin_region_id, filters.get("regionId"))
  4442. if selection_mode == "allFiltered":
  4443. dt_start, dt_end = _parse_datetime_range(filters.get("startDate"), filters.get("endDate"))
  4444. q = db.query(BizOrder.id).filter(
  4445. BizOrder.is_del == 0,
  4446. BizOrder.order_status != "cancelled",
  4447. BizOrder.order_status == "completed",
  4448. BizOrder.payment_method == "offline",
  4449. BizOrder.client_settlement_status == "pending",
  4450. )
  4451. if eff_region:
  4452. q = q.filter(BizOrder.region_id == eff_region)
  4453. if filters.get("clientId"):
  4454. q = q.filter(BizOrder.client_id == filters["clientId"])
  4455. if filters.get("keyword"):
  4456. q = q.filter(BizOrder.order_no.like(f"%{filters['keyword']}%"))
  4457. if dt_start:
  4458. q = q.filter(BizOrder.create_at >= dt_start)
  4459. if dt_end:
  4460. q = q.filter(BizOrder.create_at <= dt_end)
  4461. order_ids = [x[0] for x in q.all()]
  4462. excluded = set(body.get("excludedOrderIds") or [])
  4463. return [oid for oid in order_ids if oid not in excluded]
  4464. return list(set(body.get("orderIds") or []))
  4465. def _resolve_supplier_order_ids(db: Session, body: dict, admin_region_id: Optional[str]) -> List[str]:
  4466. selection_mode = (body.get("selectionMode") or "ids").strip()
  4467. filters = body.get("filters") or {}
  4468. eff_region = _effective_settlement_region_id(admin_region_id, filters.get("regionId"))
  4469. if selection_mode == "allFiltered":
  4470. dt_start, dt_end = _parse_datetime_range(filters.get("startDate"), filters.get("endDate"))
  4471. q = db.query(BizOrder.id).join(
  4472. BizPriceList, BizPriceList.id == BizOrder.price_list_id
  4473. ).filter(
  4474. BizOrder.is_del == 0,
  4475. BizOrder.order_status != "cancelled",
  4476. BizOrder.order_status == "completed",
  4477. BizOrder.supplier_settlement_status == "pending",
  4478. )
  4479. if eff_region:
  4480. q = q.filter(BizOrder.region_id == eff_region)
  4481. if filters.get("supplierId"):
  4482. q = q.filter(BizPriceList.supplier_id == filters["supplierId"])
  4483. if filters.get("keyword"):
  4484. q = q.filter(BizOrder.order_no.like(f"%{filters['keyword']}%"))
  4485. if dt_start:
  4486. q = q.filter(BizOrder.create_at >= dt_start)
  4487. if dt_end:
  4488. q = q.filter(BizOrder.create_at <= dt_end)
  4489. order_ids = [x[0] for x in q.all()]
  4490. excluded = set(body.get("excludedOrderIds") or [])
  4491. return [oid for oid in order_ids if oid not in excluded]
  4492. return list(set(body.get("orderIds") or []))
  4493. @router.post("/client-settlements", response_model=dict)
  4494. def create_client_settlement(
  4495. request: dict,
  4496. db: Session = Depends(get_db),
  4497. current_user: dict = Depends(require_admin),
  4498. ):
  4499. admin_region_id = get_admin_region_filter(db, current_user)
  4500. body = dict(request or {})
  4501. voucher_urls = body.get("voucherUrls") or []
  4502. order_ids = _resolve_client_order_ids(db, body, admin_region_id)
  4503. if not order_ids:
  4504. return error_response(400, "未选择可结算订单")
  4505. orders = db.query(BizOrder).filter(
  4506. BizOrder.id.in_(order_ids),
  4507. BizOrder.is_del == 0,
  4508. BizOrder.order_status == "completed",
  4509. BizOrder.payment_method == "offline",
  4510. BizOrder.client_settlement_status == "pending",
  4511. ).all()
  4512. if not orders:
  4513. return error_response(400, "无可结算订单")
  4514. eff_region = _effective_settlement_region_id(
  4515. admin_region_id, (body.get("filters") or {}).get("regionId")
  4516. )
  4517. if eff_region and any((o.region_id or "") != eff_region for o in orders):
  4518. return error_response(400, "存在不属于当前区域的订单")
  4519. total_amount = sum((o.total_amount or 0) for o in orders)
  4520. client_id = orders[0].client_id
  4521. if any(o.client_id != client_id for o in orders):
  4522. return error_response(400, "客户结算必须选择同一客户")
  4523. client = user_crud.get(db, client_id)
  4524. now = datetime.now()
  4525. creator = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  4526. settlement = OrdClientSettlement(
  4527. id=generate_id(),
  4528. settlement_no=_build_settlement_no("CST"),
  4529. client_id=client_id,
  4530. client_name=(client.real_name if client else None),
  4531. order_count=len(orders),
  4532. total_amount=total_amount,
  4533. voucher_urls=json.dumps(voucher_urls, ensure_ascii=False),
  4534. remark=body.get("remark"),
  4535. settlement_at=now,
  4536. status="done",
  4537. create_by=creator["user_id"],
  4538. create_name=creator["real_name"],
  4539. update_by=creator["user_id"],
  4540. )
  4541. db.add(settlement)
  4542. db.flush()
  4543. for order in orders:
  4544. db.add(OrdClientSettlementItem(
  4545. id=generate_id(),
  4546. settlement_id=settlement.id,
  4547. order_id=order.id,
  4548. order_no=order.order_no,
  4549. client_id=order.client_id,
  4550. order_amount=order.total_amount or 0,
  4551. create_by=creator["user_id"],
  4552. create_name=creator["real_name"],
  4553. update_by=creator["user_id"],
  4554. ))
  4555. order.client_settlement_status = "settled"
  4556. order.client_settlement_at = now
  4557. order.update_by = creator["user_id"]
  4558. order.update_at = now
  4559. db.commit()
  4560. return success_response({
  4561. "id": settlement.id,
  4562. "settlementNo": settlement.settlement_no,
  4563. "orderCount": settlement.order_count,
  4564. "totalAmount": float(settlement.total_amount or 0),
  4565. })
  4566. @router.post("/supplier-settlements", response_model=dict)
  4567. def create_supplier_settlement(
  4568. request: dict,
  4569. db: Session = Depends(get_db),
  4570. current_user: dict = Depends(require_admin),
  4571. ):
  4572. admin_region_id = get_admin_region_filter(db, current_user)
  4573. body = dict(request or {})
  4574. voucher_urls = body.get("voucherUrls") or []
  4575. order_ids = _resolve_supplier_order_ids(db, body, admin_region_id)
  4576. if not order_ids:
  4577. return error_response(400, "未选择可结算订单")
  4578. rows = db.query(BizOrder, BizPriceList.supplier_id).join(
  4579. BizPriceList, BizPriceList.id == BizOrder.price_list_id
  4580. ).filter(
  4581. BizOrder.id.in_(order_ids),
  4582. BizOrder.is_del == 0,
  4583. BizOrder.order_status == "completed",
  4584. BizOrder.supplier_settlement_status == "pending",
  4585. ).all()
  4586. if not rows:
  4587. return error_response(400, "无可结算订单")
  4588. eff_region = _effective_settlement_region_id(
  4589. admin_region_id, (body.get("filters") or {}).get("regionId")
  4590. )
  4591. if eff_region and any((order.region_id or "") != eff_region for order, _ in rows):
  4592. return error_response(400, "存在不属于当前区域的订单")
  4593. supplier_id = rows[0][1]
  4594. if any(s_id != supplier_id for _, s_id in rows):
  4595. return error_response(400, "商家结算必须选择同一供应商")
  4596. orders = [r[0] for r in rows]
  4597. supplier_totals = _batch_supplier_totals_for_orders(db, [o.id for o in orders])
  4598. total_amount = sum(supplier_totals.get(o.id, 0) for o in orders)
  4599. supplier = user_crud.get(db, supplier_id) if supplier_id else None
  4600. now = datetime.now()
  4601. creator = {"user_id": current_user.get("user_id"), "real_name": current_user.get("real_name")}
  4602. settlement = OrdSupplierSettlement(
  4603. id=generate_id(),
  4604. settlement_no=_build_settlement_no("SST"),
  4605. supplier_id=supplier_id,
  4606. supplier_name=(supplier.real_name if supplier else None),
  4607. order_count=len(orders),
  4608. total_amount=total_amount,
  4609. voucher_urls=json.dumps(voucher_urls, ensure_ascii=False),
  4610. remark=body.get("remark"),
  4611. settlement_at=now,
  4612. status="done",
  4613. create_by=creator["user_id"],
  4614. create_name=creator["real_name"],
  4615. update_by=creator["user_id"],
  4616. )
  4617. db.add(settlement)
  4618. db.flush()
  4619. for order in orders:
  4620. db.add(OrdSupplierSettlementItem(
  4621. id=generate_id(),
  4622. settlement_id=settlement.id,
  4623. order_id=order.id,
  4624. order_no=order.order_no,
  4625. supplier_id=supplier_id,
  4626. order_amount=supplier_totals.get(order.id, 0),
  4627. create_by=creator["user_id"],
  4628. create_name=creator["real_name"],
  4629. update_by=creator["user_id"],
  4630. ))
  4631. order.supplier_settlement_status = "settled"
  4632. order.supplier_settlement_at = now
  4633. order.update_by = creator["user_id"]
  4634. order.update_at = now
  4635. db.commit()
  4636. return success_response({
  4637. "id": settlement.id,
  4638. "settlementNo": settlement.settlement_no,
  4639. "orderCount": settlement.order_count,
  4640. "totalAmount": float(settlement.total_amount or 0),
  4641. })
  4642. def _sheet_voucher_urls_list(raw) -> list:
  4643. if not raw:
  4644. return []
  4645. if isinstance(raw, list):
  4646. return [str(x) for x in raw if x]
  4647. s = str(raw).strip()
  4648. if not s:
  4649. return []
  4650. try:
  4651. data = json.loads(s)
  4652. if isinstance(data, list):
  4653. return [str(x) for x in data if x]
  4654. except Exception:
  4655. pass
  4656. return [s]
  4657. def _build_settlement_detail_item_tree(db: Session, settlement_items: List[Any]) -> List[dict]:
  4658. """结算单明细:每个订单一行父节点,子行为订单商品行(与前端树表对应)。"""
  4659. from app.crud.order import order_crud
  4660. if not settlement_items:
  4661. return []
  4662. order_ids = list({it.order_id for it in settlement_items if getattr(it, "order_id", None)})
  4663. if not order_ids:
  4664. return []
  4665. orders = (
  4666. db.query(BizOrder)
  4667. .filter(BizOrder.id.in_(order_ids), BizOrder.is_del == 0)
  4668. .all()
  4669. )
  4670. order_map = {o.id: o for o in orders}
  4671. client_ids = list({o.client_id for o in orders if o.client_id})
  4672. client_map: dict = {}
  4673. if client_ids:
  4674. clients = db.query(SysUser).filter(SysUser.id.in_(client_ids), SysUser.is_del == 0).all()
  4675. client_map = {u.id: (u.real_name or u.username) for u in clients}
  4676. region_ids = list({o.region_id for o in orders if o.region_id})
  4677. region_map: dict = {}
  4678. for rid in region_ids:
  4679. r = region_crud.get(db, rid)
  4680. region_map[rid] = r.name if r else None
  4681. lines = (
  4682. db.query(BizOrderItem)
  4683. .filter(BizOrderItem.order_id.in_(order_ids), BizOrderItem.is_del == 0)
  4684. .order_by(BizOrderItem.order_id.asc(), BizOrderItem.create_at.asc())
  4685. .all()
  4686. )
  4687. by_order: dict = {}
  4688. for ln in lines:
  4689. by_order.setdefault(ln.order_id, []).append(ln)
  4690. product_ids = list({ln.product_id for ln in lines})
  4691. unit_ids = list({ln.unit_id for ln in lines})
  4692. products = (
  4693. db.query(BasProduct)
  4694. .filter(BasProduct.id.in_(product_ids), BasProduct.is_del == 0)
  4695. .all()
  4696. ) if product_ids else []
  4697. product_map = {p.id: p for p in products}
  4698. category_ids = list({p.category_id for p in products if p.category_id})
  4699. category_map: dict = {}
  4700. for cid in category_ids:
  4701. c = category_crud.get(db, cid)
  4702. category_map[cid] = c.name if c else None
  4703. units = (
  4704. db.query(BasProductUnit)
  4705. .filter(BasProductUnit.id.in_(unit_ids), BasProductUnit.is_del == 0)
  4706. .all()
  4707. ) if unit_ids else []
  4708. unit_map = {u.id: u for u in units}
  4709. pl_ids = list({o.price_list_id for o in order_map.values() if o and o.price_list_id})
  4710. pli_map = _price_list_item_map(db, pl_ids)
  4711. out: List[dict] = []
  4712. for it in settlement_items:
  4713. order = order_map.get(it.order_id)
  4714. rid = order.region_id if order else None
  4715. children: List[dict] = []
  4716. for ln in by_order.get(it.order_id, []):
  4717. p = product_map.get(ln.product_id)
  4718. u = unit_map.get(ln.unit_id)
  4719. img = None
  4720. if p and getattr(p, "image_url", None):
  4721. img = str(p.image_url).strip() or None
  4722. mv = None
  4723. if p is not None and p.measure_value is not None:
  4724. try:
  4725. mv = float(p.measure_value)
  4726. except (TypeError, ValueError):
  4727. mv = None
  4728. pli = pli_map.get((order.price_list_id, ln.product_id, ln.unit_id)) if order else None
  4729. sup_u = _supplier_unit_yuan_from_pli(pli)
  4730. if sup_u is None:
  4731. sup_u = float(ln.unit_price or 0)
  4732. sell_u = float(ln.unit_price or 0)
  4733. qty = float(ln.quantity or 0)
  4734. sell_amt = float(ln.amount or 0) if ln.amount is not None else round(qty * sell_u, 2)
  4735. sup_amt = round(qty * sup_u, 2)
  4736. children.append({
  4737. "rowType": "line",
  4738. "id": f"line-{ln.id}",
  4739. "lineId": ln.id,
  4740. "productId": ln.product_id,
  4741. "productName": p.name if p else None,
  4742. "skuCode": p.sku_code if p else None,
  4743. "imageUrl": img,
  4744. "categoryName": category_map.get(p.category_id) if p and p.category_id else None,
  4745. "unitName": u.name if u else None,
  4746. "measureValue": mv,
  4747. "quantity": qty,
  4748. "unitPrice": sell_u,
  4749. "amount": sell_amt,
  4750. "sellingUnitPrice": sell_u,
  4751. "sellingAmount": sell_amt,
  4752. "supplierUnitPrice": sup_u,
  4753. "supplierAmount": sup_amt,
  4754. "deliveredQuantity": float(ln.delivered_quantity or 0),
  4755. "note": ln.note,
  4756. })
  4757. out.append({
  4758. "rowType": "order",
  4759. "id": f"order-{it.id}",
  4760. "settlementItemId": it.id,
  4761. "orderId": it.order_id,
  4762. "orderNo": it.order_no,
  4763. "orderAmount": float(it.order_amount or 0),
  4764. "totalAmount": float(it.order_amount or 0),
  4765. "clientId": order.client_id if order else None,
  4766. "clientName": client_map.get(order.client_id) if order else None,
  4767. "regionId": rid,
  4768. "regionName": region_map.get(rid),
  4769. "orderCreateAt": str(order.create_at) if order and order.create_at else None,
  4770. "contactPerson": order.contact_person if order else None,
  4771. "contactPhone": order.contact_phone if order else None,
  4772. "deliveryAddress": order.delivery_address if order else None,
  4773. "orderStatus": order.order_status if order else None,
  4774. "paymentMethod": order_crud.normalize_payment_method(order.payment_method) if order else None,
  4775. "createAt": str(it.create_at) if it.create_at else None,
  4776. "children": children,
  4777. })
  4778. return out
  4779. @router.get("/client-settlements/sheets", response_model=dict)
  4780. def list_client_settlement_sheets(
  4781. page: int = Query(1, ge=1),
  4782. pageSize: int = Query(10, ge=1, le=100),
  4783. clientId: Optional[str] = Query(None),
  4784. settlementNo: Optional[str] = Query(None),
  4785. startDate: Optional[str] = Query(None),
  4786. endDate: Optional[str] = Query(None),
  4787. regionId: Optional[str] = Query(None, description="区域(Tab);超级管理员可选"),
  4788. db: Session = Depends(get_db),
  4789. current_user: dict = Depends(require_admin),
  4790. ):
  4791. """客户结算单(批次)列表"""
  4792. from app.crud.ord_settlement import ord_client_settlement_crud
  4793. admin_region_id = get_admin_region_filter(db, current_user)
  4794. eff_region_id = _effective_settlement_region_id(admin_region_id, regionId)
  4795. dt_start, dt_end = _parse_datetime_range(startDate, endDate)
  4796. rows, total = ord_client_settlement_crud.get_multi_with_filters(
  4797. db,
  4798. client_id=clientId,
  4799. settlement_no=settlementNo,
  4800. start_date=dt_start,
  4801. end_date=dt_end,
  4802. region_id=eff_region_id,
  4803. skip=(page - 1) * pageSize,
  4804. limit=pageSize,
  4805. )
  4806. out = []
  4807. for s in rows:
  4808. out.append({
  4809. "id": s.id,
  4810. "settlementNo": s.settlement_no,
  4811. "clientId": s.client_id,
  4812. "clientName": s.client_name,
  4813. "orderCount": s.order_count,
  4814. "totalAmount": float(s.total_amount or 0),
  4815. "settlementAt": str(s.settlement_at) if s.settlement_at else None,
  4816. "status": s.status,
  4817. "remark": s.remark,
  4818. "createAt": str(s.create_at) if s.create_at else None,
  4819. "createName": s.create_name,
  4820. })
  4821. return success_response({
  4822. "list": out,
  4823. "total": total,
  4824. "page": page,
  4825. "pageSize": pageSize,
  4826. "totalPages": (total + pageSize - 1) // pageSize,
  4827. })
  4828. @router.get("/client-settlements/sheets/{sheet_id}", response_model=dict)
  4829. def get_client_settlement_sheet_detail(
  4830. sheet_id: str,
  4831. db: Session = Depends(get_db),
  4832. current_user: dict = Depends(require_admin),
  4833. ):
  4834. """客户结算单详情(含明细订单)"""
  4835. from app.crud.ord_settlement import ord_client_settlement_crud
  4836. admin_region_id = get_admin_region_filter(db, current_user)
  4837. main, items = ord_client_settlement_crud.get_with_items(db, sheet_id)
  4838. if not main:
  4839. return error_response(404, "结算单不存在")
  4840. if admin_region_id and not ord_client_settlement_crud.belongs_to_region(db, sheet_id, admin_region_id):
  4841. return error_response(403, "无权限查看该结算单")
  4842. item_out = _build_settlement_detail_item_tree(db, items)
  4843. return success_response({
  4844. "id": main.id,
  4845. "settlementNo": main.settlement_no,
  4846. "clientId": main.client_id,
  4847. "clientName": main.client_name,
  4848. "orderCount": main.order_count,
  4849. "totalAmount": float(main.total_amount or 0),
  4850. "voucherUrls": _sheet_voucher_urls_list(main.voucher_urls),
  4851. "remark": main.remark,
  4852. "settlementAt": str(main.settlement_at) if main.settlement_at else None,
  4853. "status": main.status,
  4854. "createAt": str(main.create_at) if main.create_at else None,
  4855. "createName": main.create_name,
  4856. "items": item_out,
  4857. })
  4858. @router.put("/client-settlements/sheets/{sheet_id}", response_model=dict)
  4859. def update_client_settlement_sheet(
  4860. sheet_id: str,
  4861. request: dict,
  4862. db: Session = Depends(get_db),
  4863. current_user: dict = Depends(require_admin),
  4864. ):
  4865. """更新客户结算单(备注/凭证);UPDATE 前写入 ord_client_settlement_his"""
  4866. from app.crud.ord_settlement import ord_client_settlement_crud
  4867. admin_region_id = get_admin_region_filter(db, current_user)
  4868. if admin_region_id and not ord_client_settlement_crud.belongs_to_region(db, sheet_id, admin_region_id):
  4869. return error_response(403, "无权限操作该结算单")
  4870. body = dict(request or {})
  4871. update_data = {}
  4872. if "remark" in body:
  4873. update_data["remark"] = body.get("remark")
  4874. if "voucherUrls" in body:
  4875. urls = body.get("voucherUrls") or []
  4876. if not isinstance(urls, list):
  4877. return error_response(400, "voucherUrls 须为数组")
  4878. update_data["voucher_urls"] = json.dumps(urls, ensure_ascii=False)
  4879. if not update_data:
  4880. return error_response(400, "无可更新字段")
  4881. updater = {"user_id": current_user.get("user_id")}
  4882. row = ord_client_settlement_crud.update_with_history(db, sheet_id, update_data, updater)
  4883. if not row:
  4884. return error_response(404, "结算单不存在")
  4885. return success_response({
  4886. "id": row.id,
  4887. "settlementNo": row.settlement_no,
  4888. "remark": row.remark,
  4889. "voucherUrls": _sheet_voucher_urls_list(row.voucher_urls),
  4890. })
  4891. @router.get("/supplier-settlements/sheets", response_model=dict)
  4892. def list_supplier_settlement_sheets(
  4893. page: int = Query(1, ge=1),
  4894. pageSize: int = Query(10, ge=1, le=100),
  4895. supplierId: Optional[str] = Query(None),
  4896. settlementNo: Optional[str] = Query(None),
  4897. startDate: Optional[str] = Query(None),
  4898. endDate: Optional[str] = Query(None),
  4899. regionId: Optional[str] = Query(None, description="区域(Tab);超级管理员可选"),
  4900. db: Session = Depends(get_db),
  4901. current_user: dict = Depends(require_admin),
  4902. ):
  4903. """供应商结算单(批次)列表"""
  4904. from app.crud.ord_settlement import ord_supplier_settlement_crud
  4905. admin_region_id = get_admin_region_filter(db, current_user)
  4906. eff_region_id = _effective_settlement_region_id(admin_region_id, regionId)
  4907. dt_start, dt_end = _parse_datetime_range(startDate, endDate)
  4908. rows, total = ord_supplier_settlement_crud.get_multi_with_filters(
  4909. db,
  4910. supplier_id=supplierId,
  4911. settlement_no=settlementNo,
  4912. start_date=dt_start,
  4913. end_date=dt_end,
  4914. region_id=eff_region_id,
  4915. skip=(page - 1) * pageSize,
  4916. limit=pageSize,
  4917. )
  4918. out = []
  4919. for s in rows:
  4920. out.append({
  4921. "id": s.id,
  4922. "settlementNo": s.settlement_no,
  4923. "supplierId": s.supplier_id,
  4924. "supplierName": s.supplier_name,
  4925. "orderCount": s.order_count,
  4926. "totalAmount": float(s.total_amount or 0),
  4927. "settlementAt": str(s.settlement_at) if s.settlement_at else None,
  4928. "status": s.status,
  4929. "remark": s.remark,
  4930. "createAt": str(s.create_at) if s.create_at else None,
  4931. "createName": s.create_name,
  4932. })
  4933. return success_response({
  4934. "list": out,
  4935. "total": total,
  4936. "page": page,
  4937. "pageSize": pageSize,
  4938. "totalPages": (total + pageSize - 1) // pageSize,
  4939. })
  4940. @router.get("/supplier-settlements/sheets/{sheet_id}", response_model=dict)
  4941. def get_supplier_settlement_sheet_detail(
  4942. sheet_id: str,
  4943. db: Session = Depends(get_db),
  4944. current_user: dict = Depends(require_admin),
  4945. ):
  4946. """供应商结算单详情(含明细订单)"""
  4947. from app.crud.ord_settlement import ord_supplier_settlement_crud
  4948. admin_region_id = get_admin_region_filter(db, current_user)
  4949. main, items = ord_supplier_settlement_crud.get_with_items(db, sheet_id)
  4950. if not main:
  4951. return error_response(404, "结算单不存在")
  4952. if admin_region_id and not ord_supplier_settlement_crud.belongs_to_region(db, sheet_id, admin_region_id):
  4953. return error_response(403, "无权限查看该结算单")
  4954. item_out = _build_settlement_detail_item_tree(db, items)
  4955. return success_response({
  4956. "id": main.id,
  4957. "settlementNo": main.settlement_no,
  4958. "supplierId": main.supplier_id,
  4959. "supplierName": main.supplier_name,
  4960. "orderCount": main.order_count,
  4961. "totalAmount": float(main.total_amount or 0),
  4962. "voucherUrls": _sheet_voucher_urls_list(main.voucher_urls),
  4963. "remark": main.remark,
  4964. "settlementAt": str(main.settlement_at) if main.settlement_at else None,
  4965. "status": main.status,
  4966. "createAt": str(main.create_at) if main.create_at else None,
  4967. "createName": main.create_name,
  4968. "items": item_out,
  4969. })
  4970. @router.put("/supplier-settlements/sheets/{sheet_id}", response_model=dict)
  4971. def update_supplier_settlement_sheet(
  4972. sheet_id: str,
  4973. request: dict,
  4974. db: Session = Depends(get_db),
  4975. current_user: dict = Depends(require_admin),
  4976. ):
  4977. """更新供应商结算单(备注/凭证);UPDATE 前写入 ord_supplier_settlement_his"""
  4978. from app.crud.ord_settlement import ord_supplier_settlement_crud
  4979. admin_region_id = get_admin_region_filter(db, current_user)
  4980. if admin_region_id and not ord_supplier_settlement_crud.belongs_to_region(db, sheet_id, admin_region_id):
  4981. return error_response(403, "无权限操作该结算单")
  4982. body = dict(request or {})
  4983. update_data = {}
  4984. if "remark" in body:
  4985. update_data["remark"] = body.get("remark")
  4986. if "voucherUrls" in body:
  4987. urls = body.get("voucherUrls") or []
  4988. if not isinstance(urls, list):
  4989. return error_response(400, "voucherUrls 须为数组")
  4990. update_data["voucher_urls"] = json.dumps(urls, ensure_ascii=False)
  4991. if not update_data:
  4992. return error_response(400, "无可更新字段")
  4993. updater = {"user_id": current_user.get("user_id")}
  4994. row = ord_supplier_settlement_crud.update_with_history(db, sheet_id, update_data, updater)
  4995. if not row:
  4996. return error_response(404, "结算单不存在")
  4997. return success_response({
  4998. "id": row.id,
  4999. "settlementNo": row.settlement_no,
  5000. "remark": row.remark,
  5001. "voucherUrls": _sheet_voucher_urls_list(row.voucher_urls),
  5002. })
  5003. @router.get("/settlements", response_model=dict)
  5004. def list_settlements(
  5005. page: int = Query(1, ge=1, description="页码"),
  5006. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5007. regionId: Optional[str] = Query(None, description="区域ID"),
  5008. clientId: Optional[str] = Query(None, description="客户ID"),
  5009. status: Optional[str] = Query(None, description="状态"),
  5010. startDate: Optional[str] = Query(None, description="开始日期"),
  5011. endDate: Optional[str] = Query(None, description="结束日期"),
  5012. db: Session = Depends(get_db),
  5013. current_user: dict = Depends(require_admin)
  5014. ):
  5015. """获取线下结算订单列表"""
  5016. from app.crud.settlement import settlement_crud
  5017. settlements, total = settlement_crud.get_multi_with_filters(
  5018. db,
  5019. region_id=regionId,
  5020. client_id=clientId,
  5021. status=status,
  5022. start_date=startDate,
  5023. end_date=endDate,
  5024. skip=(page - 1) * pageSize,
  5025. limit=pageSize
  5026. )
  5027. region_map = {}
  5028. client_map = {}
  5029. result = []
  5030. for settlement in settlements:
  5031. if settlement.region_id and settlement.region_id not in region_map:
  5032. region = region_crud.get(db, settlement.region_id)
  5033. region_map[settlement.region_id] = region.name if region else None
  5034. if settlement.client_id and settlement.client_id not in client_map:
  5035. client = user_crud.get(db, settlement.client_id)
  5036. client_map[settlement.client_id] = client.real_name if client else None
  5037. result.append({
  5038. "id": settlement.id,
  5039. "orderId": settlement.order_id,
  5040. "clientId": settlement.client_id,
  5041. "clientName": client_map.get(settlement.client_id),
  5042. "regionId": settlement.region_id,
  5043. "regionName": region_map.get(settlement.region_id),
  5044. "amount": float(settlement.amount) if settlement.amount else 0,
  5045. "settlementMethod": settlement.settlement_method,
  5046. "settlementTime": str(settlement.settlement_time) if settlement.settlement_time else None,
  5047. "settlementNote": settlement.settlement_note,
  5048. "status": settlement.status,
  5049. "reviewedBy": settlement.reviewed_by,
  5050. "reviewedTime": str(settlement.reviewed_time) if settlement.reviewed_time else None,
  5051. "createAt": str(settlement.create_at) if settlement.create_at else None
  5052. })
  5053. return success_response({
  5054. "list": result,
  5055. "total": total,
  5056. "page": page,
  5057. "pageSize": pageSize,
  5058. "totalPages": (total + pageSize - 1) // pageSize
  5059. })
  5060. @router.get("/settlements/client-summary", response_model=dict)
  5061. def get_client_summary(
  5062. page: int = Query(1, ge=1, description="页码"),
  5063. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5064. regionId: Optional[str] = Query(None, description="区域ID"),
  5065. clientId: Optional[str] = Query(None, description="客户ID"),
  5066. db: Session = Depends(get_db),
  5067. current_user: dict = Depends(require_admin)
  5068. ):
  5069. """获取客户待结算汇总"""
  5070. from app.crud.settlement import settlement_crud
  5071. summaries, total = settlement_crud.get_client_summary(
  5072. db,
  5073. region_id=regionId,
  5074. client_id=clientId,
  5075. skip=(page - 1) * pageSize,
  5076. limit=pageSize
  5077. )
  5078. result = []
  5079. for summary in summaries:
  5080. client = user_crud.get(db, summary["client_id"])
  5081. result.append({
  5082. "clientId": summary["client_id"],
  5083. "clientName": client.real_name if client else None,
  5084. "orderCount": summary["order_count"],
  5085. "totalUnpaid": float(summary["total_unpaid"]) if summary["total_unpaid"] else 0
  5086. })
  5087. return success_response({
  5088. "list": result,
  5089. "total": total,
  5090. "page": page,
  5091. "pageSize": pageSize,
  5092. "totalPages": (total + pageSize - 1) // pageSize
  5093. })
  5094. @router.post("/settlements", response_model=dict)
  5095. def create_settlement(
  5096. request: dict,
  5097. db: Session = Depends(get_db),
  5098. current_user: dict = Depends(require_admin)
  5099. ):
  5100. """确认线下结算"""
  5101. from app.crud.settlement import settlement_crud
  5102. from datetime import datetime
  5103. from decimal import Decimal
  5104. order_id = request.get("orderId")
  5105. settlement_method = request.get("settlementMethod")
  5106. settlement_time_str = request.get("settlementTime")
  5107. note = request.get("settlementNote")
  5108. attachment_url = request.get("attachmentUrl")
  5109. if not order_id:
  5110. return error_response(400, "请选择订单")
  5111. if not settlement_method:
  5112. return error_response(400, "请选择结算方式")
  5113. # 获取订单信息
  5114. from app.models.models import BizOrder
  5115. order = db.query(BizOrder).filter(BizOrder.id == order_id).first()
  5116. if not order:
  5117. return error_response(404, "订单不存在")
  5118. # 计算未付金额
  5119. unpaid_amount = (order.receivable_amount or Decimal("0")) - (order.paid_amount or Decimal("0"))
  5120. if unpaid_amount <= 0:
  5121. return error_response(400, "该订单已无欠款,无需结算")
  5122. # 解析结算时间
  5123. settlement_time = None
  5124. if settlement_time_str:
  5125. try:
  5126. settlement_time = datetime.fromisoformat(settlement_time_str.replace("Z", "+00:00"))
  5127. except:
  5128. settlement_time = datetime.now()
  5129. creator = {
  5130. "user_id": current_user.get("user_id"),
  5131. "real_name": current_user.get("real_name")
  5132. }
  5133. settlement = settlement_crud.create_settlement(
  5134. db,
  5135. order_id=order_id,
  5136. client_id=order.client_id,
  5137. region_id=order.region_id,
  5138. amount=unpaid_amount,
  5139. settlement_method=settlement_method,
  5140. settlement_time=settlement_time,
  5141. attachment_url=attachment_url,
  5142. note=note,
  5143. creator=creator
  5144. )
  5145. return success_response({
  5146. "id": settlement.id,
  5147. "message": "结算成功"
  5148. })
  5149. @router.post("/settlements/batch", response_model=dict)
  5150. def batch_create_settlements(
  5151. request: dict,
  5152. db: Session = Depends(get_db),
  5153. current_user: dict = Depends(require_admin)
  5154. ):
  5155. """批量确认线下结算"""
  5156. from app.crud.settlement import settlement_crud
  5157. from datetime import datetime
  5158. order_ids = request.get("orderIds", [])
  5159. settlement_method = request.get("settlementMethod")
  5160. settlement_time_str = request.get("settlementTime")
  5161. note = request.get("settlementNote")
  5162. attachment_url = request.get("attachmentUrl")
  5163. if not order_ids:
  5164. return error_response(400, "请选择要结算的订单")
  5165. if not settlement_method:
  5166. return error_response(400, "请选择结算方式")
  5167. if len(order_ids) > 50:
  5168. return error_response(400, "单次最多结算50个订单")
  5169. # 解析结算时间
  5170. settlement_time = None
  5171. if settlement_time_str:
  5172. try:
  5173. settlement_time = datetime.fromisoformat(settlement_time_str.replace("Z", "+00:00"))
  5174. except:
  5175. settlement_time = datetime.now()
  5176. creator = {
  5177. "user_id": current_user.get("user_id"),
  5178. "real_name": current_user.get("real_name")
  5179. }
  5180. settlements = settlement_crud.batch_create_settlements(
  5181. db,
  5182. order_ids=order_ids,
  5183. settlement_method=settlement_method,
  5184. settlement_time=settlement_time,
  5185. attachment_url=attachment_url,
  5186. note=note,
  5187. creator=creator
  5188. )
  5189. return success_response({
  5190. "count": len(settlements),
  5191. "message": f"成功结算{len(settlements)}个订单"
  5192. })
  5193. @router.get("/settlements/records", response_model=dict)
  5194. def list_settlement_records(
  5195. page: int = Query(1, ge=1, description="页码"),
  5196. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5197. regionId: Optional[str] = Query(None, description="区域ID"),
  5198. clientId: Optional[str] = Query(None, description="客户ID"),
  5199. startDate: Optional[str] = Query(None, description="开始日期"),
  5200. endDate: Optional[str] = Query(None, description="结束日期"),
  5201. db: Session = Depends(get_db),
  5202. current_user: dict = Depends(require_admin)
  5203. ):
  5204. """获取结算记录列表"""
  5205. from app.crud.settlement import settlement_crud
  5206. settlements, total = settlement_crud.get_multi_with_filters(
  5207. db,
  5208. region_id=regionId,
  5209. client_id=clientId,
  5210. status="confirmed",
  5211. start_date=startDate,
  5212. end_date=endDate,
  5213. skip=(page - 1) * pageSize,
  5214. limit=pageSize
  5215. )
  5216. region_map = {}
  5217. client_map = {}
  5218. reviewer_map = {}
  5219. result = []
  5220. for settlement in settlements:
  5221. if settlement.region_id and settlement.region_id not in region_map:
  5222. region = region_crud.get(db, settlement.region_id)
  5223. region_map[settlement.region_id] = region.name if region else None
  5224. if settlement.client_id and settlement.client_id not in client_map:
  5225. client = user_crud.get(db, settlement.client_id)
  5226. client_map[settlement.client_id] = client.real_name if client else None
  5227. if settlement.reviewed_by and settlement.reviewed_by not in reviewer_map:
  5228. reviewer = user_crud.get(db, settlement.reviewed_by)
  5229. reviewer_map[settlement.reviewed_by] = reviewer.real_name if reviewer else None
  5230. result.append({
  5231. "id": settlement.id,
  5232. "orderId": settlement.order_id,
  5233. "clientId": settlement.client_id,
  5234. "clientName": client_map.get(settlement.client_id),
  5235. "regionId": settlement.region_id,
  5236. "regionName": region_map.get(settlement.region_id),
  5237. "amount": float(settlement.amount) if settlement.amount else 0,
  5238. "settlementMethod": settlement.settlement_method,
  5239. "settlementTime": str(settlement.settlement_time) if settlement.settlement_time else None,
  5240. "settlementNote": settlement.settlement_note,
  5241. "settlementFileUrl": settlement.settlement_file_url,
  5242. "reviewedBy": settlement.reviewed_by,
  5243. "reviewedByName": reviewer_map.get(settlement.reviewed_by),
  5244. "reviewedTime": str(settlement.reviewed_time) if settlement.reviewed_time else None,
  5245. "createAt": str(settlement.create_at) if settlement.create_at else None
  5246. })
  5247. return success_response({
  5248. "list": result,
  5249. "total": total,
  5250. "page": page,
  5251. "pageSize": pageSize,
  5252. "totalPages": (total + pageSize - 1) // pageSize
  5253. })
  5254. @router.get("/settlements/statistics", response_model=dict)
  5255. def get_settlement_statistics(
  5256. regionId: Optional[str] = Query(None, description="区域ID"),
  5257. startDate: Optional[str] = Query(None, description="开始日期"),
  5258. endDate: Optional[str] = Query(None, description="结束日期"),
  5259. db: Session = Depends(get_db),
  5260. current_user: dict = Depends(require_admin)
  5261. ):
  5262. """获取结算统计数据"""
  5263. from app.crud.settlement import settlement_crud
  5264. # 区域管理员只能查看自己区域的统计数据
  5265. admin_region_id = get_admin_region_filter(db, current_user)
  5266. if admin_region_id and not regionId:
  5267. regionId = admin_region_id
  5268. elif admin_region_id and regionId != admin_region_id:
  5269. return success_response({
  5270. "pendingOrderCount": 0,
  5271. "pendingAmount": 0,
  5272. "settledCount": 0,
  5273. "settledAmount": 0,
  5274. "refundPendingCount": 0
  5275. })
  5276. stats = settlement_crud.get_statistics(
  5277. db,
  5278. region_id=regionId,
  5279. start_date=startDate,
  5280. end_date=endDate
  5281. )
  5282. return success_response(stats)
  5283. # =========================================
  5284. # 退款管理 API (Web端)
  5285. # =========================================
  5286. @router.get("/refunds", response_model=dict)
  5287. def list_refunds(
  5288. page: int = Query(1, ge=1, description="页码"),
  5289. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5290. regionId: Optional[str] = Query(None, description="区域ID"),
  5291. status: Optional[str] = Query(None, description="状态"),
  5292. orderNo: Optional[str] = Query(None, description="订单号"),
  5293. refundMethod: Optional[str] = Query(None, description="退款方式"),
  5294. startDate: Optional[str] = Query(None, description="开始日期"),
  5295. endDate: Optional[str] = Query(None, description="结束日期"),
  5296. db: Session = Depends(get_db),
  5297. current_user: dict = Depends(require_admin)
  5298. ):
  5299. """获取退款记录列表"""
  5300. from app.crud.settlement import refund_crud
  5301. from app.models.models import BizOrder
  5302. refunds, total = refund_crud.get_multi_with_filters(
  5303. db,
  5304. region_id=regionId,
  5305. order_no=orderNo,
  5306. status=status,
  5307. refund_method=refundMethod,
  5308. start_date=startDate,
  5309. end_date=endDate,
  5310. skip=(page - 1) * pageSize,
  5311. limit=pageSize
  5312. )
  5313. order_map = {}
  5314. result = []
  5315. for refund in refunds:
  5316. if refund.order_id and refund.order_id not in order_map:
  5317. order = db.query(BizOrder).filter(BizOrder.id == refund.order_id).first()
  5318. if order:
  5319. client = user_crud.get(db, order.client_id)
  5320. order_map[refund.order_id] = {
  5321. "orderNo": order.order_no,
  5322. "clientId": order.client_id,
  5323. "clientName": client.real_name if client else None,
  5324. "regionId": order.region_id,
  5325. "totalAmount": float(order.total_amount) if order.total_amount else 0,
  5326. "paidAmount": float(order.paid_amount) if order.paid_amount else 0
  5327. }
  5328. order_info = order_map.get(refund.order_id, {})
  5329. result.append({
  5330. "id": refund.id,
  5331. "orderId": refund.order_id,
  5332. "orderNo": order_info.get("orderNo"),
  5333. "clientId": order_info.get("clientId"),
  5334. "clientName": order_info.get("clientName"),
  5335. "regionId": order_info.get("regionId"),
  5336. "totalAmount": order_info.get("totalAmount"),
  5337. "paidAmount": order_info.get("paidAmount"),
  5338. "refundNo": refund.refund_no,
  5339. "refundAmount": float(refund.refund_amount) if refund.refund_amount else 0,
  5340. "refundMethod": refund.refund_method,
  5341. "refundResult": refund.refund_result,
  5342. "refundTime": str(refund.refund_time) if refund.refund_time else None,
  5343. "refundNoWechat": refund.refund_no_wechat,
  5344. "refundFailReason": refund.refund_fail_reason,
  5345. "status": refund.status,
  5346. "createAt": str(refund.create_at) if refund.create_at else None
  5347. })
  5348. return success_response({
  5349. "list": result,
  5350. "total": total,
  5351. "page": page,
  5352. "pageSize": pageSize,
  5353. "totalPages": (total + pageSize - 1) // pageSize
  5354. })
  5355. @router.get("/refunds/{refund_id}", response_model=dict)
  5356. def get_refund(
  5357. refund_id: str,
  5358. db: Session = Depends(get_db),
  5359. current_user: dict = Depends(require_admin)
  5360. ):
  5361. """获取退款详情"""
  5362. from app.crud.settlement import refund_crud
  5363. from app.models.models import BizOrder
  5364. refund = refund_crud.get(db, refund_id)
  5365. if not refund:
  5366. return error_response(404, "退款记录不存在")
  5367. order = db.query(BizOrder).filter(BizOrder.id == refund.order_id).first()
  5368. client = user_crud.get(db, order.client_id) if order else None
  5369. return success_response({
  5370. "id": refund.id,
  5371. "orderId": refund.order_id,
  5372. "orderNo": order.order_no if order else None,
  5373. "clientId": order.client_id if order else None,
  5374. "clientName": client.real_name if client else None,
  5375. "totalAmount": float(order.total_amount) if order and order.total_amount else 0,
  5376. "paidAmount": float(order.paid_amount) if order and order.paid_amount else 0,
  5377. "refundNo": refund.refund_no,
  5378. "refundAmount": float(refund.refund_amount) if refund.refund_amount else 0,
  5379. "refundMethod": refund.refund_method,
  5380. "refundResult": refund.refund_result,
  5381. "refundTime": str(refund.refund_time) if refund.refund_time else None,
  5382. "refundNoWechat": refund.refund_no_wechat,
  5383. "refundFailReason": refund.refund_fail_reason,
  5384. "status": refund.status,
  5385. "createAt": str(refund.create_at) if refund.create_at else None,
  5386. "createName": refund.create_name
  5387. })
  5388. @router.post("/refunds/wechat-refund/{order_id}", response_model=dict)
  5389. def create_wechat_refund(
  5390. order_id: str,
  5391. request: dict,
  5392. db: Session = Depends(get_db),
  5393. current_user: dict = Depends(require_admin)
  5394. ):
  5395. """微信退款"""
  5396. from app.crud.settlement import refund_crud
  5397. from datetime import datetime
  5398. from decimal import Decimal
  5399. refund_amount = request.get("refundAmount")
  5400. reason = request.get("reason")
  5401. if not refund_amount or refund_amount <= 0:
  5402. return error_response(400, "退款金额必须大于0")
  5403. # 获取订单信息
  5404. from app.models.models import BizOrder
  5405. order = db.query(BizOrder).filter(BizOrder.id == order_id).first()
  5406. if not order:
  5407. return error_response(404, "订单不存在")
  5408. # 检查已支付金额
  5409. paid_amount = float(order.paid_amount) if order.paid_amount else 0
  5410. if refund_amount > paid_amount:
  5411. return error_response(400, "退款金额不能超过已支付金额")
  5412. # 检查是否有处理中的退款
  5413. existing_refunds = refund_crud.get_by_order(db, order_id)
  5414. processing_refund = any(r.status in ["pending", "processing"] for r in existing_refunds)
  5415. if processing_refund:
  5416. return error_response(400, "该订单有退款正在处理中,请勿重复提交")
  5417. creator = {
  5418. "user_id": current_user.get("user_id"),
  5419. "real_name": current_user.get("real_name")
  5420. }
  5421. refund = refund_crud.create_refund(
  5422. db,
  5423. order_id=order_id,
  5424. refund_amount=Decimal(str(refund_amount)),
  5425. refund_method="wechat",
  5426. reason=reason,
  5427. creator=creator
  5428. )
  5429. # 模拟微信退款处理(实际项目中需要调用微信支付API)
  5430. refund_crud.process_refund(
  5431. db,
  5432. refund_id=refund.id,
  5433. refund_result="success",
  5434. refund_no_wechat=f"WXREF{datetime.now().strftime('%Y%m%d%H%M%S')}"
  5435. )
  5436. return success_response({
  5437. "refundId": refund.id,
  5438. "refundNo": refund.refund_no,
  5439. "refundAmount": float(refund.refund_amount),
  5440. "refundResult": "success",
  5441. "refundTime": str(refund.refund_time)
  5442. })
  5443. @router.get("/refunds/{refund_id}/status", response_model=dict)
  5444. def get_refund_status(
  5445. refund_id: str,
  5446. db: Session = Depends(get_db),
  5447. current_user: dict = Depends(require_admin)
  5448. ):
  5449. """查询退款状态"""
  5450. from app.crud.settlement import refund_crud
  5451. refund = refund_crud.get(db, refund_id)
  5452. if not refund:
  5453. return error_response(404, "退款记录不存在")
  5454. return success_response({
  5455. "refundId": refund.id,
  5456. "refundNo": refund.refund_no,
  5457. "refundAmount": float(refund.refund_amount) if refund.refund_amount else 0,
  5458. "refundResult": refund.refund_result,
  5459. "refundTime": str(refund.refund_time) if refund.refund_time else None,
  5460. "refundNoWechat": refund.refund_no_wechat
  5461. })
  5462. @router.post("/refunds/{refund_id}/process", response_model=dict)
  5463. def process_refund(
  5464. refund_id: str,
  5465. request: dict,
  5466. db: Session = Depends(get_db),
  5467. current_user: dict = Depends(require_admin)
  5468. ):
  5469. """处理退款(成功/失败)"""
  5470. from app.crud.settlement import refund_crud
  5471. refund_result = request.get("refundResult")
  5472. refund_no_wechat = request.get("refundNoWechat")
  5473. if not refund_result or refund_result not in ["success", "failed"]:
  5474. return error_response(400, "请提供正确的退款结果")
  5475. refund = refund_crud.process_refund(
  5476. db,
  5477. refund_id=refund_id,
  5478. refund_result=refund_result,
  5479. refund_no_wechat=refund_no_wechat
  5480. )
  5481. if not refund:
  5482. return error_response(404, "退款记录不存在")
  5483. return success_response({
  5484. "refundId": refund.id,
  5485. "refundResult": refund.refund_result,
  5486. "message": "处理成功"
  5487. })
  5488. @router.post("/refunds/{refund_id}/handle-failure", response_model=dict)
  5489. def handle_refund_failure(
  5490. refund_id: str,
  5491. request: dict,
  5492. db: Session = Depends(get_db),
  5493. current_user: dict = Depends(require_admin)
  5494. ):
  5495. """处理退款失败"""
  5496. from app.crud.settlement import refund_crud
  5497. fail_reason = request.get("failReason")
  5498. if not fail_reason:
  5499. return error_response(400, "请提供失败原因")
  5500. refund = refund_crud.handle_refund_failure(
  5501. db,
  5502. refund_id=refund_id,
  5503. fail_reason=fail_reason
  5504. )
  5505. if not refund:
  5506. return error_response(404, "退款记录不存在")
  5507. return success_response({
  5508. "refundId": refund.id,
  5509. "refundResult": refund.refund_result,
  5510. "message": "处理成功"
  5511. })
  5512. @router.get("/refunds/statistics", response_model=dict)
  5513. def get_refund_statistics(
  5514. startDate: Optional[str] = Query(None, description="开始日期"),
  5515. endDate: Optional[str] = Query(None, description="结束日期"),
  5516. db: Session = Depends(get_db),
  5517. current_user: dict = Depends(require_admin)
  5518. ):
  5519. """获取退款统计数据"""
  5520. from app.crud.settlement import refund_crud
  5521. stats = refund_crud.get_refund_statistics(
  5522. db,
  5523. start_date=startDate,
  5524. end_date=endDate
  5525. )
  5526. return success_response(stats)
  5527. # =========================================
  5528. # 配送时效预警 API
  5529. # =========================================
  5530. @router.get("/delivery-warnings", response_model=dict)
  5531. def list_delivery_warnings(
  5532. page: int = Query(1, ge=1, description="页码"),
  5533. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5534. regionId: Optional[str] = Query(None, description="区域ID"),
  5535. urgencyLevel: Optional[str] = Query(None, description="紧急程度: critical/urgent/normal"),
  5536. db: Session = Depends(get_db),
  5537. current_user: dict = Depends(require_admin)
  5538. ):
  5539. """获取配送时效预警列表"""
  5540. from app.crud.delivery import delivery_task_crud
  5541. from datetime import datetime, timedelta
  5542. # 计算时间阈值
  5543. now = datetime.now()
  5544. critical_time = now + timedelta(minutes=30) # 30分钟内
  5545. urgent_time = now + timedelta(minutes=60) # 1小时内
  5546. normal_time = now + timedelta(hours=2) # 2小时内
  5547. # 获取所有待配送任务
  5548. query = db.query(delivery_task_crud.model).filter(
  5549. and_(
  5550. delivery_task_crud.model.is_del == 0,
  5551. delivery_task_crud.model.status.in_(["pending", "assigned", "picking", "picked"]),
  5552. delivery_task_crud.model.effective_time != None,
  5553. delivery_task_crud.model.effective_time >= now
  5554. )
  5555. )
  5556. if regionId:
  5557. query = query.filter(delivery_task_crud.model.region_id == regionId)
  5558. all_tasks = query.order_by(delivery_task_crud.model.effective_time.asc()).all()
  5559. # 计算紧急程度
  5560. result = []
  5561. for task in all_tasks:
  5562. time_diff = (task.effective_time - now).total_seconds() / 60 # 分钟
  5563. if time_diff <= 30:
  5564. urgency = "critical"
  5565. remaining_minutes = int(time_diff)
  5566. elif time_diff <= 60:
  5567. urgency = "urgent"
  5568. remaining_minutes = int(time_diff)
  5569. else:
  5570. urgency = "normal"
  5571. remaining_minutes = int(time_diff)
  5572. # 按紧急程度过滤
  5573. if urgencyLevel and urgency != urgencyLevel:
  5574. continue
  5575. # 获取关联信息
  5576. client_name = None
  5577. if task.order_id:
  5578. from app.crud.order import order_crud
  5579. order = order_crud.get(db, task.order_id)
  5580. if order:
  5581. client = user_crud.get(db, order.client_id)
  5582. client_name = client.real_name if client else None
  5583. region_name = None
  5584. if task.region_id:
  5585. region = region_crud.get(db, task.region_id)
  5586. region_name = region.name if region else None
  5587. deliver_name = None
  5588. if task.deliver_id:
  5589. deliver = user_crud.get(db, task.deliver_id)
  5590. deliver_name = deliver.real_name if deliver else None
  5591. supplier_name = None
  5592. if task.supplier_id:
  5593. supplier = user_crud.get(db, task.supplier_id)
  5594. supplier_name = supplier.real_name if supplier else None
  5595. result.append({
  5596. "id": task.id,
  5597. "taskNo": task.task_no,
  5598. "orderId": task.order_id,
  5599. "regionId": task.region_id,
  5600. "regionName": region_name,
  5601. "clientName": client_name,
  5602. "supplierId": task.supplier_id,
  5603. "supplierName": supplier_name,
  5604. "deliverId": task.deliver_id,
  5605. "deliverName": deliver_name,
  5606. "status": task.status,
  5607. "effectiveTime": str(task.effective_time) if task.effective_time else None,
  5608. "remainingMinutes": remaining_minutes,
  5609. "urgencyLevel": urgency,
  5610. "isAssigned": task.deliver_id is not None,
  5611. "createAt": str(task.create_at) if task.create_at else None
  5612. })
  5613. # 手动分页
  5614. total = len(result)
  5615. start_idx = (page - 1) * pageSize
  5616. end_idx = start_idx + pageSize
  5617. paginated_result = result[start_idx:end_idx]
  5618. return success_response({
  5619. "list": paginated_result,
  5620. "total": total,
  5621. "page": page,
  5622. "pageSize": pageSize,
  5623. "totalPages": (total + pageSize - 1) // pageSize
  5624. })
  5625. @router.get("/delivery-warnings/statistics", response_model=dict)
  5626. def get_delivery_warning_statistics(
  5627. regionId: Optional[str] = Query(None, description="区域ID"),
  5628. db: Session = Depends(get_db),
  5629. current_user: dict = Depends(require_admin)
  5630. ):
  5631. """获取配送时效预警统计"""
  5632. from app.crud.delivery import delivery_task_crud
  5633. from datetime import datetime, timedelta
  5634. now = datetime.now()
  5635. # 基础查询
  5636. base_query = db.query(delivery_task_crud.model).filter(
  5637. and_(
  5638. delivery_task_crud.model.is_del == 0,
  5639. delivery_task_crud.model.status.in_(["pending", "assigned", "picking", "picked"]),
  5640. delivery_task_crud.model.effective_time != None,
  5641. delivery_task_crud.model.effective_time >= now
  5642. )
  5643. )
  5644. if regionId:
  5645. base_query = base_query.filter(delivery_task_crud.model.region_id == regionId)
  5646. all_tasks = base_query.all()
  5647. critical_count = 0
  5648. urgent_count = 0
  5649. normal_count = 0
  5650. unassigned_count = 0
  5651. total_pending = len(all_tasks)
  5652. for task in all_tasks:
  5653. time_diff = (task.effective_time - now).total_seconds() / 60
  5654. if time_diff <= 30:
  5655. critical_count += 1
  5656. elif time_diff <= 60:
  5657. urgent_count += 1
  5658. else:
  5659. normal_count += 1
  5660. if not task.deliver_id:
  5661. unassigned_count += 1
  5662. return success_response({
  5663. "totalPending": total_pending,
  5664. "criticalCount": critical_count,
  5665. "urgentCount": urgent_count,
  5666. "normalCount": normal_count,
  5667. "unassignedCount": unassigned_count
  5668. })
  5669. @router.post("/delivery-warnings/{task_id}/reassign", response_model=dict)
  5670. def reassign_delivery_task(
  5671. task_id: str,
  5672. request: dict,
  5673. db: Session = Depends(get_db),
  5674. current_user: dict = Depends(require_admin)
  5675. ):
  5676. """紧急重新分配配送任务"""
  5677. from app.crud.delivery import delivery_task_crud
  5678. new_deliver_id = request.get("deliverId")
  5679. reason = request.get("reason")
  5680. if not new_deliver_id:
  5681. return error_response(400, "请选择新的配送员")
  5682. task = delivery_task_crud.get(db, task_id)
  5683. if not task:
  5684. return error_response(404, "任务不存在")
  5685. if task.status in ["completed", "cancelled"]:
  5686. return error_response(400, "已完成或已取消的任务无法重新分配")
  5687. # 验证新配送员
  5688. new_deliver = user_crud.get(db, new_deliver_id)
  5689. if not new_deliver:
  5690. return error_response(404, "配送员不存在")
  5691. if new_deliver.role != "deliver":
  5692. return error_response(400, "该用户不是配送员")
  5693. old_deliver_id = task.deliver_id
  5694. old_deliver_name = None
  5695. if old_deliver_id:
  5696. old_deliver = user_crud.get(db, old_deliver_id)
  5697. old_deliver_name = old_deliver.real_name if old_deliver else None
  5698. # 更新任务(换配送员:只重置配送员侧待取货,不重置供应商备货进度)
  5699. task.deliver_id = new_deliver_id
  5700. task.update_at = datetime.now()
  5701. task.deliverer_status = "pending_pickup"
  5702. delivery_task_crud._sync_legacy_status_from_dual(task)
  5703. # 如果之前没有分配配送员,设置新的截止时间
  5704. if not old_deliver_id:
  5705. task.effective_time = datetime.now() + timedelta(hours=4)
  5706. db.commit()
  5707. db.refresh(task)
  5708. return success_response({
  5709. "id": task.id,
  5710. "taskNo": task.task_no,
  5711. "newDeliverId": new_deliver_id,
  5712. "newDeliverName": new_deliver.real_name,
  5713. "oldDeliverId": old_deliver_id,
  5714. "oldDeliverName": old_deliver_name,
  5715. "message": "任务重新分配成功"
  5716. })
  5717. def get_client_ip(request: Request) -> str:
  5718. """获取客户端IP地址"""
  5719. forwarded = request.headers.get("X-Forwarded-For")
  5720. if forwarded:
  5721. return forwarded.split(",")[0].strip()
  5722. return request.client.host if request.client else "unknown"
  5723. # =========================================
  5724. # API 请求日志(中间件落库,此处仅查询/删除)
  5725. # =========================================
  5726. @router.get("/api-request-logs", response_model=dict)
  5727. def list_api_request_logs(
  5728. page: int = Query(1, ge=1, description="页码"),
  5729. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  5730. httpMethod: Optional[str] = Query(None, description="HTTP 方法"),
  5731. statusCode: Optional[int] = Query(None, description="HTTP 状态码"),
  5732. pathPrefix: Optional[str] = Query(None, description="路径包含"),
  5733. keyword: Optional[str] = Query(None, description="关键词"),
  5734. startDate: Optional[str] = Query(None, description="开始日期"),
  5735. endDate: Optional[str] = Query(None, description="结束日期"),
  5736. db: Session = Depends(get_db),
  5737. current_user: dict = Depends(require_admin)
  5738. ):
  5739. """API 请求日志列表"""
  5740. from app.crud.api_request_log import api_request_log_crud
  5741. logs, total = api_request_log_crud.get_multi_with_filters(
  5742. db,
  5743. http_method=httpMethod,
  5744. status_code=statusCode,
  5745. path_prefix=pathPrefix,
  5746. keyword=keyword,
  5747. start_date=startDate,
  5748. end_date=endDate,
  5749. skip=(page - 1) * pageSize,
  5750. limit=pageSize,
  5751. )
  5752. return success_response({
  5753. "list": [{
  5754. "id": log.id,
  5755. "httpMethod": log.http_method,
  5756. "path": log.path,
  5757. "queryString": log.query_string,
  5758. "statusCode": log.status_code,
  5759. "durationMs": log.duration_ms,
  5760. "userId": log.user_id,
  5761. "username": log.username,
  5762. "role": log.role,
  5763. "ipAddress": log.ip_address,
  5764. "userAgent": log.user_agent,
  5765. "requestBody": log.request_body,
  5766. "responseBody": log.response_body,
  5767. "createAt": str(log.create_at) if log.create_at else None,
  5768. } for log in logs],
  5769. "total": total,
  5770. "page": page,
  5771. "pageSize": pageSize,
  5772. "totalPages": (total + pageSize - 1) // pageSize
  5773. })
  5774. @router.get("/api-request-logs/{log_id}", response_model=dict)
  5775. def get_api_request_log(
  5776. log_id: str,
  5777. db: Session = Depends(get_db),
  5778. current_user: dict = Depends(require_admin)
  5779. ):
  5780. """API 请求日志详情"""
  5781. from app.crud.api_request_log import api_request_log_crud
  5782. log = api_request_log_crud.get(db, log_id)
  5783. if not log:
  5784. return error_response(404, "日志不存在")
  5785. return success_response({
  5786. "id": log.id,
  5787. "httpMethod": log.http_method,
  5788. "path": log.path,
  5789. "queryString": log.query_string,
  5790. "statusCode": log.status_code,
  5791. "durationMs": log.duration_ms,
  5792. "userId": log.user_id,
  5793. "username": log.username,
  5794. "role": log.role,
  5795. "ipAddress": log.ip_address,
  5796. "userAgent": log.user_agent,
  5797. "requestBody": log.request_body,
  5798. "responseBody": log.response_body,
  5799. "createAt": str(log.create_at) if log.create_at else None,
  5800. })
  5801. @router.delete("/api-request-logs/{log_id}", response_model=dict)
  5802. def delete_api_request_log(
  5803. log_id: str,
  5804. db: Session = Depends(get_db),
  5805. current_user: dict = Depends(require_admin)
  5806. ):
  5807. """删除 API 请求日志(软删除)"""
  5808. from app.crud.api_request_log import api_request_log_crud
  5809. if not api_request_log_crud.delete(db, log_id):
  5810. return error_response(404, "日志不存在")
  5811. return success_response({"id": log_id})
  5812. # =========================================
  5813. # 数据统计 API
  5814. # =========================================
  5815. @router.get("/statistics/dashboard", response_model=dict)
  5816. def get_dashboard_statistics(
  5817. regionId: Optional[str] = Query(None, description="区域ID"),
  5818. db: Session = Depends(get_db),
  5819. current_user: dict = Depends(require_admin)
  5820. ):
  5821. """获取仪表盘统计数据"""
  5822. from app.crud.statistics import statistics_crud
  5823. stats = statistics_crud.get_dashboard_summary(db, region_id=regionId)
  5824. return success_response(stats)
  5825. @router.get("/statistics/orders", response_model=dict)
  5826. def get_order_statistics(
  5827. regionId: Optional[str] = Query(None, description="区域ID"),
  5828. startDate: Optional[str] = Query(None, description="开始日期"),
  5829. endDate: Optional[str] = Query(None, description="结束日期"),
  5830. db: Session = Depends(get_db),
  5831. current_user: dict = Depends(require_admin)
  5832. ):
  5833. """获取订单统计数据"""
  5834. from app.crud.statistics import statistics_crud
  5835. stats = statistics_crud.get_order_statistics(
  5836. db,
  5837. region_id=regionId,
  5838. start_date=startDate,
  5839. end_date=endDate
  5840. )
  5841. return success_response(stats)
  5842. @router.get("/statistics/orders/trend", response_model=dict)
  5843. def get_order_trend(
  5844. regionId: Optional[str] = Query(None, description="区域ID"),
  5845. days: int = Query(7, ge=1, le=30, description="统计天数"),
  5846. db: Session = Depends(get_db),
  5847. current_user: dict = Depends(require_admin)
  5848. ):
  5849. """获取订单趋势数据"""
  5850. from app.crud.statistics import statistics_crud
  5851. trend = statistics_crud.get_order_trend(
  5852. db,
  5853. region_id=regionId,
  5854. days=days
  5855. )
  5856. return success_response(trend)
  5857. @router.get("/statistics/financial", response_model=dict)
  5858. def get_financial_statistics(
  5859. regionId: Optional[str] = Query(None, description="区域ID"),
  5860. startDate: Optional[str] = Query(None, description="开始日期"),
  5861. endDate: Optional[str] = Query(None, description="结束日期"),
  5862. db: Session = Depends(get_db),
  5863. current_user: dict = Depends(require_admin)
  5864. ):
  5865. """获取财务统计数据"""
  5866. from app.crud.statistics import statistics_crud
  5867. stats = statistics_crud.get_financial_statistics(
  5868. db,
  5869. region_id=regionId,
  5870. start_date=startDate,
  5871. end_date=endDate
  5872. )
  5873. return success_response(stats)
  5874. @router.get("/statistics/financial/trend", response_model=dict)
  5875. def get_financial_trend(
  5876. regionId: Optional[str] = Query(None, description="区域ID"),
  5877. days: int = Query(7, ge=1, le=30, description="统计天数"),
  5878. db: Session = Depends(get_db),
  5879. current_user: dict = Depends(require_admin)
  5880. ):
  5881. """获取财务趋势数据"""
  5882. from app.crud.statistics import statistics_crud
  5883. trend = statistics_crud.get_financial_trend(
  5884. db,
  5885. region_id=regionId,
  5886. days=days
  5887. )
  5888. return success_response(trend)
  5889. @router.get("/statistics/delivery", response_model=dict)
  5890. def get_delivery_statistics(
  5891. regionId: Optional[str] = Query(None, description="区域ID"),
  5892. startDate: Optional[str] = Query(None, description="开始日期"),
  5893. endDate: Optional[str] = Query(None, description="结束日期"),
  5894. db: Session = Depends(get_db),
  5895. current_user: dict = Depends(require_admin)
  5896. ):
  5897. """获取配送统计数据"""
  5898. from app.crud.statistics import statistics_crud
  5899. stats = statistics_crud.get_delivery_statistics(
  5900. db,
  5901. region_id=regionId,
  5902. start_date=startDate,
  5903. end_date=endDate
  5904. )
  5905. return success_response(stats)
  5906. @router.get("/statistics/products", response_model=dict)
  5907. def get_product_statistics(
  5908. regionId: Optional[str] = Query(None, description="区域ID"),
  5909. startDate: Optional[str] = Query(None, description="开始日期"),
  5910. endDate: Optional[str] = Query(None, description="结束日期"),
  5911. limit: int = Query(10, ge=1, le=50, description="返回数量"),
  5912. db: Session = Depends(get_db),
  5913. current_user: dict = Depends(require_admin)
  5914. ):
  5915. """获取商品销售排行"""
  5916. from app.crud.statistics import statistics_crud
  5917. stats = statistics_crud.get_product_statistics(
  5918. db,
  5919. region_id=regionId,
  5920. start_date=startDate,
  5921. end_date=endDate,
  5922. limit=limit
  5923. )
  5924. return success_response(stats)
  5925. @router.get("/statistics/customers", response_model=dict)
  5926. def get_customer_statistics(
  5927. regionId: Optional[str] = Query(None, description="区域ID"),
  5928. startDate: Optional[str] = Query(None, description="开始日期"),
  5929. endDate: Optional[str] = Query(None, description="结束日期"),
  5930. limit: int = Query(10, ge=1, le=50, description="返回数量"),
  5931. db: Session = Depends(get_db),
  5932. current_user: dict = Depends(require_admin)
  5933. ):
  5934. """获取客户订单排行"""
  5935. from app.crud.statistics import statistics_crud
  5936. stats = statistics_crud.get_customer_statistics(
  5937. db,
  5938. region_id=regionId,
  5939. start_date=startDate,
  5940. end_date=endDate,
  5941. limit=limit
  5942. )
  5943. return success_response(stats)
  5944. # =========================================
  5945. # 缺失的订单相关 API
  5946. # =========================================
  5947. @router.post("/orders/{order_id}/complete", response_model=dict)
  5948. def force_complete_order(
  5949. order_id: str,
  5950. db: Session = Depends(get_db),
  5951. current_user: dict = Depends(require_admin)
  5952. ):
  5953. """完结订单"""
  5954. from app.crud.order import order_crud
  5955. order = order_crud.get(db, order_id)
  5956. if not order:
  5957. return error_response(404, "订单不存在")
  5958. # 新状态模型:待收货阶段可由运营强制完结
  5959. if getattr(order, "order_status", None) != "pending_confirm":
  5960. return error_response(400, "只有待收货订单才能完结")
  5961. try:
  5962. completed_order = order_crud.force_complete(db, order_id, current_user.get("user_id"))
  5963. return success_response({
  5964. "id": completed_order.id,
  5965. "status": completed_order.status,
  5966. "message": "订单已完结"
  5967. })
  5968. except Exception as e:
  5969. return error_response(400, str(e))
  5970. @router.post("/orders/{order_id}/cancel", response_model=dict)
  5971. def cancel_order_admin(
  5972. order_id: str,
  5973. request: dict,
  5974. db: Session = Depends(get_db),
  5975. current_user: dict = Depends(require_admin)
  5976. ):
  5977. """运营端取消订单"""
  5978. from app.crud.order import order_crud
  5979. order = order_crud.get(db, order_id)
  5980. if not order:
  5981. return error_response(404, "订单不存在")
  5982. # 新状态模型:仅未完成且未取消订单允许运营取消
  5983. if getattr(order, "order_status", None) in ["completed", "cancelled"]:
  5984. return error_response(400, "已完成或已取消订单不能再次取消")
  5985. reason = request.get("reason", "")
  5986. note = request.get("note", "")
  5987. evidence_image_urls = request.get("evidenceImageUrls", []) or []
  5988. if not reason:
  5989. return error_response(400, "请填写取消原因")
  5990. if not isinstance(evidence_image_urls, list):
  5991. return error_response(400, "evidenceImageUrls 格式不正确")
  5992. try:
  5993. cancelled_order = order_crud.admin_cancel(
  5994. db,
  5995. order_id=order_id,
  5996. operator_id=current_user.get("user_id"),
  5997. operator_name=current_user.get("real_name"),
  5998. reason=reason,
  5999. note=note,
  6000. evidence_image_urls=evidence_image_urls,
  6001. )
  6002. if evidence_image_urls:
  6003. from app.models.models import BizAttachment
  6004. from app.core.utils import generate_id
  6005. for url in evidence_image_urls:
  6006. if not isinstance(url, str) or not url.strip():
  6007. continue
  6008. db.add(BizAttachment(
  6009. id=generate_id(),
  6010. business_type="order",
  6011. business_id=order_id,
  6012. file_name=url.split("/")[-1][:200],
  6013. file_url=url,
  6014. file_type="image/*",
  6015. upload_by=current_user.get("user_id"),
  6016. upload_by_name=current_user.get("real_name"),
  6017. create_by=current_user.get("user_id"),
  6018. create_name=current_user.get("real_name"),
  6019. ))
  6020. db.commit()
  6021. return success_response({
  6022. "id": cancelled_order.id,
  6023. "status": cancelled_order.status,
  6024. "message": "订单已取消"
  6025. })
  6026. except Exception as e:
  6027. return error_response(400, str(e))
  6028. @router.get("/orders/adjustable", response_model=dict)
  6029. def list_adjustable_orders(
  6030. keyword: Optional[str] = Query(None, description="关键词搜索"),
  6031. db: Session = Depends(get_db),
  6032. current_user: dict = Depends(require_admin)
  6033. ):
  6034. """获取可调整的订单列表"""
  6035. from app.crud.order import order_crud, order_item_crud
  6036. # 可调整的订单状态:待支付、待收货(线下单)
  6037. adjustable_statuses = ["pending_payment", "pending_confirm"]
  6038. orders, total = order_crud.get_multi_with_filters(
  6039. db,
  6040. status=None, # 不按状态过滤,我们手动过滤
  6041. order_no=keyword,
  6042. skip=0,
  6043. limit=100 # 默认获取100条
  6044. )
  6045. # 过滤出可调整的订单
  6046. adjustable_orders = []
  6047. for order in orders:
  6048. if getattr(order, "order_status", None) in adjustable_statuses and order_crud.normalize_payment_method(order.payment_method) == "offline":
  6049. item_count = order_item_crud.get_count_by_order(db, order.id)
  6050. adjustable_orders.append({
  6051. "id": order.id,
  6052. "orderNo": order.order_no,
  6053. "status": order.status,
  6054. "orderStatus": getattr(order, "order_status", None) or "pending_confirm",
  6055. "deliveryStatus": getattr(order, "delivery_status", None) or "pending_dispatch",
  6056. "payStatus": getattr(order, "pay_status", None) or "pending_payment",
  6057. "statusText": ORDER_STATUS_MAP.get(order.status, order.status),
  6058. "totalAmount": float(order.total_amount) if order.total_amount else 0,
  6059. "itemCount": item_count,
  6060. "createAt": str(order.create_at) if order.create_at else None
  6061. })
  6062. return success_response({
  6063. "list": adjustable_orders,
  6064. "total": len(adjustable_orders)
  6065. })
  6066. @router.get("/orders/{order_id}/items", response_model=dict)
  6067. def get_order_items(
  6068. order_id: str,
  6069. db: Session = Depends(get_db),
  6070. current_user: dict = Depends(require_admin)
  6071. ):
  6072. """获取订单商品列表"""
  6073. from app.crud.order import order_crud, order_item_crud
  6074. order = order_crud.get(db, order_id)
  6075. if not order:
  6076. return error_response(404, "订单不存在")
  6077. items = order_item_crud.get_by_order(db, order_id)
  6078. from app.crud.price_list import price_list_crud
  6079. price_list = price_list_crud.get(db, order.price_list_id) if order.price_list_id else None
  6080. supplier_id_from_price_list = getattr(price_list, "supplier_id", None) if price_list else None
  6081. supplier_name_from_price_list = None
  6082. if supplier_id_from_price_list:
  6083. _sup_u = user_crud.get(db, supplier_id_from_price_list)
  6084. if _sup_u:
  6085. supplier_name_from_price_list = _sup_u.real_name or _sup_u.username
  6086. pl_ids_for_order = [order.price_list_id] if order.price_list_id else []
  6087. pli_map_for_order = _price_list_item_map(db, pl_ids_for_order)
  6088. from app.crud.delivery import delivery_task_item_crud as _merge_task_delivered_items
  6089. _line_delivered_from_task = _merge_task_delivered_items.get_delivered_quantity_by_order_item(db, order_id)
  6090. result = []
  6091. for item in items:
  6092. product = product_crud.get(db, item.product_id)
  6093. unit_name = None
  6094. if item.unit_id:
  6095. u = unit_crud.get(db, item.unit_id)
  6096. unit_name = u.name if u else None
  6097. category_name = None
  6098. if product and product.category_id:
  6099. cat = category_crud.get(db, product.category_id)
  6100. category_name = cat.name if cat else None
  6101. _oi_dq = float(item.delivered_quantity) if item.delivered_quantity else 0.0
  6102. _ti_dq = float(_line_delivered_from_task.get(item.id, 0.0))
  6103. _merged_dq = max(_oi_dq, _ti_dq)
  6104. qty = float(item.quantity) if item.quantity else 0
  6105. selling_u = float(item.unit_price) if item.unit_price else 0
  6106. selling_amt = float(item.amount) if item.amount else round(qty * selling_u, 2)
  6107. pli = pli_map_for_order.get((order.price_list_id, item.product_id, item.unit_id))
  6108. supplier_u = _supplier_unit_yuan_from_pli(pli)
  6109. if supplier_u is None:
  6110. supplier_u = selling_u
  6111. supplier_amt = round(qty * supplier_u, 2)
  6112. result.append({
  6113. "id": item.id,
  6114. "productId": item.product_id,
  6115. "productName": product.name if product else None,
  6116. "imageUrl": getattr(product, "image_url", None) if product else None,
  6117. "categoryName": category_name,
  6118. "unitId": item.unit_id,
  6119. "unitName": unit_name,
  6120. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)) if product else None,
  6121. "supplierId": supplier_id_from_price_list,
  6122. "supplierName": supplier_name_from_price_list,
  6123. "quantity": qty,
  6124. "unitPrice": selling_u,
  6125. "amount": selling_amt,
  6126. "sellingUnitPrice": selling_u,
  6127. "sellingAmount": selling_amt,
  6128. "supplierUnitPrice": supplier_u,
  6129. "supplierAmount": supplier_amt,
  6130. "deliveredQuantity": _merged_dq,
  6131. "status": item.status
  6132. })
  6133. return success_response({
  6134. "list": result,
  6135. "total": len(result)
  6136. })
  6137. # =========================================
  6138. # 商品简单列表 API
  6139. # =========================================
  6140. @router.get("/products/simple", response_model=dict)
  6141. def list_products_simple(
  6142. keyword: Optional[str] = Query(None, description="关键词搜索"),
  6143. categoryId: Optional[str] = Query(None, description="分类ID"),
  6144. db: Session = Depends(get_db),
  6145. current_user: dict = Depends(require_admin)
  6146. ):
  6147. """获取商品简单列表(用于订单调整选择替代商品)"""
  6148. from app.models.models import BizProduct
  6149. query = db.query(BizProduct).filter(BizProduct.is_del == 0, BizProduct.is_active == 1)
  6150. if keyword:
  6151. query = query.filter(BizProduct.name.ilike(f"%{keyword}%"))
  6152. if categoryId:
  6153. query = query.filter(BizProduct.category_id == categoryId)
  6154. products = query.order_by(BizProduct.name).limit(100).all()
  6155. result = []
  6156. for p in products:
  6157. category_name = None
  6158. if p.category_id:
  6159. cat = category_crud.get(db, p.category_id)
  6160. category_name = cat.name if cat else None
  6161. unit_name = None
  6162. if p.unit_id:
  6163. u = unit_crud.get(db, p.unit_id)
  6164. unit_name = u.name if u else None
  6165. result.append({
  6166. "id": p.id,
  6167. "name": p.name,
  6168. "categoryId": p.category_id,
  6169. "categoryName": category_name,
  6170. "unitId": p.unit_id,
  6171. "unitName": unit_name,
  6172. "imageUrl": p.image_url
  6173. })
  6174. return success_response({
  6175. "list": result,
  6176. "total": len(result)
  6177. })
  6178. # =========================================
  6179. # 询价单简单列表 API
  6180. # =========================================
  6181. @router.get("/inquiries/simple", response_model=dict)
  6182. def list_inquiries_simple(
  6183. status: Optional[str] = Query(None, description="状态"),
  6184. db: Session = Depends(get_db),
  6185. current_user: dict = Depends(require_admin)
  6186. ):
  6187. """获取询价单简单列表(用于报价对比选择)"""
  6188. from app.models.models import BizInquiry
  6189. query = db.query(BizInquiry).filter(BizInquiry.is_del == 0)
  6190. if status:
  6191. query = query.filter(BizInquiry.status == status)
  6192. inquiries = query.order_by(BizInquiry.create_at.desc()).limit(50).all()
  6193. result = []
  6194. for inquiry in inquiries:
  6195. region_name = None
  6196. if inquiry.region_id:
  6197. region = region_crud.get(db, inquiry.region_id)
  6198. region_name = region.name if region else None
  6199. result.append({
  6200. "id": inquiry.id,
  6201. "title": inquiry.title,
  6202. "status": inquiry.status,
  6203. "regionId": inquiry.region_id,
  6204. "regionName": region_name,
  6205. "createAt": str(inquiry.create_at) if inquiry.create_at else None
  6206. })
  6207. return success_response({
  6208. "list": result,
  6209. "total": len(result)
  6210. })
  6211. # =========================================
  6212. # 报价确认供应商 API
  6213. # =========================================
  6214. @router.post("/quotations/confirm-supplier", response_model=dict)
  6215. def confirm_quotation_supplier(
  6216. request: dict,
  6217. db: Session = Depends(get_db),
  6218. current_user: dict = Depends(require_admin)
  6219. ):
  6220. """确认选择供应商报价,并生成区域生效价格清单(active)
  6221. 约束:
  6222. - 同一询价单,仅允许 1 个报价单为 selected
  6223. - 报价单状态仅使用:submitted / selected
  6224. - 不改变询价单状态(仍为 published 等业务状态)
  6225. """
  6226. from app.models.models import BizInquiry, BizQuotation, BizPriceList, BizPriceListItem
  6227. from app.crud.quotation import quotation_crud, quotation_item_crud
  6228. from app.crud.inquiry import inquiry_item_crud
  6229. from app.crud.product import product_crud
  6230. from app.core.utils import generate_id
  6231. from sqlalchemy import and_
  6232. from decimal import Decimal
  6233. inquiry_id = request.get("inquiryId")
  6234. quotation_id = request.get("quotationId")
  6235. final_price_items = request.get("finalPriceItems") or []
  6236. if not inquiry_id or not quotation_id:
  6237. return error_response(400, "询价单ID和报价ID不能为空")
  6238. inquiry = db.query(BizInquiry).filter(and_(BizInquiry.id == inquiry_id, BizInquiry.is_del == 0)).first()
  6239. if not inquiry:
  6240. return error_response(404, "询价单不存在")
  6241. quotation = quotation_crud.get(db, quotation_id)
  6242. if not quotation:
  6243. return error_response(404, "报价不存在")
  6244. if quotation.inquiry_id != inquiry_id:
  6245. return error_response(400, "报价不属于该询价单")
  6246. # 询价单必须处于发布中,才允许选择供应商生成生效价格
  6247. if inquiry.status != "published":
  6248. return error_response(400, "只能对已发布状态的询价单选择供应商报价")
  6249. # 同一询价仅允许一个 selected:先将其它报价恢复为 submitted
  6250. db.query(BizQuotation).filter(
  6251. and_(
  6252. BizQuotation.inquiry_id == inquiry_id,
  6253. BizQuotation.id != quotation_id,
  6254. BizQuotation.is_del == 0
  6255. )
  6256. ).update({"status": "submitted"}, synchronize_session=False)
  6257. # 当前报价置为 selected
  6258. quotation.status = "selected"
  6259. # 生成价格清单:范围仅询价单的商品
  6260. inquiry_items = inquiry_item_crud.get_by_inquiry(db, inquiry_id)
  6261. inquiry_product_ids = {i.product_id for i in inquiry_items if i and i.product_id}
  6262. if not inquiry_product_ids:
  6263. return error_response(400, "询价单必须包含至少一个商品")
  6264. quotation_items = quotation_item_crud.get_by_quotation(db, quotation_id)
  6265. quotation_item_by_pid: dict[str, any] = {}
  6266. for qi in quotation_items or []:
  6267. pid = str(getattr(qi, "product_id", "") or "")
  6268. if not pid:
  6269. continue
  6270. if pid in inquiry_product_ids:
  6271. quotation_item_by_pid[pid] = qi
  6272. # 允许供应商某些商品未报价:只要运营端传入了最终售价(finalPriceItems)即可生成价格清单
  6273. if not quotation_item_by_pid and not final_price_items:
  6274. return error_response(400, "该报价单未包含本询价单商品报价,且未传入最终售价,无法生成价格清单")
  6275. # 计算版本号(区域维度自增)
  6276. max_version_row = db.query(BizPriceList).filter(
  6277. and_(BizPriceList.region_id == inquiry.region_id, BizPriceList.is_del == 0)
  6278. ).order_by(BizPriceList.version.desc()).first()
  6279. next_version = (max_version_row.version + 1) if max_version_row and max_version_row.version else 1
  6280. # 将该区域其他 active 价格清单置为 inactive
  6281. db.query(BizPriceList).filter(
  6282. and_(
  6283. BizPriceList.region_id == inquiry.region_id,
  6284. BizPriceList.status == "active",
  6285. BizPriceList.is_del == 0
  6286. )
  6287. ).update({"status": "inactive"}, synchronize_session=False)
  6288. # 创建新价格清单(直接生效)
  6289. price_list_id = generate_id()
  6290. now = datetime.now()
  6291. price_list = BizPriceList(
  6292. id=price_list_id,
  6293. region_id=inquiry.region_id,
  6294. supplier_id=quotation.supplier_id,
  6295. inquiry_id=inquiry_id,
  6296. quotation_id=quotation_id,
  6297. source_type="quotation_select",
  6298. version=next_version,
  6299. status="active",
  6300. effective_time=now,
  6301. published_by=current_user.get("user_id"),
  6302. published_time=now,
  6303. remark=f"由询价单选择供应商报价生成(询价={inquiry_id}, 报价={quotation_id})",
  6304. create_by=current_user.get("user_id"),
  6305. create_name=current_user.get("real_name")
  6306. )
  6307. db.add(price_list)
  6308. db.flush()
  6309. # 可选:前端传入最终售卖价 + 本次调价系数(用于回显与二次发布)
  6310. # key 统一使用 str(product_id),避免类型不一致导致匹配失败
  6311. final_price_map: dict[str, Decimal] = {}
  6312. pricing_coeff_map: dict[str, Decimal] = {}
  6313. if final_price_items:
  6314. if not isinstance(final_price_items, list):
  6315. return error_response(400, "finalPriceItems 参数格式错误")
  6316. for it in final_price_items:
  6317. if not isinstance(it, dict):
  6318. return error_response(400, "finalPriceItems 参数格式错误")
  6319. pid = it.get("productId")
  6320. price = it.get("price")
  6321. pricing_coeff = it.get("pricingCoefficient")
  6322. if not pid:
  6323. return error_response(400, "finalPriceItems.productId 不能为空")
  6324. pid_key = str(pid)
  6325. try:
  6326. price_decimal = Decimal(str(price))
  6327. except Exception:
  6328. return error_response(400, f"商品 {pid} 的价格格式不正确")
  6329. if price_decimal <= Decimal("0"):
  6330. return error_response(400, f"商品 {pid} 的价格必须大于0")
  6331. final_price_map[pid_key] = price_decimal.quantize(Decimal("0.01"))
  6332. if pricing_coeff is not None and pricing_coeff != "":
  6333. try:
  6334. coeff_decimal = Decimal(str(pricing_coeff))
  6335. except Exception:
  6336. return error_response(400, f"商品 {pid} 的调价系数格式不正确")
  6337. pricing_coeff_map[pid_key] = coeff_decimal.quantize(Decimal("0.01"))
  6338. # 写入价格清单明细:范围=询价单的商品(不要求供应商都报价)
  6339. for ii in inquiry_items:
  6340. pid_key = str(getattr(ii, "product_id", "") or "")
  6341. if not pid_key:
  6342. continue
  6343. qi = quotation_item_by_pid.get(pid_key)
  6344. final_price = final_price_map.get(pid_key)
  6345. pricing_coeff = pricing_coeff_map.get(pid_key)
  6346. # 最终售价优先取前端传入;否则回退为供应商报价
  6347. if final_price is None:
  6348. if qi is not None and getattr(qi, "price", None) is not None:
  6349. final_price = Decimal(str(qi.price)).quantize(Decimal("0.01"))
  6350. else:
  6351. return error_response(400, f"商品 {pid_key} 缺少供应商报价,且未传入最终售价,无法生成价格清单")
  6352. # 单位ID:优先报价单项;否则从商品表取
  6353. unit_id = getattr(qi, "unit_id", None) if qi is not None else None
  6354. if not unit_id:
  6355. product_for_unit = product_crud.get(db, pid_key)
  6356. unit_id = getattr(product_for_unit, "unit_id", None) if product_for_unit else None
  6357. if not unit_id:
  6358. return error_response(400, f"商品 {pid_key} 缺少单位信息,无法生成价格清单")
  6359. # 若前端未传调价系数:尝试通过(最终价, 供应商报价)反推;再兜底商品默认系数
  6360. if pricing_coeff is None:
  6361. if qi is not None and getattr(qi, "price", None) is not None:
  6362. try:
  6363. supplier_price_decimal = Decimal(str(qi.price))
  6364. except Exception:
  6365. supplier_price_decimal = Decimal("0")
  6366. if supplier_price_decimal > Decimal("0"):
  6367. try:
  6368. pricing_coeff = ((final_price / supplier_price_decimal) - Decimal("1")) * Decimal("100")
  6369. pricing_coeff = pricing_coeff.quantize(Decimal("0.01"))
  6370. except Exception:
  6371. pricing_coeff = None
  6372. if pricing_coeff is None:
  6373. product = product_crud.get(db, pid_key)
  6374. raw_default = getattr(product, "price_coefficient", None) if product else None
  6375. try:
  6376. pricing_coeff = Decimal(str(raw_default)).quantize(Decimal("0.01")) if raw_default is not None else Decimal("0.00")
  6377. except Exception:
  6378. pricing_coeff = Decimal("0.00")
  6379. pli = BizPriceListItem(
  6380. id=generate_id(),
  6381. price_list_id=price_list_id,
  6382. product_id=pid_key,
  6383. unit_id=unit_id,
  6384. price=final_price,
  6385. pricing_coefficient=pricing_coeff,
  6386. create_by=current_user.get("user_id"),
  6387. create_name=current_user.get("real_name")
  6388. )
  6389. db.add(pli)
  6390. db.commit()
  6391. return success_response({
  6392. "message": "已选择供应商报价并生成生效价格",
  6393. "inquiryId": inquiry_id,
  6394. "quotationId": quotation_id,
  6395. "priceListId": price_list_id,
  6396. "priceVersion": next_version
  6397. })
  6398. # =========================================
  6399. # 价格版本管理 API
  6400. # =========================================
  6401. @router.get("/price-versions", response_model=dict)
  6402. def list_price_versions(
  6403. page: int = Query(1, ge=1, description="页码"),
  6404. pageSize: int = Query(10, ge=1, le=100, description="每页条数"),
  6405. regionId: Optional[str] = Query(None, description="区域ID"),
  6406. supplierId: Optional[str] = Query(None, description="供应商ID"),
  6407. status: Optional[str] = Query(None, description="状态"),
  6408. db: Session = Depends(get_db),
  6409. current_user: dict = Depends(require_admin)
  6410. ):
  6411. """获取价格版本列表"""
  6412. from app.models.models import BizPriceList
  6413. from sqlalchemy import or_
  6414. query = db.query(BizPriceList).filter(BizPriceList.is_del == 0)
  6415. if regionId:
  6416. query = query.filter(BizPriceList.region_id == regionId)
  6417. if supplierId:
  6418. query = query.filter(BizPriceList.supplier_id == supplierId)
  6419. if status:
  6420. query = query.filter(BizPriceList.status == status)
  6421. total = query.count()
  6422. versions = query.order_by(BizPriceList.create_at.desc()).offset((page - 1) * pageSize).limit(pageSize).all()
  6423. result = []
  6424. for v in versions:
  6425. region_name = None
  6426. if v.region_id:
  6427. region = region_crud.get(db, v.region_id)
  6428. region_name = region.name if region else None
  6429. supplier_name = None
  6430. if v.supplier_id:
  6431. supplier = user_crud.get(db, v.supplier_id)
  6432. supplier_name = supplier.real_name if supplier else None
  6433. result.append({
  6434. "id": v.id,
  6435. "versionNo": getattr(v, "version_no", None) or getattr(v, "version", None),
  6436. "regionId": v.region_id,
  6437. "regionName": region_name,
  6438. "supplierId": v.supplier_id,
  6439. "supplierName": supplier_name,
  6440. "status": v.status,
  6441. "effectiveTime": str(v.effective_time) if v.effective_time else None,
  6442. "remark": v.remark,
  6443. "createAt": str(v.create_at) if v.create_at else None
  6444. })
  6445. return success_response({
  6446. "list": result,
  6447. "total": total,
  6448. "page": page,
  6449. "pageSize": pageSize,
  6450. "totalPages": (total + pageSize - 1) // pageSize
  6451. })
  6452. @router.get("/price-versions/{version_id}", response_model=dict)
  6453. def get_price_version_detail(
  6454. version_id: str,
  6455. db: Session = Depends(get_db),
  6456. current_user: dict = Depends(require_admin)
  6457. ):
  6458. """获取价格版本详情(含供应商报价与最终售价拆解,便于订单侧只读查看)。"""
  6459. from app.models.models import BizPriceList, BizPriceListItem, BizQuotationItem
  6460. from app.crud.inquiry import inquiry_crud
  6461. version = db.query(BizPriceList).filter(BizPriceList.id == version_id, BizPriceList.is_del == 0).first()
  6462. if not version:
  6463. return error_response(404, "价格清单不存在")
  6464. region_name = None
  6465. if version.region_id:
  6466. region = region_crud.get(db, version.region_id)
  6467. region_name = region.name if region else None
  6468. supplier_name = None
  6469. if version.supplier_id:
  6470. supplier = user_crud.get(db, version.supplier_id)
  6471. supplier_name = supplier.real_name if supplier else None
  6472. inquiry_title = None
  6473. if version.inquiry_id:
  6474. iq = inquiry_crud.get(db, version.inquiry_id)
  6475. inquiry_title = iq.title if iq else None
  6476. # 来源报价单:用于还原供应商侧单价
  6477. q_item_by_pid: dict[str, object] = {}
  6478. if version.quotation_id:
  6479. q_rows = db.query(BizQuotationItem).filter(
  6480. and_(
  6481. BizQuotationItem.quotation_id == version.quotation_id,
  6482. BizQuotationItem.is_del == 0
  6483. )
  6484. ).all()
  6485. for qi in q_rows:
  6486. pid = str(getattr(qi, "product_id", "") or "")
  6487. if pid and pid not in q_item_by_pid:
  6488. q_item_by_pid[pid] = qi
  6489. # 获取版本明细
  6490. items = db.query(BizPriceListItem).filter(
  6491. BizPriceListItem.price_list_id == version_id,
  6492. BizPriceListItem.is_del == 0
  6493. ).all()
  6494. item_details = []
  6495. for item in items:
  6496. product = product_crud.get(db, item.product_id)
  6497. unit_name = None
  6498. if item.unit_id:
  6499. u = unit_crud.get(db, item.unit_id)
  6500. unit_name = u.name if u else None
  6501. pid = str(item.product_id or "")
  6502. q_item = q_item_by_pid.get(pid)
  6503. supplier_price = float(getattr(q_item, "price", 0) or 0) if q_item else 0.0
  6504. coeff = None
  6505. if getattr(item, "pricing_coefficient", None) is not None:
  6506. coeff = float(item.pricing_coefficient)
  6507. elif product and getattr(product, "price_coefficient", None) is not None:
  6508. coeff = float(product.price_coefficient)
  6509. else:
  6510. coeff = 0.0
  6511. final_price = float(item.price) if item.price else 0.0
  6512. category_id = getattr(product, "category_id", None) if product else None
  6513. category_path = _category_path_display(db, str(category_id)) if category_id else ""
  6514. item_details.append({
  6515. "id": item.id,
  6516. "productId": item.product_id,
  6517. "productName": product.name if product else None,
  6518. "imageUrl": getattr(product, "image_url", None) if product else None,
  6519. "categoryId": str(category_id) if category_id else None,
  6520. "categoryName": category_path or None,
  6521. "measureValue": _numeric_to_float_optional(getattr(product, "measure_value", None)) if product else None,
  6522. "unitId": item.unit_id,
  6523. "unitName": unit_name,
  6524. "supplierPrice": supplier_price,
  6525. "pricingCoefficient": coeff,
  6526. "finalPrice": final_price,
  6527. "price": final_price
  6528. })
  6529. return success_response({
  6530. "id": version.id,
  6531. "versionNo": getattr(version, "version_no", None) or getattr(version, "version", None),
  6532. "version": getattr(version, "version", None),
  6533. "regionId": version.region_id,
  6534. "regionName": region_name,
  6535. "supplierId": version.supplier_id,
  6536. "supplierName": supplier_name,
  6537. "inquiryId": version.inquiry_id,
  6538. "inquiryTitle": inquiry_title,
  6539. "quotationId": version.quotation_id,
  6540. "status": version.status,
  6541. "effectiveTime": str(version.effective_time) if version.effective_time else None,
  6542. "remark": version.remark,
  6543. "createAt": str(version.create_at) if version.create_at else None,
  6544. "items": item_details
  6545. })
  6546. @router.post("/price-versions", response_model=dict)
  6547. def create_price_version(
  6548. request: dict,
  6549. db: Session = Depends(get_db),
  6550. current_user: dict = Depends(require_admin)
  6551. ):
  6552. """创建价格版本"""
  6553. from app.models.models import BizPriceList
  6554. from app.core.utils import generate_uuid
  6555. region_id = request.get("regionId")
  6556. supplier_id = request.get("supplierId")
  6557. effective_time = request.get("effectiveTime")
  6558. remark = request.get("remark")
  6559. if not region_id or not supplier_id:
  6560. return error_response(400, "区域ID和供应商ID不能为空")
  6561. # 生成版本号
  6562. today = datetime.now().strftime("%Y%m%d")
  6563. count = db.query(BizPriceList).filter(
  6564. BizPriceList.region_id == region_id,
  6565. BizPriceList.supplier_id == supplier_id
  6566. ).count()
  6567. version_no = f"PL{today}{count + 1:04d}"
  6568. # 解析生效时间
  6569. effective_dt = None
  6570. if effective_time:
  6571. try:
  6572. effective_dt = datetime.strptime(effective_time, "%Y-%m-%d %H:%M:%S")
  6573. except:
  6574. try:
  6575. effective_dt = datetime.strptime(effective_time, "%Y-%m-%d")
  6576. except:
  6577. pass
  6578. new_version = BizPriceList(
  6579. id=generate_uuid(),
  6580. region_id=region_id,
  6581. supplier_id=supplier_id,
  6582. version_no=version_no,
  6583. status="draft",
  6584. effective_time=effective_dt,
  6585. remark=remark,
  6586. create_at=datetime.now(),
  6587. create_by=current_user.get("user_id"),
  6588. create_name=current_user.get("real_name"),
  6589. is_del=0
  6590. )
  6591. db.add(new_version)
  6592. db.commit()
  6593. return success_response({
  6594. "id": new_version.id,
  6595. "versionNo": version_no,
  6596. "message": "价格版本创建成功"
  6597. })
  6598. @router.post("/price-versions/{version_id}/publish", response_model=dict)
  6599. def publish_price_version(
  6600. version_id: str,
  6601. db: Session = Depends(get_db),
  6602. current_user: dict = Depends(require_admin)
  6603. ):
  6604. """发布价格版本"""
  6605. from app.models.models import BizPriceList
  6606. version = db.query(BizPriceList).filter(BizPriceList.id == version_id, BizPriceList.is_del == 0).first()
  6607. if not version:
  6608. return error_response(404, "价格版本不存在")
  6609. if version.status != "draft":
  6610. return error_response(400, "只有草稿状态的价格版本才能发布")
  6611. version.status = "published"
  6612. version.publish_time = datetime.now()
  6613. version.publisher_id = current_user.get("user_id")
  6614. db.commit()
  6615. return success_response({
  6616. "id": version.id,
  6617. "status": version.status,
  6618. "message": "价格版本发布成功"
  6619. })
  6620. @router.post("/price-versions/{version_id}/disable", response_model=dict)
  6621. def disable_price_version(
  6622. version_id: str,
  6623. db: Session = Depends(get_db),
  6624. current_user: dict = Depends(require_admin)
  6625. ):
  6626. """禁用价格版本"""
  6627. from app.models.models import BizPriceList
  6628. version = db.query(BizPriceList).filter(BizPriceList.id == version_id, BizPriceList.is_del == 0).first()
  6629. if not version:
  6630. return error_response(404, "价格版本不存在")
  6631. if version.status == "invalid":
  6632. return error_response(400, "该价格版本已经失效")
  6633. version.status = "invalid"
  6634. version.invalidate_time = datetime.now()
  6635. version.invalidate_operator_id = current_user.get("user_id")
  6636. db.commit()
  6637. return success_response({
  6638. "id": version.id,
  6639. "status": version.status,
  6640. "message": "价格版本已禁用"
  6641. })
  6642. @router.get("/price-versions/compare", response_model=dict)
  6643. def compare_price_versions(
  6644. versionIds: str = Query(..., description="版本ID列表,逗号分隔"),
  6645. db: Session = Depends(get_db),
  6646. current_user: dict = Depends(require_admin)
  6647. ):
  6648. """版本价格对比"""
  6649. from app.models.models import BizPriceList, BizPriceListItem
  6650. version_id_list = [v.strip() for v in versionIds.split(",") if v.strip()]
  6651. if len(version_id_list) < 2:
  6652. return error_response(400, "至少需要选择两个版本进行对比")
  6653. versions = db.query(BizPriceList).filter(
  6654. BizPriceList.id.in_(version_id_list),
  6655. BizPriceList.is_del == 0
  6656. ).all()
  6657. if len(versions) < 2:
  6658. return error_response(400, "选择的版本中有不存在的")
  6659. # 获取所有版本的价格明细
  6660. version_items = {}
  6661. all_products = set()
  6662. for version in versions:
  6663. items = db.query(BizPriceListItem).filter(
  6664. BizPriceListItem.price_list_id == version.id,
  6665. BizPriceListItem.is_del == 0
  6666. ).all()
  6667. version_items[version.id] = {item.product_id: float(item.price) if item.price else 0 for item in items}
  6668. all_products.update([item.product_id for item in items])
  6669. # 构建对比数据
  6670. compare_data = []
  6671. for product_id in all_products:
  6672. product = product_crud.get(db, product_id)
  6673. if not product:
  6674. continue
  6675. row = {
  6676. "productId": product_id,
  6677. "productName": product.name,
  6678. "prices": {}
  6679. }
  6680. for version in versions:
  6681. row["prices"][version.id] = version_items.get(version.id, {}).get(product_id, None)
  6682. if row["prices"][version.id] is not None:
  6683. if not hasattr(row, "lowestPrice") or row["lowestPrice"] > row["prices"][version.id]:
  6684. row["lowestPrice"] = row["prices"][version.id]
  6685. row["lowestVersionId"] = version.id
  6686. compare_data.append(row)
  6687. # 版本基本信息
  6688. version_info = [{
  6689. "id": v.id,
  6690. "versionNo": v.version_no,
  6691. "status": v.status
  6692. } for v in versions]
  6693. return success_response({
  6694. "versions": version_info,
  6695. "products": compare_data
  6696. })