order_service.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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
  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.product_routing import VasProductRouting
  19. from app.schemas.order import VasOrderCreate, VasOrderAdjustPrice, VasOrderPatchUserInputs
  20. from app.services.webhook_service import WebhookService
  21. class OrderService:
  22. @staticmethod
  23. async def create(
  24. db: AsyncSession,
  25. data: VasOrderCreate,
  26. product: VasProduct,
  27. auth_user: VasUser,
  28. redis_client: Redis,
  29. ) -> VasOrder:
  30. if not auth_user.email:
  31. raise BizLogicError(
  32. "Your account must be linked to an email address before you can place an order."
  33. )
  34. order_id = f"ORD-{datetime.utcnow():%Y%m%d%H%M%S}-{uuid.uuid4().hex[:8]}"
  35. safe_product_name = (product.title[:100]) if product.title else ""
  36. order = VasOrder(
  37. id=order_id,
  38. **data.dict(),
  39. product_name=safe_product_name,
  40. base_amount=product.price_amount,
  41. base_currency=product.price_currency,
  42. adjustment_delta=0,
  43. final_amount=product.price_amount,
  44. user_id=auth_user.id,
  45. )
  46. db.add(order)
  47. await db.commit()
  48. await db.refresh(order)
  49. logger.info(f"📦 [ORDER] Created order: id={order.id} product={product.id} user={auth_user.id} amount={order.final_amount} {order.base_currency}")
  50. return order
  51. @staticmethod
  52. async def cancel(
  53. db: AsyncSession,
  54. order_id,
  55. ) -> VasOrder:
  56. stmt = select(VasOrder).where(VasOrder.id == order_id)
  57. order = (await db.execute(stmt)).scalar_one_or_none()
  58. if not order:
  59. raise NotFoundError("Order not exist")
  60. order.status = "closed"
  61. task_res = await db.execute(
  62. select(VasTask).where(
  63. VasTask.order_id == order.id,
  64. VasTask.status.in_(["pending", "grabbed", "running", "pause", "completed"]),
  65. )
  66. )
  67. for task in task_res.scalars().all():
  68. task.status = "cancelled"
  69. await db.commit()
  70. await db.refresh(order)
  71. logger.info(f"🚫 [ORDER] Cancelled order: id={order.id} and its associated tasks")
  72. return order
  73. @staticmethod
  74. async def create_by_admin(
  75. db: AsyncSession,
  76. data: VasOrderCreate,
  77. product: VasProduct,
  78. auth_user: VasUser
  79. ) -> VasOrder:
  80. order_id = f"ORD-{datetime.utcnow():%Y%m%d%H%M%S}-{uuid.uuid4().hex[:8]}"
  81. safe_product_name = (product.title[:100]) if product.title else ""
  82. order = VasOrder(
  83. id=order_id,
  84. **data.dict(),
  85. status="paid",
  86. product_name=safe_product_name,
  87. base_amount=product.price_amount,
  88. base_currency=product.price_currency,
  89. adjustment_delta=0,
  90. final_amount=product.price_amount,
  91. user_id=auth_user.id,
  92. )
  93. # ===== user_inputs 安全修复 =====
  94. raw_inputs = order.user_inputs
  95. if isinstance(raw_inputs, str):
  96. try:
  97. order.user_inputs = json.loads(raw_inputs)
  98. except Exception:
  99. order.user_inputs = {}
  100. elif raw_inputs is None or not isinstance(raw_inputs, dict):
  101. order.user_inputs = {}
  102. order.user_inputs["_admin_bypass"] = {
  103. "enabled": True,
  104. "by": auth_user.id,
  105. "at": datetime.utcnow().isoformat(),
  106. "reason": "admin manual order",
  107. }
  108. db.add(order)
  109. await WebhookService._create_task_if_not_exists(db, order)
  110. await db.commit()
  111. await db.refresh(order)
  112. logger.info(f"👑 [ORDER] Admin created order: id={order.id} product={product.id} user={auth_user.id} status=paid")
  113. return order
  114. @staticmethod
  115. async def adjust_order_price(db: AsyncSession, order_id: str, payload: VasOrderAdjustPrice) -> VasOrder:
  116. stmt = select(VasOrder).where(VasOrder.id == order_id)
  117. order = (await db.execute(stmt)).scalar_one_or_none()
  118. if not order:
  119. logger.warning(f"⚠️ [ORDER] Price adjust failed: Order {order_id} not found")
  120. raise NotFoundError("Order not exist")
  121. if order.status != "pending":
  122. logger.warning(f"⚠️ [ORDER] Price adjust failed: Order {order_id} status is {order.status} (expected pending)")
  123. raise BizLogicError(message="Order not adjustable")
  124. # 2. 更新订单价格
  125. old_amount = order.final_amount
  126. order.adjustment_delta = payload.adjustment_delta
  127. order.final_amount = order.base_amount + payload.adjustment_delta
  128. if order.final_amount <= 0:
  129. raise BizLogicError(message="final_amount must be > 0")
  130. # ② 是否已有 pending payment(幂等)
  131. stmt = select(VasPayment).where(
  132. VasPayment.order_id == order.id,
  133. VasPayment.status == "pending",
  134. )
  135. active_payment = (await db.execute(stmt)).scalar_one_or_none()
  136. if active_payment:
  137. active_payment.status = "expired"
  138. await db.commit()
  139. await db.refresh(order)
  140. logger.info(f"💰 [ORDER] Adjusted order price: id={order.id} old={old_amount} new={order.final_amount} delta={payload.adjustment_delta}")
  141. return order
  142. @staticmethod
  143. async def get(db: AsyncSession, order_id: str) -> Optional[VasOrder]:
  144. stmt = select(VasOrder).where(VasOrder.id == order_id)
  145. return (await db.execute(stmt)).scalar_one_or_none()
  146. @staticmethod
  147. async def list_by_user(
  148. db: AsyncSession,
  149. user_id: str,
  150. page: int = 0,
  151. size: int = 10,
  152. keyword: Optional[str] = None,
  153. ):
  154. stmt = select(VasOrder).where(VasOrder.user_id == user_id)
  155. stmt = apply_keyword_search_stmt(
  156. stmt=stmt,
  157. model=VasOrder,
  158. keyword=keyword,
  159. fields=["id", "user_id", "product_name", "user_inputs"],
  160. ).order_by(VasOrder.created_at.desc())
  161. return await paginate(db, stmt, page, size)
  162. @staticmethod
  163. async def list_all(
  164. db: AsyncSession,
  165. page: int = 0,
  166. size: int = 10,
  167. keyword: Optional[str] = None,
  168. ):
  169. stmt = select(VasOrder)
  170. query = apply_keyword_search_stmt(
  171. stmt=stmt,
  172. model=VasOrder,
  173. keyword=keyword,
  174. fields=["id", "user_id", "user_name", "product_name", "user_inputs"],
  175. ).order_by(VasOrder.created_at.desc())
  176. return await paginate(db, query, page, size)
  177. @staticmethod
  178. async def patch_user_inputs(
  179. db: AsyncSession,
  180. order_id: str,
  181. payload: VasOrderPatchUserInputs,
  182. ) -> VasOrder:
  183. stmt = select(VasOrder).where(VasOrder.id == order_id)
  184. order = (await db.execute(stmt)).scalar_one_or_none()
  185. if not order:
  186. logger.warning(f"⚠️ [ORDER] Patch user_inputs failed: Order {order_id} not found")
  187. raise NotFoundError("Order not exist")
  188. order.user_inputs = payload.user_inputs
  189. # 1️⃣ 取消旧任务
  190. task_res = await db.execute(
  191. select(VasTask).where(
  192. VasTask.order_id == order.id,
  193. VasTask.status.in_(["pending", "grabbed", "running", "pause", "completed"]),
  194. )
  195. )
  196. for task in task_res.scalars().all():
  197. task.status = "cancelled"
  198. await db.flush()
  199. await WebhookService._create_task_if_not_exists(db, order)
  200. await db.commit()
  201. await db.refresh(order)
  202. logger.info(f"🔄 [ORDER] Patched user inputs for order {order.id}, recreated tasks")
  203. return order