routes_orders.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. # -*- coding: utf-8 -*-
  2. """用户侧订单路由:下单(大 JSON 载荷)、我的订单、模拟支付、取消。"""
  3. import base64
  4. import json
  5. import os
  6. import time
  7. from fastapi import APIRouter, HTTPException, Request
  8. from pydantic import BaseModel
  9. import auth
  10. import cache
  11. from db import FILES_DIR, add_event, db, events_of, gen_order_no, order_row_to_dict
  12. router = APIRouter(prefix="/api/orders", tags=["orders"])
  13. class OrderContact(BaseModel):
  14. name: str = ""
  15. phone: str = ""
  16. email: str = ""
  17. address: str = ""
  18. note: str = ""
  19. class OrderCreateBody(BaseModel):
  20. type: str # bag | box
  21. contact: OrderContact
  22. spec: dict = {}
  23. quote: dict = {}
  24. summary: str = ""
  25. design: dict | None = None
  26. dieline: dict | None = None
  27. previews: dict = {} # {front|back|dieline: dataURL}
  28. def _save_preview(order_no: str, key: str, data_url: str):
  29. """把 dataURL 预览图写入 data/files/<order_no>/preview-<key>.png"""
  30. if not data_url or not data_url.startswith("data:image"):
  31. return
  32. try:
  33. payload = data_url.split(",", 1)[1]
  34. raw = base64.b64decode(payload)
  35. except (IndexError, ValueError):
  36. return
  37. folder = os.path.join(FILES_DIR, order_no)
  38. os.makedirs(folder, exist_ok=True)
  39. with open(os.path.join(folder, "preview-%s.png" % key), "wb") as f:
  40. f.write(raw)
  41. def preview_keys(order_no: str) -> list:
  42. folder = os.path.join(FILES_DIR, order_no)
  43. if not os.path.isdir(folder):
  44. return []
  45. return sorted(
  46. f[len("preview-"):-len(".png")]
  47. for f in os.listdir(folder)
  48. if f.startswith("preview-") and f.endswith(".png")
  49. )
  50. def create_order(user: dict, body: OrderCreateBody) -> dict:
  51. if body.type not in ("bag", "box"):
  52. raise HTTPException(status_code=400, detail="订单类型不合法")
  53. if not body.contact.name or not body.contact.phone:
  54. raise HTTPException(status_code=400, detail="请填写联系人和手机号")
  55. if not body.contact.address:
  56. raise HTTPException(status_code=400, detail="请填写收货地址")
  57. now = int(time.time())
  58. unit = float(body.quote.get("unit") or 0)
  59. total = float(body.quote.get("total") or 0)
  60. if total <= 0:
  61. raise HTTPException(status_code=400, detail="订单金额不合法")
  62. with db() as cur:
  63. order_no = gen_order_no(cur)
  64. cur.execute(
  65. "INSERT INTO orders (order_no, user_id, type, status, pay_status, contact_name,"
  66. " contact_phone, contact_email, address, note, spec_json, quote_json, summary,"
  67. " unit_price, total, created_at, updated_at)"
  68. " VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
  69. (
  70. order_no, user["id"], body.type, "pending_payment", "unpaid",
  71. body.contact.name, body.contact.phone, body.contact.email,
  72. body.contact.address, body.contact.note,
  73. json.dumps(body.spec, ensure_ascii=False),
  74. json.dumps(body.quote, ensure_ascii=False),
  75. body.summary[:200], unit, total, now, now,
  76. ),
  77. )
  78. order_id = cur.lastrowid
  79. cur.execute(
  80. "INSERT INTO order_blobs (order_id, design_json, dieline_json) VALUES (%s,%s,%s)",
  81. (
  82. order_id,
  83. json.dumps(body.design, ensure_ascii=False) if body.design else None,
  84. json.dumps(body.dieline, ensure_ascii=False) if body.dieline else None,
  85. ),
  86. )
  87. add_event(order_id, "created", "订单创建", body.summary[:120], cur=cur)
  88. cache.invalidate_stats()
  89. for key, data_url in body.previews.items():
  90. _save_preview(order_no, str(key), str(data_url))
  91. return get_order_by_no(order_no)
  92. def get_order_by_no(order_no: str) -> dict:
  93. with db() as cur:
  94. cur.execute("SELECT * FROM orders WHERE order_no = %s", (order_no,))
  95. row = cur.fetchone()
  96. if not row:
  97. raise HTTPException(status_code=404, detail="订单不存在")
  98. d = order_row_to_dict(row)
  99. d["previews"] = preview_keys(order_no)
  100. return d
  101. def load_order_for(order_no: str, user: dict) -> dict:
  102. d = get_order_by_no(order_no)
  103. if d["userId"] != user["id"] and user["role"] != "admin":
  104. raise HTTPException(status_code=403, detail="无权查看该订单")
  105. return d
  106. @router.post("")
  107. def create(body: OrderCreateBody, request: Request):
  108. user = auth.require_user(request)
  109. return create_order(user, body)
  110. @router.get("/mine")
  111. def mine(request: Request, page: int = 1, page_size: int = 10):
  112. user = auth.require_user(request)
  113. page = max(1, page)
  114. page_size = min(50, max(1, page_size))
  115. with db() as cur:
  116. cur.execute("SELECT COUNT(*) AS c FROM orders WHERE user_id = %s", (user["id"],))
  117. total = cur.fetchone()["c"]
  118. cur.execute(
  119. "SELECT * FROM orders WHERE user_id = %s ORDER BY id DESC LIMIT %s OFFSET %s",
  120. (user["id"], page_size, (page - 1) * page_size),
  121. )
  122. rows = cur.fetchall()
  123. items = []
  124. for r in rows:
  125. d = order_row_to_dict(r)
  126. d["previews"] = preview_keys(r["order_no"])
  127. items.append(d)
  128. return {"total": total, "page": page, "pageSize": page_size, "items": items}
  129. @router.get("/mine/{order_no}")
  130. def detail(order_no: str, request: Request):
  131. user = auth.require_user(request)
  132. d = load_order_for(order_no, user)
  133. d["events"] = events_of(d["id"])
  134. return d
  135. @router.post("/mine/{order_no}/pay")
  136. def pay(order_no: str, request: Request):
  137. """模拟支付。接入真实渠道时(支付宝/微信),在此创建支付单并在回调里落状态。"""
  138. user = auth.require_user(request)
  139. with db() as cur:
  140. cur.execute("SELECT * FROM orders WHERE order_no = %s", (order_no,))
  141. row = cur.fetchone()
  142. if not row or (row["user_id"] != user["id"] and user["role"] != "admin"):
  143. raise HTTPException(status_code=404, detail="订单不存在")
  144. if row["pay_status"] != "unpaid":
  145. raise HTTPException(status_code=400, detail="订单不是待支付状态")
  146. if row["status"] not in ("pending_payment", "cancelled"):
  147. raise HTTPException(status_code=400, detail="订单状态不允许支付")
  148. now = int(time.time())
  149. cur.execute(
  150. "UPDATE orders SET pay_status='paid', status='producing', updated_at=%s WHERE id=%s",
  151. (now, row["id"]),
  152. )
  153. add_event(row["id"], "payment", "支付成功(模拟)", "¥%.2f" % row["total"], cur=cur)
  154. add_event(row["id"], "status", "订单进入生产", "", cur=cur)
  155. cache.invalidate_stats()
  156. return get_order_by_no(order_no)
  157. @router.post("/mine/{order_no}/cancel")
  158. def cancel(order_no: str, request: Request):
  159. user = auth.require_user(request)
  160. with db() as cur:
  161. cur.execute("SELECT * FROM orders WHERE order_no = %s", (order_no,))
  162. row = cur.fetchone()
  163. if not row or (row["user_id"] != user["id"] and user["role"] != "admin"):
  164. raise HTTPException(status_code=404, detail="订单不存在")
  165. if row["pay_status"] != "unpaid":
  166. raise HTTPException(status_code=400, detail="已支付订单请联系客服处理")
  167. if row["status"] in ("shipped", "completed", "cancelled"):
  168. raise HTTPException(status_code=400, detail="当前状态不可取消")
  169. now = int(time.time())
  170. cur.execute(
  171. "UPDATE orders SET status='cancelled', updated_at=%s WHERE id=%s", (now, row["id"])
  172. )
  173. add_event(row["id"], "status", "订单已取消", "", cur=cur)
  174. cache.invalidate_stats()
  175. return get_order_by_no(order_no)