order_service.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. # app/services/order_service.py
  2. import uuid
  3. import json
  4. from datetime import datetime, timedelta
  5. from typing import List, Optional
  6. from redis.asyncio import Redis
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from sqlalchemy import select
  9. from app.core.logger import logger
  10. from app.utils.search import apply_keyword_search_stmt
  11. from app.utils.pagination import paginate
  12. from app.core.biz_exception import NotFoundError, BizLogicError, PermissionDeniedError
  13. from app.models.user import VasUser
  14. from app.models.order import VasOrder
  15. from app.models.vas_task import VasTask
  16. from app.models.product import VasProduct
  17. from app.models.payment import VasPayment
  18. from app.models.agency import VasAgency
  19. from app.schemas.order import VasOrderCreate, VasOrderCreateAdmin, VasOrderAdjustPrice, VasOrderPatchUserInputs, VasOrderUpdate
  20. from app.services.webhook_service import WebhookService
  21. from app.services.agency_service import AgencyService
  22. class OrderService:
  23. @staticmethod
  24. async def create(
  25. db: AsyncSession,
  26. data: VasOrderCreate,
  27. product: VasProduct,
  28. auth_user: VasUser,
  29. redis_client: Redis,
  30. ) -> VasOrder:
  31. """
  32. 前台散客自主下单 (公海订单)
  33. """
  34. if not auth_user.email:
  35. raise BizLogicError(
  36. "Your account must be linked to an email address before you can place an order."
  37. )
  38. order_id = f"ORD-{datetime.utcnow():%Y%m%d%H%M%S}-{uuid.uuid4().hex[:8]}"
  39. safe_product_name = (product.title[:100]) if product.title else ""
  40. order = VasOrder(
  41. id=order_id,
  42. **data.dict(),
  43. product_name=safe_product_name,
  44. base_amount=product.price_amount,
  45. base_currency=product.price_currency,
  46. adjustment_delta=0,
  47. final_amount=product.price_amount,
  48. user_id=auth_user.id,
  49. channel_type='website', # 官网公海
  50. handler_id=None, # 无专人对接,销售提成甲乙双方对半平分
  51. developer_id=None, # 订单不硬绑开发者ID,由商品绑定插件动态解析技术分成归属
  52. settlement_status='unsettled',
  53. )
  54. db.add(order)
  55. await db.commit()
  56. await db.refresh(order)
  57. logger.info(f"📦 [ORDER] Created website order: id={order.id} product={product.id} user={auth_user.id} amount={order.final_amount} {order.base_currency}")
  58. return order
  59. @staticmethod
  60. async def create_by_admin(
  61. db: AsyncSession,
  62. data: VasOrderCreateAdmin,
  63. product: VasProduct,
  64. auth_user: VasUser
  65. ) -> VasOrder:
  66. """
  67. 后台管理员/客服代客录单 (支持社交自收直客 与 中介渠道同行单)
  68. """
  69. channel_type = data.channel_type or "direct"
  70. agency_id = data.agency_id if channel_type == "agency" else None
  71. # 确定金额
  72. final_amount = data.final_amount if (data.final_amount is not None and data.final_amount > 0) else product.price_amount
  73. # 渠道判定与底价拦截
  74. if channel_type == "agency":
  75. if not agency_id:
  76. raise BizLogicError("Agency channel orders must specify agency_id")
  77. agency = await AgencyService.get(db, agency_id)
  78. if not agency:
  79. raise BizLogicError(f"Agency not found: {agency_id}")
  80. if agency.status != 1:
  81. raise BizLogicError(f"Agency '{agency.name}' is currently suspended")
  82. # 专属对接人绑定 (中介拓展人独享40%提成)
  83. handler_id = agency.owner_id
  84. # 底价校验
  85. effective_floor = agency.min_floor_price if agency.min_floor_price > 0 else (getattr(product, 'min_floor_price', 0) or 0)
  86. if effective_floor > 0 and final_amount < effective_floor:
  87. raise BizLogicError(f"Agency order amount ({final_amount/100:.2f}) cannot be lower than the minimum floor price ({effective_floor/100:.2f})")
  88. else:
  89. # 社交账号自收直客单 (小红书/微信私域): 默认录单人自己,亦可指定团队接单人
  90. handler_id = data.handler_id or auth_user.id
  91. order_id = f"ORD-{datetime.utcnow():%Y%m%d%H%M%S}-{uuid.uuid4().hex[:8]}"
  92. safe_product_name = (product.title[:100]) if product.title else ""
  93. order = VasOrder(
  94. id=order_id,
  95. product_id=data.product_id,
  96. user_inputs=data.user_inputs,
  97. status="paid",
  98. product_name=safe_product_name,
  99. base_amount=product.price_amount,
  100. base_currency=product.price_currency,
  101. adjustment_delta=final_amount - product.price_amount,
  102. final_amount=final_amount,
  103. user_id=auth_user.id,
  104. channel_type=channel_type,
  105. agency_id=agency_id,
  106. handler_id=handler_id,
  107. developer_id=None, # 订单不硬绑开发者ID,由商品绑定插件动态解析技术分成归属
  108. settlement_status='unsettled',
  109. )
  110. # ===== user_inputs 安全修复 =====
  111. raw_inputs = order.user_inputs
  112. if isinstance(raw_inputs, str):
  113. try:
  114. order.user_inputs = json.loads(raw_inputs)
  115. except Exception:
  116. order.user_inputs = {}
  117. elif raw_inputs is None or not isinstance(raw_inputs, dict):
  118. order.user_inputs = {}
  119. order.user_inputs["_admin_bypass"] = {
  120. "enabled": True,
  121. "by": auth_user.id,
  122. "at": datetime.utcnow().isoformat(),
  123. "reason": "admin manual order",
  124. "channel_type": channel_type,
  125. "handler_id": handler_id,
  126. }
  127. db.add(order)
  128. await WebhookService._create_task_if_not_exists(db, order)
  129. await db.commit()
  130. await db.refresh(order)
  131. logger.info(f"👑 [ORDER] Admin created order: id={order.id} product={product.id} channel={channel_type} handler={handler_id} amount={final_amount}")
  132. return order
  133. @staticmethod
  134. async def cancel(
  135. db: AsyncSession,
  136. order_id: str,
  137. ) -> VasOrder:
  138. stmt = select(VasOrder).where(VasOrder.id == order_id)
  139. order = (await db.execute(stmt)).scalar_one_or_none()
  140. if not order:
  141. raise NotFoundError("Order not exist")
  142. order.status = "closed"
  143. order.settlement_status = "unsettled"
  144. task_res = await db.execute(
  145. select(VasTask).where(
  146. VasTask.order_id == order.id,
  147. VasTask.status.in_(["pending", "grabbed", "running", "pause", "completed"]),
  148. )
  149. )
  150. for task in task_res.scalars().all():
  151. task.status = "cancelled"
  152. await db.commit()
  153. await db.refresh(order)
  154. logger.info(f"🚫 [ORDER] Cancelled order: id={order.id} and its associated tasks")
  155. return order
  156. @staticmethod
  157. async def mark_completed(
  158. db: AsyncSession,
  159. order_id: str,
  160. risk_days: int = 7
  161. ) -> VasOrder:
  162. """
  163. 履约成功完成订单,并自动开启 T+N 退款风险期
  164. """
  165. stmt = select(VasOrder).where(VasOrder.id == order_id)
  166. order = (await db.execute(stmt)).scalar_one_or_none()
  167. if not order:
  168. raise NotFoundError("Order not exist")
  169. now = datetime.utcnow()
  170. order.status = "completed"
  171. order.completed_at = now
  172. order.risk_cleared_at = now + timedelta(days=risk_days)
  173. order.settlement_status = "eligible"
  174. await db.commit()
  175. await db.refresh(order)
  176. logger.info(f"🎉 [ORDER] Order completed: id={order.id}, risk cleared at: {order.risk_cleared_at}")
  177. return order
  178. @staticmethod
  179. async def adjust_order_price(db: AsyncSession, order_id: str, payload: VasOrderAdjustPrice) -> VasOrder:
  180. stmt = select(VasOrder).where(VasOrder.id == order_id)
  181. order = (await db.execute(stmt)).scalar_one_or_none()
  182. if not order:
  183. logger.warning(f"⚠️ [ORDER] Price adjust failed: Order {order_id} not found")
  184. raise NotFoundError("Order not exist")
  185. if order.status != "pending":
  186. logger.warning(f"⚠️ [ORDER] Price adjust failed: Order {order_id} status is {order.status} (expected pending)")
  187. raise BizLogicError(message="Order not adjustable")
  188. new_final = order.base_amount + payload.adjustment_delta
  189. if new_final <= 0:
  190. raise BizLogicError(message="final_amount must be > 0")
  191. order.adjustment_delta = payload.adjustment_delta
  192. order.final_amount = new_final
  193. # 是否已有 pending payment
  194. stmt = select(VasPayment).where(
  195. VasPayment.order_id == order.id,
  196. VasPayment.status == "pending",
  197. )
  198. active_payment = (await db.execute(stmt)).scalar_one_or_none()
  199. if active_payment:
  200. active_payment.status = "expired"
  201. await db.commit()
  202. await db.refresh(order)
  203. logger.info(f"💰 [ORDER] Adjusted order price: id={order.id} new={order.final_amount} delta={payload.adjustment_delta}")
  204. return order
  205. @staticmethod
  206. async def get(db: AsyncSession, order_id: str) -> Optional[VasOrder]:
  207. stmt = select(VasOrder).where(VasOrder.id == order_id)
  208. return (await db.execute(stmt)).scalar_one_or_none()
  209. @staticmethod
  210. async def get_authorized_order(
  211. db: AsyncSession,
  212. order_id: str,
  213. current_user: VasUser
  214. ) -> VasOrder:
  215. order = await OrderService.get(db, order_id)
  216. if not order:
  217. raise NotFoundError("Order not found")
  218. if current_user.role != "admin" and str(order.user_id) != str(current_user.id):
  219. raise PermissionDeniedError("Permission denied: You do not have access to this order")
  220. return order
  221. @staticmethod
  222. async def list_by_user(
  223. db: AsyncSession,
  224. user_id: str,
  225. page: int = 0,
  226. size: int = 10,
  227. keyword: Optional[str] = None,
  228. ):
  229. stmt = select(VasOrder).where(VasOrder.user_id == user_id)
  230. stmt = apply_keyword_search_stmt(
  231. stmt=stmt,
  232. model=VasOrder,
  233. keyword=keyword,
  234. fields=["id", "user_id", "product_name", "user_inputs"],
  235. ).order_by(VasOrder.created_at.desc())
  236. return await paginate(db, stmt, page, size)
  237. @staticmethod
  238. async def list_all(
  239. db: AsyncSession,
  240. page: int = 0,
  241. size: int = 10,
  242. keyword: Optional[str] = None,
  243. channel_type: Optional[str] = None,
  244. handler_id: Optional[str] = None,
  245. settlement_status: Optional[str] = None,
  246. ):
  247. stmt = select(VasOrder)
  248. if channel_type:
  249. stmt = stmt.where(VasOrder.channel_type == channel_type)
  250. if handler_id:
  251. stmt = stmt.where(VasOrder.handler_id == handler_id)
  252. if settlement_status:
  253. stmt = stmt.where(VasOrder.settlement_status == settlement_status)
  254. query = apply_keyword_search_stmt(
  255. stmt=stmt,
  256. model=VasOrder,
  257. keyword=keyword,
  258. fields=["id", "user_id", "user_name", "product_name", "user_inputs", "handler_id", "agency_id"],
  259. ).order_by(VasOrder.created_at.desc())
  260. return await paginate(db, query, page, size)
  261. @staticmethod
  262. async def patch_user_inputs(
  263. db: AsyncSession,
  264. order_id: str,
  265. payload: VasOrderPatchUserInputs,
  266. ) -> VasOrder:
  267. stmt = select(VasOrder).where(VasOrder.id == order_id)
  268. order = (await db.execute(stmt)).scalar_one_or_none()
  269. if not order:
  270. logger.warning(f"⚠️ [ORDER] Patch user_inputs failed: Order {order_id} not found")
  271. raise NotFoundError("Order not exist")
  272. order.user_inputs = payload.user_inputs
  273. # 取消旧任务
  274. task_res = await db.execute(
  275. select(VasTask).where(
  276. VasTask.order_id == order.id,
  277. VasTask.status.in_(["pending", "grabbed", "running", "pause", "completed"]),
  278. )
  279. )
  280. for task in task_res.scalars().all():
  281. task.status = "cancelled"
  282. await db.flush()
  283. await WebhookService._create_task_if_not_exists(db, order)
  284. await db.commit()
  285. await db.refresh(order)
  286. logger.info(f"🔄 [ORDER] Patched user inputs for order {order.id}, recreated tasks")
  287. return order
  288. @staticmethod
  289. async def update_order(
  290. db: AsyncSession,
  291. order_id: str,
  292. data: VasOrderUpdate,
  293. ) -> VasOrder:
  294. stmt = select(VasOrder).where(VasOrder.id == order_id)
  295. order = (await db.execute(stmt)).scalar_one_or_none()
  296. if not order:
  297. logger.warning(f"⚠️ [ORDER] Update failed: Order {order_id} not found")
  298. raise NotFoundError("Order not exist")
  299. if data.channel_type is not None:
  300. order.channel_type = data.channel_type
  301. if data.channel_type == "agency":
  302. if data.agency_id is not None:
  303. order.agency_id = data.agency_id.strip() if data.agency_id else None
  304. if data.handler_id is not None:
  305. order.handler_id = data.handler_id.strip() if data.handler_id else None
  306. elif order.agency_id:
  307. agency = await AgencyService.get(db, order.agency_id)
  308. if agency and agency.owner_id:
  309. order.handler_id = agency.owner_id
  310. elif data.channel_type == "direct":
  311. order.agency_id = None
  312. if data.handler_id is not None:
  313. order.handler_id = data.handler_id.strip() if data.handler_id else None
  314. elif data.channel_type == "website":
  315. order.agency_id = None
  316. if data.handler_id is not None:
  317. order.handler_id = data.handler_id.strip() if data.handler_id else None
  318. else:
  319. if data.agency_id is not None:
  320. order.agency_id = data.agency_id.strip() if data.agency_id else None
  321. if data.handler_id is not None:
  322. order.handler_id = data.handler_id.strip() if data.handler_id else None
  323. if data.status is not None:
  324. order.status = data.status
  325. if data.user_inputs is not None:
  326. order.user_inputs = data.user_inputs
  327. task_res = await db.execute(
  328. select(VasTask).where(
  329. VasTask.order_id == order.id,
  330. VasTask.status.in_(["pending", "grabbed", "running", "pause", "completed"]),
  331. )
  332. )
  333. for task in task_res.scalars().all():
  334. task.status = "cancelled"
  335. await db.flush()
  336. await WebhookService._create_task_if_not_exists(db, order)
  337. await db.commit()
  338. await db.refresh(order)
  339. logger.info(f"🔄 [ORDER] Admin updated order: id={order.id} channel={order.channel_type} handler={order.handler_id} agency={order.agency_id}")
  340. return order