| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391 |
- # app/services/order_service.py
- import uuid
- import json
- from datetime import datetime, timedelta
- from typing import List, Optional
- from redis.asyncio import Redis
- from sqlalchemy.ext.asyncio import AsyncSession
- from sqlalchemy import select
- from app.core.logger import logger
- from app.utils.search import apply_keyword_search_stmt
- from app.utils.pagination import paginate
- from app.core.biz_exception import NotFoundError, BizLogicError, PermissionDeniedError
- from app.models.user import VasUser
- from app.models.order import VasOrder
- from app.models.vas_task import VasTask
- from app.models.product import VasProduct
- from app.models.payment import VasPayment
- 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.agency_service import AgencyService
- class OrderService:
- @staticmethod
- async def create(
- db: AsyncSession,
- data: VasOrderCreate,
- product: VasProduct,
- auth_user: VasUser,
- redis_client: Redis,
- ) -> VasOrder:
- """
- 前台散客自主下单 (公海订单)
- """
- if not auth_user.email:
- raise BizLogicError(
- "Your account must be linked to an email address before you can place an order."
- )
- 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 ""
- order = VasOrder(
- id=order_id,
- **data.dict(),
- product_name=safe_product_name,
- base_amount=product.price_amount,
- base_currency=product.price_currency,
- adjustment_delta=0,
- final_amount=product.price_amount,
- user_id=auth_user.id,
- channel_type='website', # 官网公海
- handler_id=None, # 无专人对接,销售提成甲乙双方对半平分
- developer_id=None, # 订单不硬绑开发者ID,由商品绑定插件动态解析技术分成归属
- settlement_status='unsettled',
- )
- db.add(order)
- await db.commit()
- await db.refresh(order)
- 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
- @staticmethod
- async def create_by_admin(
- db: AsyncSession,
- data: VasOrderCreateAdmin,
- product: VasProduct,
- auth_user: VasUser
- ) -> 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 channel orders must specify agency_id")
- agency = await AgencyService.get(db, agency_id)
- if not agency:
- raise BizLogicError(f"Agency not found: {agency_id}")
- if agency.status != 1:
- raise BizLogicError(f"Agency '{agency.name}' is currently suspended")
-
- # 专属对接人绑定 (中介拓展人独享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"Agency order amount ({final_amount/100:.2f}) cannot be lower than the minimum floor price ({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]}"
- safe_product_name = (product.title[:100]) if product.title else ""
- order = VasOrder(
- id=order_id,
- product_id=data.product_id,
- user_inputs=data.user_inputs,
- status="paid",
- product_name=safe_product_name,
- base_amount=product.price_amount,
- base_currency=product.price_currency,
- adjustment_delta=final_amount - product.price_amount,
- final_amount=final_amount,
- 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 安全修复 =====
- raw_inputs = order.user_inputs
- if isinstance(raw_inputs, str):
- try:
- order.user_inputs = json.loads(raw_inputs)
- except Exception:
- order.user_inputs = {}
- elif raw_inputs is None or not isinstance(raw_inputs, dict):
- order.user_inputs = {}
- order.user_inputs["_admin_bypass"] = {
- "enabled": True,
- "by": auth_user.id,
- "at": datetime.utcnow().isoformat(),
- "reason": "admin manual order",
- "channel_type": channel_type,
- "handler_id": handler_id,
- }
-
- db.add(order)
- await WebhookService._create_task_if_not_exists(db, order)
-
- await db.commit()
- await db.refresh(order)
- 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
- @staticmethod
- 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)
- order = (await db.execute(stmt)).scalar_one_or_none()
- if not order:
- logger.warning(f"⚠️ [ORDER] Price adjust failed: Order {order_id} not found")
- raise NotFoundError("Order not exist")
- if order.status != "pending":
- logger.warning(f"⚠️ [ORDER] Price adjust failed: Order {order_id} status is {order.status} (expected pending)")
- raise BizLogicError(message="Order not adjustable")
- new_final = order.base_amount + payload.adjustment_delta
- if new_final <= 0:
- raise BizLogicError(message="final_amount must be > 0")
- order.adjustment_delta = payload.adjustment_delta
- order.final_amount = new_final
- # 是否已有 pending payment
- stmt = select(VasPayment).where(
- VasPayment.order_id == order.id,
- VasPayment.status == "pending",
- )
- active_payment = (await db.execute(stmt)).scalar_one_or_none()
- if active_payment:
- active_payment.status = "expired"
- await db.commit()
- await db.refresh(order)
- logger.info(f"💰 [ORDER] Adjusted order price: id={order.id} new={order.final_amount} delta={payload.adjustment_delta}")
- return order
- @staticmethod
- async def get(db: AsyncSession, order_id: str) -> Optional[VasOrder]:
- stmt = select(VasOrder).where(VasOrder.id == order_id)
- return (await db.execute(stmt)).scalar_one_or_none()
- @staticmethod
- async def get_authorized_order(
- db: AsyncSession,
- order_id: str,
- current_user: VasUser
- ) -> VasOrder:
- order = await OrderService.get(db, order_id)
- if not order:
- raise NotFoundError("Order not found")
- if current_user.role != "admin" and str(order.user_id) != str(current_user.id):
- raise PermissionDeniedError("Permission denied: You do not have access to this order")
- return order
- @staticmethod
- async def list_by_user(
- db: AsyncSession,
- user_id: str,
- page: int = 0,
- size: int = 10,
- keyword: Optional[str] = None,
- ):
- stmt = select(VasOrder).where(VasOrder.user_id == user_id)
- stmt = apply_keyword_search_stmt(
- stmt=stmt,
- model=VasOrder,
- keyword=keyword,
- fields=["id", "user_id", "product_name", "user_inputs"],
- ).order_by(VasOrder.created_at.desc())
- return await paginate(db, stmt, page, size)
- @staticmethod
- async def list_all(
- db: AsyncSession,
- page: int = 0,
- size: int = 10,
- keyword: Optional[str] = None,
- channel_type: Optional[str] = None,
- handler_id: Optional[str] = None,
- settlement_status: Optional[str] = None,
- ):
- 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(
- stmt=stmt,
- model=VasOrder,
- keyword=keyword,
- fields=["id", "user_id", "user_name", "product_name", "user_inputs", "handler_id", "agency_id"],
- ).order_by(VasOrder.created_at.desc())
- return await paginate(db, query, page, size)
- @staticmethod
- async def patch_user_inputs(
- db: AsyncSession,
- order_id: str,
- payload: VasOrderPatchUserInputs,
- ) -> 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] Patch user_inputs failed: Order {order_id} not found")
- raise NotFoundError("Order not exist")
- order.user_inputs = payload.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] Patched user inputs for order {order.id}, recreated tasks")
- 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
|