|
@@ -17,9 +17,10 @@ from app.models.order import VasOrder
|
|
|
from app.models.vas_task import VasTask
|
|
from app.models.vas_task import VasTask
|
|
|
from app.models.product import VasProduct
|
|
from app.models.product import VasProduct
|
|
|
from app.models.payment import VasPayment
|
|
from app.models.payment import VasPayment
|
|
|
-from app.models.product_routing import VasProductRouting
|
|
|
|
|
-from app.schemas.order import VasOrderCreate, VasOrderAdjustPrice, VasOrderPatchUserInputs
|
|
|
|
|
|
|
+from app.models.agency import VasAgency
|
|
|
|
|
+from app.schemas.order import VasOrderCreate, VasOrderCreateAdmin, VasOrderAdjustPrice, VasOrderPatchUserInputs, VasOrderUpdate
|
|
|
from app.services.webhook_service import WebhookService
|
|
from app.services.webhook_service import WebhookService
|
|
|
|
|
+from app.services.agency_service import AgencyService
|
|
|
|
|
|
|
|
|
|
|
|
|
class OrderService:
|
|
class OrderService:
|
|
@@ -32,7 +33,9 @@ class OrderService:
|
|
|
auth_user: VasUser,
|
|
auth_user: VasUser,
|
|
|
redis_client: Redis,
|
|
redis_client: Redis,
|
|
|
) -> VasOrder:
|
|
) -> VasOrder:
|
|
|
-
|
|
|
|
|
|
|
+ """
|
|
|
|
|
+ 前台散客自主下单 (公海订单)
|
|
|
|
|
+ """
|
|
|
if not auth_user.email:
|
|
if not auth_user.email:
|
|
|
raise BizLogicError(
|
|
raise BizLogicError(
|
|
|
"Your account must be linked to an email address before you can place an order."
|
|
"Your account must be linked to an email address before you can place an order."
|
|
@@ -49,65 +52,78 @@ class OrderService:
|
|
|
adjustment_delta=0,
|
|
adjustment_delta=0,
|
|
|
final_amount=product.price_amount,
|
|
final_amount=product.price_amount,
|
|
|
user_id=auth_user.id,
|
|
user_id=auth_user.id,
|
|
|
|
|
+ channel_type='website', # 官网公海
|
|
|
|
|
+ handler_id=None, # 无专人对接,销售提成甲乙双方对半平分
|
|
|
|
|
+ developer_id=None, # 订单不硬绑开发者ID,由商品绑定插件动态解析技术分成归属
|
|
|
|
|
+ settlement_status='unsettled',
|
|
|
)
|
|
)
|
|
|
|
|
|
|
|
db.add(order)
|
|
db.add(order)
|
|
|
await db.commit()
|
|
await db.commit()
|
|
|
await db.refresh(order)
|
|
await db.refresh(order)
|
|
|
|
|
|
|
|
- logger.info(f"📦 [ORDER] Created order: id={order.id} product={product.id} user={auth_user.id} amount={order.final_amount} {order.base_currency}")
|
|
|
|
|
|
|
+ logger.info(f"📦 [ORDER] Created website order: id={order.id} product={product.id} user={auth_user.id} amount={order.final_amount} {order.base_currency}")
|
|
|
return order
|
|
return order
|
|
|
|
|
|
|
|
-
|
|
|
|
|
- @staticmethod
|
|
|
|
|
- async def cancel(
|
|
|
|
|
- db: AsyncSession,
|
|
|
|
|
- order_id,
|
|
|
|
|
- ) -> VasOrder:
|
|
|
|
|
- stmt = select(VasOrder).where(VasOrder.id == order_id)
|
|
|
|
|
- order = (await db.execute(stmt)).scalar_one_or_none()
|
|
|
|
|
-
|
|
|
|
|
- if not order:
|
|
|
|
|
- raise NotFoundError("Order not exist")
|
|
|
|
|
-
|
|
|
|
|
- order.status = "closed"
|
|
|
|
|
- task_res = await db.execute(
|
|
|
|
|
- select(VasTask).where(
|
|
|
|
|
- VasTask.order_id == order.id,
|
|
|
|
|
- VasTask.status.in_(["pending", "grabbed", "running", "pause", "completed"]),
|
|
|
|
|
- )
|
|
|
|
|
- )
|
|
|
|
|
- for task in task_res.scalars().all():
|
|
|
|
|
- task.status = "cancelled"
|
|
|
|
|
-
|
|
|
|
|
- await db.commit()
|
|
|
|
|
- await db.refresh(order)
|
|
|
|
|
- logger.info(f"🚫 [ORDER] Cancelled order: id={order.id} and its associated tasks")
|
|
|
|
|
- return order
|
|
|
|
|
-
|
|
|
|
|
@staticmethod
|
|
@staticmethod
|
|
|
async def create_by_admin(
|
|
async def create_by_admin(
|
|
|
db: AsyncSession,
|
|
db: AsyncSession,
|
|
|
- data: VasOrderCreate,
|
|
|
|
|
|
|
+ data: VasOrderCreateAdmin,
|
|
|
product: VasProduct,
|
|
product: VasProduct,
|
|
|
auth_user: VasUser
|
|
auth_user: VasUser
|
|
|
) -> VasOrder:
|
|
) -> VasOrder:
|
|
|
|
|
+ """
|
|
|
|
|
+ 后台管理员/客服代客录单 (支持社交自收直客 与 中介渠道同行单)
|
|
|
|
|
+ """
|
|
|
|
|
+ channel_type = data.channel_type or "direct"
|
|
|
|
|
+ agency_id = data.agency_id if channel_type == "agency" else None
|
|
|
|
|
+
|
|
|
|
|
+ # 确定金额
|
|
|
|
|
+ final_amount = data.final_amount if (data.final_amount is not None and data.final_amount > 0) else product.price_amount
|
|
|
|
|
+
|
|
|
|
|
+ # 渠道判定与底价拦截
|
|
|
|
|
+ if channel_type == "agency":
|
|
|
|
|
+ if not agency_id:
|
|
|
|
|
+ raise BizLogicError("中介渠道单必须指定合作中介 agency_id")
|
|
|
|
|
+ agency = await AgencyService.get(db, agency_id)
|
|
|
|
|
+ if not agency:
|
|
|
|
|
+ raise BizLogicError(f"未找到中介机构: {agency_id}")
|
|
|
|
|
+ if agency.status != 1:
|
|
|
|
|
+ raise BizLogicError(f"中介机构 '{agency.name}' 已暂停合作")
|
|
|
|
|
+
|
|
|
|
|
+ # 专属对接人绑定 (中介拓展人独享40%提成)
|
|
|
|
|
+ handler_id = agency.owner_id
|
|
|
|
|
+
|
|
|
|
|
+ # 底价校验
|
|
|
|
|
+ effective_floor = agency.min_floor_price if agency.min_floor_price > 0 else (getattr(product, 'min_floor_price', 0) or 0)
|
|
|
|
|
+ if effective_floor > 0 and final_amount < effective_floor:
|
|
|
|
|
+ raise BizLogicError(f"中介下单金额({final_amount/100:.2f}元)不得低于内部最低协议底价({effective_floor/100:.2f}元)")
|
|
|
|
|
+ else:
|
|
|
|
|
+ # 社交账号自收直客单 (小红书/微信私域): 默认录单人自己,亦可指定团队接单人
|
|
|
|
|
+ handler_id = data.handler_id or auth_user.id
|
|
|
|
|
+
|
|
|
order_id = f"ORD-{datetime.utcnow():%Y%m%d%H%M%S}-{uuid.uuid4().hex[:8]}"
|
|
order_id = f"ORD-{datetime.utcnow():%Y%m%d%H%M%S}-{uuid.uuid4().hex[:8]}"
|
|
|
safe_product_name = (product.title[:100]) if product.title else ""
|
|
safe_product_name = (product.title[:100]) if product.title else ""
|
|
|
order = VasOrder(
|
|
order = VasOrder(
|
|
|
id=order_id,
|
|
id=order_id,
|
|
|
- **data.dict(),
|
|
|
|
|
|
|
+ product_id=data.product_id,
|
|
|
|
|
+ user_inputs=data.user_inputs,
|
|
|
status="paid",
|
|
status="paid",
|
|
|
product_name=safe_product_name,
|
|
product_name=safe_product_name,
|
|
|
base_amount=product.price_amount,
|
|
base_amount=product.price_amount,
|
|
|
base_currency=product.price_currency,
|
|
base_currency=product.price_currency,
|
|
|
- adjustment_delta=0,
|
|
|
|
|
- final_amount=product.price_amount,
|
|
|
|
|
|
|
+ adjustment_delta=final_amount - product.price_amount,
|
|
|
|
|
+ final_amount=final_amount,
|
|
|
user_id=auth_user.id,
|
|
user_id=auth_user.id,
|
|
|
|
|
+ channel_type=channel_type,
|
|
|
|
|
+ agency_id=agency_id,
|
|
|
|
|
+ handler_id=handler_id,
|
|
|
|
|
+ developer_id=None, # 订单不硬绑开发者ID,由商品绑定插件动态解析技术分成归属
|
|
|
|
|
+ settlement_status='unsettled',
|
|
|
)
|
|
)
|
|
|
|
|
+
|
|
|
# ===== user_inputs 安全修复 =====
|
|
# ===== user_inputs 安全修复 =====
|
|
|
raw_inputs = order.user_inputs
|
|
raw_inputs = order.user_inputs
|
|
|
-
|
|
|
|
|
if isinstance(raw_inputs, str):
|
|
if isinstance(raw_inputs, str):
|
|
|
try:
|
|
try:
|
|
|
order.user_inputs = json.loads(raw_inputs)
|
|
order.user_inputs = json.loads(raw_inputs)
|
|
@@ -121,19 +137,72 @@ class OrderService:
|
|
|
"by": auth_user.id,
|
|
"by": auth_user.id,
|
|
|
"at": datetime.utcnow().isoformat(),
|
|
"at": datetime.utcnow().isoformat(),
|
|
|
"reason": "admin manual order",
|
|
"reason": "admin manual order",
|
|
|
|
|
+ "channel_type": channel_type,
|
|
|
|
|
+ "handler_id": handler_id,
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
db.add(order)
|
|
db.add(order)
|
|
|
-
|
|
|
|
|
await WebhookService._create_task_if_not_exists(db, order)
|
|
await WebhookService._create_task_if_not_exists(db, order)
|
|
|
|
|
|
|
|
await db.commit()
|
|
await db.commit()
|
|
|
await db.refresh(order)
|
|
await db.refresh(order)
|
|
|
- logger.info(f"👑 [ORDER] Admin created order: id={order.id} product={product.id} user={auth_user.id} status=paid")
|
|
|
|
|
|
|
+ logger.info(f"👑 [ORDER] Admin created order: id={order.id} product={product.id} channel={channel_type} handler={handler_id} amount={final_amount}")
|
|
|
|
|
+ return order
|
|
|
|
|
+
|
|
|
|
|
+ @staticmethod
|
|
|
|
|
+ async def cancel(
|
|
|
|
|
+ db: AsyncSession,
|
|
|
|
|
+ order_id: str,
|
|
|
|
|
+ ) -> VasOrder:
|
|
|
|
|
+ stmt = select(VasOrder).where(VasOrder.id == order_id)
|
|
|
|
|
+ order = (await db.execute(stmt)).scalar_one_or_none()
|
|
|
|
|
+
|
|
|
|
|
+ if not order:
|
|
|
|
|
+ raise NotFoundError("Order not exist")
|
|
|
|
|
+
|
|
|
|
|
+ order.status = "closed"
|
|
|
|
|
+ order.settlement_status = "unsettled"
|
|
|
|
|
+ task_res = await db.execute(
|
|
|
|
|
+ select(VasTask).where(
|
|
|
|
|
+ VasTask.order_id == order.id,
|
|
|
|
|
+ VasTask.status.in_(["pending", "grabbed", "running", "pause", "completed"]),
|
|
|
|
|
+ )
|
|
|
|
|
+ )
|
|
|
|
|
+ for task in task_res.scalars().all():
|
|
|
|
|
+ task.status = "cancelled"
|
|
|
|
|
+
|
|
|
|
|
+ await db.commit()
|
|
|
|
|
+ await db.refresh(order)
|
|
|
|
|
+ logger.info(f"🚫 [ORDER] Cancelled order: id={order.id} and its associated tasks")
|
|
|
return order
|
|
return order
|
|
|
-
|
|
|
|
|
|
|
+
|
|
|
@staticmethod
|
|
@staticmethod
|
|
|
- async def adjust_order_price(db: AsyncSession, order_id: str, payload: VasOrderAdjustPrice) -> VasOrder:
|
|
|
|
|
|
|
+ async def mark_completed(
|
|
|
|
|
+ db: AsyncSession,
|
|
|
|
|
+ order_id: str,
|
|
|
|
|
+ risk_days: int = 7
|
|
|
|
|
+ ) -> VasOrder:
|
|
|
|
|
+ """
|
|
|
|
|
+ 履约成功完成订单,并自动开启 T+N 退款风险期
|
|
|
|
|
+ """
|
|
|
|
|
+ stmt = select(VasOrder).where(VasOrder.id == order_id)
|
|
|
|
|
+ order = (await db.execute(stmt)).scalar_one_or_none()
|
|
|
|
|
+ if not order:
|
|
|
|
|
+ raise NotFoundError("Order not exist")
|
|
|
|
|
+
|
|
|
|
|
+ now = datetime.utcnow()
|
|
|
|
|
+ order.status = "completed"
|
|
|
|
|
+ order.completed_at = now
|
|
|
|
|
+ order.risk_cleared_at = now + timedelta(days=risk_days)
|
|
|
|
|
+ order.settlement_status = "eligible"
|
|
|
|
|
+
|
|
|
|
|
+ await db.commit()
|
|
|
|
|
+ await db.refresh(order)
|
|
|
|
|
+ logger.info(f"🎉 [ORDER] Order completed: id={order.id}, risk cleared at: {order.risk_cleared_at}")
|
|
|
|
|
+ return order
|
|
|
|
|
+
|
|
|
|
|
+ @staticmethod
|
|
|
|
|
+ async def adjust_order_price(db: AsyncSession, order_id: str, payload: VasOrderAdjustPrice) -> VasOrder:
|
|
|
stmt = select(VasOrder).where(VasOrder.id == order_id)
|
|
stmt = select(VasOrder).where(VasOrder.id == order_id)
|
|
|
order = (await db.execute(stmt)).scalar_one_or_none()
|
|
order = (await db.execute(stmt)).scalar_one_or_none()
|
|
|
|
|
|
|
@@ -145,27 +214,25 @@ class OrderService:
|
|
|
logger.warning(f"⚠️ [ORDER] Price adjust failed: Order {order_id} status is {order.status} (expected pending)")
|
|
logger.warning(f"⚠️ [ORDER] Price adjust failed: Order {order_id} status is {order.status} (expected pending)")
|
|
|
raise BizLogicError(message="Order not adjustable")
|
|
raise BizLogicError(message="Order not adjustable")
|
|
|
|
|
|
|
|
- # 2. 更新订单价格
|
|
|
|
|
- old_amount = order.final_amount
|
|
|
|
|
- order.adjustment_delta = payload.adjustment_delta
|
|
|
|
|
- order.final_amount = order.base_amount + payload.adjustment_delta
|
|
|
|
|
-
|
|
|
|
|
- if order.final_amount <= 0:
|
|
|
|
|
|
|
+ new_final = order.base_amount + payload.adjustment_delta
|
|
|
|
|
+ if new_final <= 0:
|
|
|
raise BizLogicError(message="final_amount must be > 0")
|
|
raise BizLogicError(message="final_amount must be > 0")
|
|
|
|
|
|
|
|
- # ② 是否已有 pending payment(幂等)
|
|
|
|
|
|
|
+ order.adjustment_delta = payload.adjustment_delta
|
|
|
|
|
+ order.final_amount = new_final
|
|
|
|
|
+
|
|
|
|
|
+ # 是否已有 pending payment
|
|
|
stmt = select(VasPayment).where(
|
|
stmt = select(VasPayment).where(
|
|
|
VasPayment.order_id == order.id,
|
|
VasPayment.order_id == order.id,
|
|
|
VasPayment.status == "pending",
|
|
VasPayment.status == "pending",
|
|
|
)
|
|
)
|
|
|
active_payment = (await db.execute(stmt)).scalar_one_or_none()
|
|
active_payment = (await db.execute(stmt)).scalar_one_or_none()
|
|
|
-
|
|
|
|
|
if active_payment:
|
|
if active_payment:
|
|
|
active_payment.status = "expired"
|
|
active_payment.status = "expired"
|
|
|
|
|
|
|
|
await db.commit()
|
|
await db.commit()
|
|
|
await db.refresh(order)
|
|
await db.refresh(order)
|
|
|
- logger.info(f"💰 [ORDER] Adjusted order price: id={order.id} old={old_amount} new={order.final_amount} delta={payload.adjustment_delta}")
|
|
|
|
|
|
|
+ logger.info(f"💰 [ORDER] Adjusted order price: id={order.id} new={order.final_amount} delta={payload.adjustment_delta}")
|
|
|
return order
|
|
return order
|
|
|
|
|
|
|
|
@staticmethod
|
|
@staticmethod
|
|
@@ -197,13 +264,23 @@ class OrderService:
|
|
|
page: int = 0,
|
|
page: int = 0,
|
|
|
size: int = 10,
|
|
size: int = 10,
|
|
|
keyword: Optional[str] = None,
|
|
keyword: Optional[str] = None,
|
|
|
|
|
+ channel_type: Optional[str] = None,
|
|
|
|
|
+ handler_id: Optional[str] = None,
|
|
|
|
|
+ settlement_status: Optional[str] = None,
|
|
|
):
|
|
):
|
|
|
stmt = select(VasOrder)
|
|
stmt = select(VasOrder)
|
|
|
|
|
+ if channel_type:
|
|
|
|
|
+ stmt = stmt.where(VasOrder.channel_type == channel_type)
|
|
|
|
|
+ if handler_id:
|
|
|
|
|
+ stmt = stmt.where(VasOrder.handler_id == handler_id)
|
|
|
|
|
+ if settlement_status:
|
|
|
|
|
+ stmt = stmt.where(VasOrder.settlement_status == settlement_status)
|
|
|
|
|
+
|
|
|
query = apply_keyword_search_stmt(
|
|
query = apply_keyword_search_stmt(
|
|
|
stmt=stmt,
|
|
stmt=stmt,
|
|
|
model=VasOrder,
|
|
model=VasOrder,
|
|
|
keyword=keyword,
|
|
keyword=keyword,
|
|
|
- fields=["id", "user_id", "user_name", "product_name", "user_inputs"],
|
|
|
|
|
|
|
+ fields=["id", "user_id", "user_name", "product_name", "user_inputs", "handler_id", "agency_id"],
|
|
|
).order_by(VasOrder.created_at.desc())
|
|
).order_by(VasOrder.created_at.desc())
|
|
|
|
|
|
|
|
return await paginate(db, query, page, size)
|
|
return await paginate(db, query, page, size)
|
|
@@ -214,7 +291,6 @@ class OrderService:
|
|
|
order_id: str,
|
|
order_id: str,
|
|
|
payload: VasOrderPatchUserInputs,
|
|
payload: VasOrderPatchUserInputs,
|
|
|
) -> VasOrder:
|
|
) -> VasOrder:
|
|
|
-
|
|
|
|
|
stmt = select(VasOrder).where(VasOrder.id == order_id)
|
|
stmt = select(VasOrder).where(VasOrder.id == order_id)
|
|
|
order = (await db.execute(stmt)).scalar_one_or_none()
|
|
order = (await db.execute(stmt)).scalar_one_or_none()
|
|
|
|
|
|
|
@@ -224,7 +300,7 @@ class OrderService:
|
|
|
|
|
|
|
|
order.user_inputs = payload.user_inputs
|
|
order.user_inputs = payload.user_inputs
|
|
|
|
|
|
|
|
- # 1️⃣ 取消旧任务
|
|
|
|
|
|
|
+ # 取消旧任务
|
|
|
task_res = await db.execute(
|
|
task_res = await db.execute(
|
|
|
select(VasTask).where(
|
|
select(VasTask).where(
|
|
|
VasTask.order_id == order.id,
|
|
VasTask.order_id == order.id,
|
|
@@ -243,3 +319,60 @@ class OrderService:
|
|
|
logger.info(f"🔄 [ORDER] Patched user inputs for order {order.id}, recreated tasks")
|
|
logger.info(f"🔄 [ORDER] Patched user inputs for order {order.id}, recreated tasks")
|
|
|
return order
|
|
return order
|
|
|
|
|
|
|
|
|
|
+ @staticmethod
|
|
|
|
|
+ async def update_order(
|
|
|
|
|
+ db: AsyncSession,
|
|
|
|
|
+ order_id: str,
|
|
|
|
|
+ data: VasOrderUpdate,
|
|
|
|
|
+ ) -> VasOrder:
|
|
|
|
|
+ stmt = select(VasOrder).where(VasOrder.id == order_id)
|
|
|
|
|
+ order = (await db.execute(stmt)).scalar_one_or_none()
|
|
|
|
|
+ if not order:
|
|
|
|
|
+ logger.warning(f"⚠️ [ORDER] Update failed: Order {order_id} not found")
|
|
|
|
|
+ raise NotFoundError("Order not exist")
|
|
|
|
|
+
|
|
|
|
|
+ if data.channel_type is not None:
|
|
|
|
|
+ order.channel_type = data.channel_type
|
|
|
|
|
+ if data.channel_type == "agency":
|
|
|
|
|
+ if data.agency_id is not None:
|
|
|
|
|
+ order.agency_id = data.agency_id.strip() if data.agency_id else None
|
|
|
|
|
+ if data.handler_id is not None:
|
|
|
|
|
+ order.handler_id = data.handler_id.strip() if data.handler_id else None
|
|
|
|
|
+ elif order.agency_id:
|
|
|
|
|
+ agency = await AgencyService.get(db, order.agency_id)
|
|
|
|
|
+ if agency and agency.owner_id:
|
|
|
|
|
+ order.handler_id = agency.owner_id
|
|
|
|
|
+ elif data.channel_type == "direct":
|
|
|
|
|
+ order.agency_id = None
|
|
|
|
|
+ if data.handler_id is not None:
|
|
|
|
|
+ order.handler_id = data.handler_id.strip() if data.handler_id else None
|
|
|
|
|
+ elif data.channel_type == "website":
|
|
|
|
|
+ order.agency_id = None
|
|
|
|
|
+ if data.handler_id is not None:
|
|
|
|
|
+ order.handler_id = data.handler_id.strip() if data.handler_id else None
|
|
|
|
|
+ else:
|
|
|
|
|
+ if data.agency_id is not None:
|
|
|
|
|
+ order.agency_id = data.agency_id.strip() if data.agency_id else None
|
|
|
|
|
+ if data.handler_id is not None:
|
|
|
|
|
+ order.handler_id = data.handler_id.strip() if data.handler_id else None
|
|
|
|
|
+
|
|
|
|
|
+ if data.status is not None:
|
|
|
|
|
+ order.status = data.status
|
|
|
|
|
+
|
|
|
|
|
+ if data.user_inputs is not None:
|
|
|
|
|
+ order.user_inputs = data.user_inputs
|
|
|
|
|
+ task_res = await db.execute(
|
|
|
|
|
+ select(VasTask).where(
|
|
|
|
|
+ VasTask.order_id == order.id,
|
|
|
|
|
+ VasTask.status.in_(["pending", "grabbed", "running", "pause", "completed"]),
|
|
|
|
|
+ )
|
|
|
|
|
+ )
|
|
|
|
|
+ for task in task_res.scalars().all():
|
|
|
|
|
+ task.status = "cancelled"
|
|
|
|
|
+ await db.flush()
|
|
|
|
|
+ await WebhookService._create_task_if_not_exists(db, order)
|
|
|
|
|
+
|
|
|
|
|
+ await db.commit()
|
|
|
|
|
+ await db.refresh(order)
|
|
|
|
|
+ logger.info(f"🔄 [ORDER] Admin updated order: id={order.id} channel={order.channel_type} handler={order.handler_id} agency={order.agency_id}")
|
|
|
|
|
+ return order
|