Commit 242b1cf0 authored by confusion's avatar confusion

优化结构

parent 5fc5dc60
...@@ -7,9 +7,9 @@ from pymongo.operations import UpdateOne ...@@ -7,9 +7,9 @@ from pymongo.operations import UpdateOne
from dependencies import get_current_user, get_fund_collect, get_bill_collect from dependencies import get_current_user, get_fund_collect, get_bill_collect
from exception.db import NotFundError from exception.db import NotFundError
from model import Response, Page, PageResponse, SortParams, FilterTime from model import Response, Page, PageResponse, SortParams, FilterTime
from model.bill import PCFBillRes, ExchangeBillRes, BillType, CreatePCFBill, CreateExchangeBill, StakingBillRes, \ from model.bill import PCFBill, ExchangeBill, AdjustBill, StakingBill
AdjustBillRes, CreateAdjustBill, UpdatePCFBill, UpdateExchangeBill, UpdateStakingBill, UpdateAdjustBill, \ from schema.bill import CreatePCFBill, PCFBillType, CreateExchangeBill, CreateAdjustBill, CreateStakingBill, \
CreateStakingBill UpdatePCFBill, UpdateExchangeBill, UpdateStakingBill, UpdateAdjustBill, AllBillType
from service.bill import update_bill, create_staking from service.bill import update_bill, create_staking
from tools.jwt_tools import User from tools.jwt_tools import User
...@@ -17,7 +17,7 @@ router = APIRouter() ...@@ -17,7 +17,7 @@ router = APIRouter()
@router.post('/pcf/', @router.post('/pcf/',
response_model=Response[PCFBillRes], response_model=Response[PCFBill],
tags=['新增'], tags=['新增'],
summary='添加[申购/赎回]账目', summary='添加[申购/赎回]账目',
description='添加申购赎回账目') description='添加申购赎回账目')
...@@ -27,13 +27,13 @@ async def create_pcf( ...@@ -27,13 +27,13 @@ async def create_pcf(
fund_collect: AgnosticCollection = Depends(get_fund_collect), fund_collect: AgnosticCollection = Depends(get_fund_collect),
bill_collect: AgnosticCollection = Depends(get_bill_collect), bill_collect: AgnosticCollection = Depends(get_bill_collect),
): ):
assert item.bill_type == BillType.sub or item.bill_type == BillType.redemption, "枚举错误" assert item.bill_type == PCFBillType.sub or item.bill_type == PCFBillType.redemption, "枚举错误"
query = {"id": item.fund_id, "user_id": user.id} query = {"id": item.fund_id, "user_id": user.id}
fund = await fund_collect.find_one(query) fund = await fund_collect.find_one(query)
assert fund, NotFundError() assert fund, NotFundError()
filter_asset = list(filter(lambda x: x["currency"] == item.currency, fund["assets"])) filter_asset = list(filter(lambda x: x["currency"] == item.currency, fund["assets"]))
if filter_asset: if filter_asset:
inc = item.volume if item.bill_type == BillType.sub else -item.volume inc = item.volume if item.bill_type == PCFBillType.sub else -item.volume
assert filter_asset[0]["volume"] + inc >= 0, "余额不足" assert filter_asset[0]["volume"] + inc >= 0, "余额不足"
update = {"$inc": {"assets.$.volume": inc}} update = {"$inc": {"assets.$.volume": inc}}
await fund_collect.update_one({**query, "assets.currency": item.currency}, update) await fund_collect.update_one({**query, "assets.currency": item.currency}, update)
...@@ -41,13 +41,13 @@ async def create_pcf( ...@@ -41,13 +41,13 @@ async def create_pcf(
update = {"$push": {"assets": {"currency": item.currency, "volume": item.volume}}} update = {"$push": {"assets": {"currency": item.currency, "volume": item.volume}}}
await fund_collect.update_one(query, update) await fund_collect.update_one(query, update)
market_value = item.volume * item.price market_value = item.volume * item.price
prc = PCFBillRes(user_id=user.id, fund_share=market_value / fund["nav"], market_value=market_value, **item.dict()) prc = PCFBill(user_id=user.id, fund_share=market_value / fund["nav"], market_value=market_value, **item.dict())
await bill_collect.insert_one(prc.dict()) await bill_collect.insert_one(prc.dict())
return Response[PCFBillRes](data=prc.dict()) return Response[PCFBill](data=prc.dict())
@router.post('/exchange/', @router.post('/exchange/',
response_model=Response[ExchangeBillRes], response_model=Response[ExchangeBill],
tags=['新增'], tags=['新增'],
summary='添加置换币账目', summary='添加置换币账目',
description='添加置换币账目') description='添加置换币账目')
...@@ -78,14 +78,14 @@ async def create_exchange( ...@@ -78,14 +78,14 @@ async def create_exchange(
result = await fund_collect.bulk_write([update_input, update_output]) result = await fund_collect.bulk_write([update_input, update_output])
logger.info(result.modified_count) logger.info(result.modified_count)
input_value, output_value = item.input_volume * item.input_price, item.output_volume * item.output_price input_value, output_value = item.input_volume * item.input_price, item.output_volume * item.output_price
exchange_bill = ExchangeBillRes(user_id=user.id, input_value=input_value, output_value=output_value, exchange_bill = ExchangeBill(user_id=user.id, input_value=input_value, output_value=output_value,
profit=output_value - input_value, **item.dict()) profit=output_value - input_value, **item.dict())
await bill_collect.insert_one(exchange_bill.dict()) await bill_collect.insert_one(exchange_bill.dict())
return Response[ExchangeBillRes](data=exchange_bill.dict()) return Response[ExchangeBill](data=exchange_bill.dict())
@router.post('/adjust/', @router.post('/adjust/',
response_model=Response[AdjustBillRes], response_model=Response[AdjustBill],
tags=['新增'], tags=['新增'],
summary='添加调整账目', summary='添加调整账目',
description='添加调整账目') description='添加调整账目')
...@@ -106,14 +106,14 @@ async def create_adjust( ...@@ -106,14 +106,14 @@ async def create_adjust(
{"$inc": {"adjust_assets.$.volume": item.volume}} {"$inc": {"adjust_assets.$.volume": item.volume}}
) )
logger.info(f"inc_result={inc_result.modified_count}") logger.info(f"inc_result={inc_result.modified_count}")
adjust_bill = AdjustBillRes(user_id=user.id, **item.dict()) adjust_bill = AdjustBill(user_id=user.id, **item.dict())
await bill_collect.insert_one(adjust_bill.dict()) await bill_collect.insert_one(adjust_bill.dict())
response = Response[AdjustBillRes](data=adjust_bill.dict()) response = Response[AdjustBill](data=adjust_bill.dict())
return response return response
@router.post('/staking/', @router.post('/staking/',
response_model=Response[StakingBillRes], response_model=Response[StakingBill],
tags=['新增'], tags=['新增'],
summary='添加质押账目', summary='添加质押账目',
description='添加质押账目') description='添加质押账目')
...@@ -124,13 +124,13 @@ async def create_staking_api( ...@@ -124,13 +124,13 @@ async def create_staking_api(
bill_collect: AgnosticCollection = Depends(get_bill_collect), bill_collect: AgnosticCollection = Depends(get_bill_collect),
): ):
staking_bill = await create_staking(item, user.id, fund_collect, bill_collect) staking_bill = await create_staking(item, user.id, fund_collect, bill_collect)
response = Response[StakingBillRes](data=staking_bill.dict()) response = Response[StakingBill](data=staking_bill.dict())
return response return response
@router.put('/pcf/{fund_id}/', @router.put('/pcf/{fund_id}/',
tags=['更新'], tags=['更新'],
response_model=Response[PCFBillRes], response_model=Response[PCFBill],
summary='更新申购赎回记录', summary='更新申购赎回记录',
description='') description='')
async def update_pcf_bill( async def update_pcf_bill(
...@@ -148,14 +148,14 @@ async def update_pcf_bill( ...@@ -148,14 +148,14 @@ async def update_pcf_bill(
update_data=update_item, update_data=update_item,
fund_collect=fund_collect, fund_collect=fund_collect,
bill_collect=bill_collect, bill_collect=bill_collect,
res_model=PCFBillRes res_model=PCFBill
) )
return response return response
@router.put('/exchange/{fund_id}/', @router.put('/exchange/{fund_id}/',
tags=['更新'], tags=['更新'],
response_model=Response[ExchangeBillRes], response_model=Response[ExchangeBill],
summary='更新置换记录', summary='更新置换记录',
description='') description='')
async def update_exchange_bill( async def update_exchange_bill(
...@@ -173,14 +173,14 @@ async def update_exchange_bill( ...@@ -173,14 +173,14 @@ async def update_exchange_bill(
update_data=update_item, update_data=update_item,
fund_collect=fund_collect, fund_collect=fund_collect,
bill_collect=bill_collect, bill_collect=bill_collect,
res_model=ExchangeBillRes res_model=ExchangeBill
) )
return response return response
@router.put('/staking/{fund_id}/', @router.put('/staking/{fund_id}/',
tags=['更新'], tags=['更新'],
response_model=Response[StakingBillRes], response_model=Response[StakingBill],
summary='更新质押记录', summary='更新质押记录',
description='') description='')
async def update_staking_bill( async def update_staking_bill(
...@@ -198,14 +198,14 @@ async def update_staking_bill( ...@@ -198,14 +198,14 @@ async def update_staking_bill(
update_data=update_item, update_data=update_item,
fund_collect=fund_collect, fund_collect=fund_collect,
bill_collect=bill_collect, bill_collect=bill_collect,
res_model=StakingBillRes res_model=StakingBill
) )
return response return response
@router.put('/adjust/{fund_id}/', @router.put('/adjust/{fund_id}/',
tags=['更新'], tags=['更新'],
response_model=Response[AdjustBillRes], response_model=Response[AdjustBill],
summary='更新调整记录', summary='更新调整记录',
description='') description='')
async def update_adjust_bill( async def update_adjust_bill(
...@@ -223,24 +223,21 @@ async def update_adjust_bill( ...@@ -223,24 +223,21 @@ async def update_adjust_bill(
update_data=update_item, update_data=update_item,
fund_collect=fund_collect, fund_collect=fund_collect,
bill_collect=bill_collect, bill_collect=bill_collect,
res_model=AdjustBillRes res_model=AdjustBill
) )
return response return response
@router.get('/{fund_id}/', @router.get('/{fund_id}/',
tags=["查询"], tags=["查询"],
# response_model=PageResponse[Any], response_model=PageResponse[Union[PCFBill, ExchangeBill, StakingBill, AdjustBill]],
response_model=Union[
PageResponse[PCFBillRes], PageResponse[ExchangeBillRes], PageResponse[StakingBillRes], PageResponse[
AdjustBillRes]],
summary='查询账单记录', summary='查询账单记录',
description='查询账单记录') description='查询账单记录')
async def query_bill( async def query_bill(
fund_id: str, fund_id: str,
sort_by: SortParams = Depends(SortParams), sort_by: SortParams = Depends(SortParams),
filter_time: FilterTime = Depends(FilterTime), filter_time: FilterTime = Depends(FilterTime),
query: List[BillType] = Query(default=BillType.all(), description='账单类型'), query: List[AllBillType] = Query(default=AllBillType.all(), description='账单类型'),
page: Page = Depends(Page), page: Page = Depends(Page),
user: User = Depends(get_current_user), user: User = Depends(get_current_user),
bill_collect: AgnosticCollection = Depends(get_bill_collect), bill_collect: AgnosticCollection = Depends(get_bill_collect),
...@@ -265,7 +262,7 @@ async def query_bill( ...@@ -265,7 +262,7 @@ async def query_bill(
async def query_bill( async def query_bill(
fund_id: str, fund_id: str,
bill_id: str, bill_id: str,
bill_type: BillType, bill_type: AllBillType,
bill_collect: AgnosticCollection = Depends(get_bill_collect), bill_collect: AgnosticCollection = Depends(get_bill_collect),
user: User = Depends(get_current_user) user: User = Depends(get_current_user)
): ):
......
...@@ -8,8 +8,9 @@ from pymongo import ReturnDocument ...@@ -8,8 +8,9 @@ from pymongo import ReturnDocument
from exception.db import NotFundError from exception.db import NotFundError
from model import Response, PageResponse, Page from model import Response, PageResponse, Page
from model.fund import FundType, CreateFund, StakingFund, NormalFund, UpdateFund, FundStatus from model.fund import FundType, StakingFund, NormalFund, FundStatus
from dependencies import get_current_user, get_fund_collect, get_scheduler from dependencies import get_current_user, get_fund_collect, get_scheduler
from schema.fund import CreateFund, UpdateFund
from service.scheduler import calculate_nav_task, delete_nav_task from service.scheduler import calculate_nav_task, delete_nav_task
from tools.jwt_tools import User from tools.jwt_tools import User
...@@ -71,7 +72,6 @@ async def update( ...@@ -71,7 +72,6 @@ async def update(
data = await fund_collect.find_one_and_update({'id': fund_id, 'user_id': user.id}, {'$set': db_update_data}, data = await fund_collect.find_one_and_update({'id': fund_id, 'user_id': user.id}, {'$set': db_update_data},
return_document=ReturnDocument.AFTER) return_document=ReturnDocument.AFTER)
assert data, NotFundError() assert data, NotFundError()
# return fund_type_map[data['fund_type']](data=fund_type_map[data['fund_type']](**data))
response_model = fund_type_map[data['fund_type']] response_model = fund_type_map[data['fund_type']]
return Response[response_model](data=response_model(**data)) return Response[response_model](data=response_model(**data))
...@@ -91,18 +91,20 @@ async def get( ...@@ -91,18 +91,20 @@ async def get(
@router.get('/', @router.get('/',
response_model=Union[PageResponse[StakingFund], PageResponse[NormalFund]], response_model=PageResponse[Union[StakingFund, NormalFund]],
summary='查询所有基金', summary='查询所有基金',
description='查询所有基金') description='查询所有基金')
async def get( async def get(
page: Page = Depends(Page), page: Page = Depends(Page),
org_id: Optional[int] = Query(default=None, description='机构id'), org_id: Optional[int] = Query(default=None, description='机构id'),
fund_type: FundType = FundType.staking, fund_type: Optional[FundType] = Query(default=None, description='基金类型'),
fund_status: FundStatus = None, fund_status: FundStatus = None,
user: User = Depends(get_current_user), user: User = Depends(get_current_user),
fund_collect: AgnosticCollection = Depends(get_fund_collect) fund_collect: AgnosticCollection = Depends(get_fund_collect)
): ):
query = {"user_id": user.id, "fund_type": fund_type} query = {"user_id": user.id}
if fund_type:
query.update({"fund_type": fund_type})
if fund_status: if fund_status:
query.update({"fund_status": fund_status}) query.update({"fund_status": fund_status})
if org_id is not None: if org_id is not None:
...@@ -112,5 +114,5 @@ async def get( ...@@ -112,5 +114,5 @@ async def get(
cursor = cursor.skip(skip).sort([('create_time', -1)]).limit(page.page_size) cursor = cursor.skip(skip).sort([('create_time', -1)]).limit(page.page_size)
result = await cursor.to_list(length=None) result = await cursor.to_list(length=None)
response = PageResponse[fund_type_map[fund_type]](data=result, total=len(result), **page.dict()) response = PageResponse[Union[StakingFund, NormalFund]](data=result, total=len(result), **page.dict())
return response return response
...@@ -69,3 +69,14 @@ class BaseCreateModel(BaseModel): ...@@ -69,3 +69,14 @@ class BaseCreateModel(BaseModel):
class Config: class Config:
orm_mode = True orm_mode = True
class MyBaseModel(BaseModel):
id: str = Field(default_factory=lambda: uuid.uuid1().__str__(), description='唯一ID')
create_time: int = Field(default_factory=lambda: int(datetime.datetime.utcnow().timestamp()),
description='创建时间')
update_time: int = Field(default_factory=lambda: int(datetime.datetime.utcnow().timestamp()),
description='更新时间')
class Config:
orm_mode = True
import datetime import datetime
from enum import Enum
from typing import Optional
from pydantic import BaseModel, Field from pydantic import Field
from model import BaseCreateModel from model import MyBaseModel
from schema.bill import PCFBillType, BillType
class BillType(str, Enum): # 数据库类型 / 接口返回类型
# 申购 class PCFBill(MyBaseModel):
sub = "sub"
# 赎回
redemption = "redemption"
# 兑换
exchange = "exchange"
# 质押
staking = "staking"
# 调整
adjust = "adjust"
@staticmethod
def all():
return list(map(lambda c: c.value, BillType))
# 接口传入模型
# 创建申购赎回记录
class CreatePCFBill(BaseModel):
fund_id: str = Field(None, description='基金id')
email: str = Field(None, description='客户邮箱')
bill_type: BillType = Field(..., description='账目类型')
currency: str = Field(None, description='币种')
volume: float = Field(..., description='资产数量')
price: float = Field(..., description="价格")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
# 传入数据库类型 / 接口返回类型
class PCFBillRes(CreatePCFBill, BaseCreateModel):
"""申购赎回""" """申购赎回"""
user_id: str user_id: str
fund_share: float = Field(..., description="基金份额") fund_share: float = Field(..., description="基金份额")
market_value: float = Field(..., description="市值") market_value: float = Field(..., description="市值")
fund_id: str = Field(..., description='基金id')
# 置换币记录 传入数据库类型 / 接口返回类型 email: str = Field(..., description='客户邮箱')
class CreateExchangeBill(BaseModel): bill_type: PCFBillType = Field(..., description='账目类型')
fund_id: str = Field(None, description='基金id') currency: str = Field(..., description='币种')
input_currency: str = Field(..., description="投入币种") volume: float = Field(..., description='资产数量')
input_price: float = Field(..., description="投入币种价格") price: float = Field(..., description="价格")
input_volume: float = Field(..., description="投入数量")
output_currency: str = Field(..., description="输出币种")
output_price: float = Field(..., description="输出币种价格")
output_volume: float = Field(..., description="输出数量")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间') record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注") remark: str = Field(default="", description="备注")
class ExchangeBillRes(CreateExchangeBill, BaseCreateModel): class ExchangeBill(MyBaseModel):
"""置换账户""" """置换账户"""
user_id: str user_id: str
input_value: float = Field(..., description="投入价值") input_value: float = Field(..., description="投入价值")
...@@ -68,80 +31,25 @@ class ExchangeBillRes(CreateExchangeBill, BaseCreateModel): ...@@ -68,80 +31,25 @@ class ExchangeBillRes(CreateExchangeBill, BaseCreateModel):
bill_type: BillType = BillType.exchange bill_type: BillType = BillType.exchange
class CreateStakingBill(BaseModel): class StakingBill(MyBaseModel):
fund_id: str = Field(None, description='基金id')
currency: str = Field(default="ETH", description='币种')
volume: float = Field(default=32, description='数量')
pub_key: str = Field(..., description='节点key')
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
class StakingBillRes(CreateStakingBill, BaseCreateModel):
"""质押账目""" """质押账目"""
user_id: str user_id: str
bill_type: BillType = BillType.staking bill_type: BillType = BillType.staking
fund_id: str = Field(..., description='基金id')
class CreateAdjustBill(BaseModel): currency: str = Field(default="ETH", description='币种')
fund_id: str = Field(None, description='基金id') volume: float = Field(default=32, description='数量')
currency: str = Field('USD', description='币种') pub_key: str = Field(..., description='节点key')
volume: float = Field(..., description='资产数量')
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间') record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注") remark: str = Field(default="", description="备注")
class AdjustBillRes(CreateAdjustBill, BaseCreateModel): class AdjustBill(MyBaseModel):
user_id: str user_id: str
bill_type: BillType = BillType.adjust bill_type: BillType = BillType.adjust
fund_id: str = Field(..., description='基金id')
# 更新model currency: str = Field('USD', description='币种')
class UpdatePCFBill(BaseModel): volume: float = Field(..., description='资产数量')
email: Optional[str] = Field(None, description='客户邮箱')
currency: Optional[str] = Field(None, description='币种')
volume: Optional[float] = Field(None, description='资产数量')
price: Optional[float] = Field(None, description="价格")
fund_share: Optional[float] = Field(None, description="基金份额")
market_value: Optional[float] = Field(None, description="市值")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
class Config:
orm_mode = True
class UpdateExchangeBill(BaseModel):
input_currency: Optional[str] = Field(None, description="投入币种")
input_price: Optional[float] = Field(None, description="投入币种价格")
input_volume: Optional[float] = Field(None, description="投入数量")
output_currency: Optional[str] = Field(None, description="输出币种")
output_price: Optional[float] = Field(None, description="输出币种价格")
output_volume: Optional[float] = Field(None, description="输出数量")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
class Config:
orm_mode = True
class UpdateStakingBill(BaseModel):
currency: Optional[str] = Field(default="ETH", description='币种')
volume: Optional[float] = Field(None, description='数量')
price: float = Field(None, description="价格")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
class Config:
orm_mode = True
class UpdateAdjustBill(BaseModel):
currency: Optional[str] = Field(None, description='币种')
volume: Optional[float] = Field(None, description='资产数量')
price: Optional[float] = Field(None, description="价格")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间') record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注") remark: str = Field(default="", description="备注")
class Config:
orm_mode = True
import datetime import datetime
from enum import Enum
from typing import List, Optional from typing import List, Optional
from pydantic import BaseModel, Field from pydantic import Field
from model import BaseCreateModel from model import MyBaseModel
from model.asset import NormalAsset, BaseCoinAssetItem from model.asset import BaseCoinAssetItem
from model.node import BaseNode from model.node import BaseNode
from schema.fund import FundType, FundStatus
class FundType(str, Enum): class BaseFundItem(MyBaseModel):
staking = 'staking'
normal = 'normal'
class FundStatus(str, Enum):
active = 'active'
deactivate = 'deactivate'
class BaseFundItem(BaseModel):
org_id: int = Field(..., description="机构id") org_id: int = Field(..., description="机构id")
name: str = Field(..., description='基金名称') name: str = Field(..., description='基金名称')
fund_type: FundType = Field(default=FundType.staking, description='基金类型') fund_type: FundType = Field(default=FundType.staking, description='基金类型')
fund_status: FundStatus = Field(default=FundStatus.active, description='基金状态') fund_status: FundStatus = Field(default=FundStatus.active, description='基金状态')
base_coin: str = Field(default='USD', description='基准币种') base_coin: str = Field(default='USD', description='基准币种')
base_nav: float = Field(default=1, description='初始净值') base_nav: float = Field(default=1, description='初始净值')
establishment_time: int = Field(default_factory=lambda: int(datetime.datetime.utcnow().timestamp()), description="成立日期") establishment_time: int = Field(default_factory=lambda: int(datetime.datetime.utcnow().timestamp()),
description="成立日期")
settlement_time: str = Field(default='08:00', description='结算时间') settlement_time: str = Field(default='08:00', description='结算时间')
# 接口传入模型
# 创建
class CreateFund(BaseFundItem):
pass
# nodes: List[BaseNode] = Field(default=[], description='绑定节点')
# 更新
class UpdateFund(BaseModel):
name: Optional[str] = Field(None, description='基金名称')
fund_type: Optional[FundType] = Field(None, description='基金类型')
fund_status: FundStatus = Field(None, description='基金状态')
base_coin: Optional[str] = Field(None, description='基准币种')
nav: Optional[float] = Field(None, description='当前净值')
base_nav: Optional[float] = Field(None, description='初始净值')
settlement_time: Optional[str] = Field(None, description='结算时间')
establishment_time: Optional[int] = Field(None, description="成立日期")
class Config:
orm_mode = True
# 传入数据库类型 / 接口返回类型 # 传入数据库类型 / 接口返回类型
class NormalFund(BaseFundItem, BaseCreateModel): class NormalFund(BaseFundItem):
user_id: str user_id: str
user_email: str user_email: str
nav: Optional[float] = Field(default=1, description='当前净值') nav: Optional[float] = Field(default=1, description='当前净值')
assets: List[BaseCoinAssetItem] = Field(default=[], description='持仓') assets: List[BaseCoinAssetItem] = Field(default=[], description='持仓')
class StakingFund(BaseFundItem, BaseCreateModel): class StakingFund(BaseFundItem):
user_id: str user_id: str
user_email: str user_email: str
nav: Optional[float] = Field(default=1, description='当前净值') nav: Optional[float] = Field(default=1, description='当前净值')
......
import datetime
from enum import Enum
from typing import Optional
from pydantic import BaseModel, Field
class PCFBillType(str, Enum):
# 申购
sub = "sub"
# 赎回
redemption = "redemption"
class BillType(str, Enum):
# 兑换
exchange = "exchange"
# 质押
staking = "staking"
# 调整
adjust = "adjust"
class AllBillType(str, Enum):
# 申购
sub = "sub"
# 赎回
redemption = "redemption"
# 兑换
exchange = "exchange"
# 质押
staking = "staking"
# 调整
adjust = "adjust"
@staticmethod
def all():
return list(map(lambda c: c.value, BillType))
# 创建申购赎回记录
class CreatePCFBill(BaseModel):
fund_id: str = Field(..., description='基金id')
email: str = Field(..., description='客户邮箱')
bill_type: PCFBillType = Field(..., description='账目类型')
currency: str = Field(..., description='币种')
volume: float = Field(..., description='资产数量')
price: float = Field(..., description="价格")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
class CreateExchangeBill(BaseModel):
fund_id: str = Field(None, description='基金id')
input_currency: str = Field(..., description="投入币种")
input_price: float = Field(..., description="投入币种价格")
input_volume: float = Field(..., description="投入数量")
output_currency: str = Field(..., description="输出币种")
output_price: float = Field(..., description="输出币种价格")
output_volume: float = Field(..., description="输出数量")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
class CreateStakingBill(BaseModel):
fund_id: str = Field(..., description='基金id')
currency: str = Field(default="ETH", description='币种')
volume: float = Field(default=32, description='数量')
pub_key: str = Field(..., description='节点key')
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
class CreateAdjustBill(BaseModel):
fund_id: str = Field(..., description='基金id')
currency: str = Field('USD', description='币种')
volume: float = Field(..., description='资产数量')
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
# 更新schema
class UpdatePCFBill(BaseModel):
email: Optional[str] = Field(None, description='客户邮箱')
currency: Optional[str] = Field(None, description='币种')
volume: Optional[float] = Field(None, description='资产数量')
price: Optional[float] = Field(None, description="价格")
fund_share: Optional[float] = Field(None, description="基金份额")
market_value: Optional[float] = Field(None, description="市值")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
class Config:
orm_mode = True
class UpdateExchangeBill(BaseModel):
input_currency: Optional[str] = Field(None, description="投入币种")
input_price: Optional[float] = Field(None, description="投入币种价格")
input_volume: Optional[float] = Field(None, description="投入数量")
output_currency: Optional[str] = Field(None, description="输出币种")
output_price: Optional[float] = Field(None, description="输出币种价格")
output_volume: Optional[float] = Field(None, description="输出数量")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
class Config:
orm_mode = True
class UpdateStakingBill(BaseModel):
currency: Optional[str] = Field(None, description='币种')
volume: Optional[float] = Field(None, description='数量')
price: float = Field(None, description="价格")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
class Config:
orm_mode = True
class UpdateAdjustBill(BaseModel):
currency: Optional[str] = Field(None, description='币种')
volume: Optional[float] = Field(None, description='资产数量')
price: Optional[float] = Field(None, description="价格")
record_time: str = Field(default_factory=lambda: str(datetime.datetime.utcnow().date()), description='记录时间')
remark: str = Field(default="", description="备注")
class Config:
orm_mode = True
# 接口传入模型
import datetime
from enum import Enum
from typing import Optional
from pydantic import BaseModel, Field
class FundType(str, Enum):
staking = 'staking'
normal = 'normal'
class FundStatus(str, Enum):
active = 'active'
deactivate = 'deactivate'
# 创建
class CreateFund(BaseModel):
org_id: int = Field(..., description="机构id")
name: str = Field(..., description='基金名称')
fund_type: FundType = Field(default=FundType.staking, description='基金类型')
fund_status: FundStatus = Field(default=FundStatus.active, description='基金状态')
base_coin: str = Field(default='USD', description='基准币种')
base_nav: float = Field(default=1, description='初始净值')
establishment_time: int = Field(default_factory=lambda: int(datetime.datetime.utcnow().timestamp()),
description="成立日期")
settlement_time: str = Field(default='08:00', description='结算时间')
# 更新
class UpdateFund(BaseModel):
name: Optional[str] = Field(None, description='基金名称')
fund_type: Optional[FundType] = Field(None, description='基金类型')
fund_status: FundStatus = Field(None, description='基金状态')
base_coin: Optional[str] = Field(None, description='基准币种')
nav: Optional[float] = Field(None, description='当前净值')
base_nav: Optional[float] = Field(None, description='初始净值')
settlement_time: Optional[str] = Field(None, description='结算时间')
establishment_time: Optional[int] = Field(None, description="成立日期")
class Config:
orm_mode = True
import datetime import datetime
from typing import TypeVar, Generic, Type from typing import TypeVar, Type
from motor.core import AgnosticCollection from motor.core import AgnosticCollection
from pymongo import ReturnDocument from pymongo import ReturnDocument
from exception.db import NotFundError from exception.db import NotFundError
from model import Response from model import Response
from model.bill import CreateStakingBill, StakingBillRes from model.bill import StakingBill
from schema.bill import CreateStakingBill
DataT = TypeVar('DataT') DataT = TypeVar('DataT')
...@@ -27,7 +28,7 @@ async def create_staking( ...@@ -27,7 +28,7 @@ async def create_staking(
# else: # else:
# update = {"$push": {"assets": {"currency": item.currency, "volume": -item.volume}}} # update = {"$push": {"assets": {"currency": item.currency, "volume": -item.volume}}}
# await fund_collect.update_one(query, update) # await fund_collect.update_one(query, update)
staking_bill = StakingBillRes(user_id=user_id, **item.dict()) staking_bill = StakingBill(user_id=user_id, **item.dict())
await bill_collect.insert_one(staking_bill.dict()) await bill_collect.insert_one(staking_bill.dict())
return staking_bill return staking_bill
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment