| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202 |
- # -*- coding: utf-8 -*-
- """用户侧订单路由:下单(大 JSON 载荷)、我的订单、模拟支付、取消。"""
- import base64
- import json
- import os
- import time
- from fastapi import APIRouter, HTTPException, Request
- from pydantic import BaseModel
- import auth
- import cache
- from db import FILES_DIR, add_event, db, events_of, gen_order_no, order_row_to_dict
- router = APIRouter(prefix="/api/orders", tags=["orders"])
- class OrderContact(BaseModel):
- name: str = ""
- phone: str = ""
- email: str = ""
- address: str = ""
- note: str = ""
- class OrderCreateBody(BaseModel):
- type: str # bag | box
- contact: OrderContact
- spec: dict = {}
- quote: dict = {}
- summary: str = ""
- design: dict | None = None
- dieline: dict | None = None
- previews: dict = {} # {front|back|dieline: dataURL}
- def _save_preview(order_no: str, key: str, data_url: str):
- """把 dataURL 预览图写入 data/files/<order_no>/preview-<key>.png"""
- if not data_url or not data_url.startswith("data:image"):
- return
- try:
- payload = data_url.split(",", 1)[1]
- raw = base64.b64decode(payload)
- except (IndexError, ValueError):
- return
- folder = os.path.join(FILES_DIR, order_no)
- os.makedirs(folder, exist_ok=True)
- with open(os.path.join(folder, "preview-%s.png" % key), "wb") as f:
- f.write(raw)
- def preview_keys(order_no: str) -> list:
- folder = os.path.join(FILES_DIR, order_no)
- if not os.path.isdir(folder):
- return []
- return sorted(
- f[len("preview-"):-len(".png")]
- for f in os.listdir(folder)
- if f.startswith("preview-") and f.endswith(".png")
- )
- def create_order(user: dict, body: OrderCreateBody) -> dict:
- if body.type not in ("bag", "box"):
- raise HTTPException(status_code=400, detail="订单类型不合法")
- if not body.contact.name or not body.contact.phone:
- raise HTTPException(status_code=400, detail="请填写联系人和手机号")
- if not body.contact.address:
- raise HTTPException(status_code=400, detail="请填写收货地址")
- now = int(time.time())
- unit = float(body.quote.get("unit") or 0)
- total = float(body.quote.get("total") or 0)
- if total <= 0:
- raise HTTPException(status_code=400, detail="订单金额不合法")
- with db() as cur:
- order_no = gen_order_no(cur)
- cur.execute(
- "INSERT INTO orders (order_no, user_id, type, status, pay_status, contact_name,"
- " contact_phone, contact_email, address, note, spec_json, quote_json, summary,"
- " unit_price, total, created_at, updated_at)"
- " VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
- (
- order_no, user["id"], body.type, "pending_payment", "unpaid",
- body.contact.name, body.contact.phone, body.contact.email,
- body.contact.address, body.contact.note,
- json.dumps(body.spec, ensure_ascii=False),
- json.dumps(body.quote, ensure_ascii=False),
- body.summary[:200], unit, total, now, now,
- ),
- )
- order_id = cur.lastrowid
- cur.execute(
- "INSERT INTO order_blobs (order_id, design_json, dieline_json) VALUES (%s,%s,%s)",
- (
- order_id,
- json.dumps(body.design, ensure_ascii=False) if body.design else None,
- json.dumps(body.dieline, ensure_ascii=False) if body.dieline else None,
- ),
- )
- add_event(order_id, "created", "订单创建", body.summary[:120], cur=cur)
- cache.invalidate_stats()
- for key, data_url in body.previews.items():
- _save_preview(order_no, str(key), str(data_url))
- return get_order_by_no(order_no)
- def get_order_by_no(order_no: str) -> dict:
- with db() as cur:
- cur.execute("SELECT * FROM orders WHERE order_no = %s", (order_no,))
- row = cur.fetchone()
- if not row:
- raise HTTPException(status_code=404, detail="订单不存在")
- d = order_row_to_dict(row)
- d["previews"] = preview_keys(order_no)
- return d
- def load_order_for(order_no: str, user: dict) -> dict:
- d = get_order_by_no(order_no)
- if d["userId"] != user["id"] and user["role"] != "admin":
- raise HTTPException(status_code=403, detail="无权查看该订单")
- return d
- @router.post("")
- def create(body: OrderCreateBody, request: Request):
- user = auth.require_user(request)
- return create_order(user, body)
- @router.get("/mine")
- def mine(request: Request, page: int = 1, page_size: int = 10):
- user = auth.require_user(request)
- page = max(1, page)
- page_size = min(50, max(1, page_size))
- with db() as cur:
- cur.execute("SELECT COUNT(*) AS c FROM orders WHERE user_id = %s", (user["id"],))
- total = cur.fetchone()["c"]
- cur.execute(
- "SELECT * FROM orders WHERE user_id = %s ORDER BY id DESC LIMIT %s OFFSET %s",
- (user["id"], page_size, (page - 1) * page_size),
- )
- rows = cur.fetchall()
- items = []
- for r in rows:
- d = order_row_to_dict(r)
- d["previews"] = preview_keys(r["order_no"])
- items.append(d)
- return {"total": total, "page": page, "pageSize": page_size, "items": items}
- @router.get("/mine/{order_no}")
- def detail(order_no: str, request: Request):
- user = auth.require_user(request)
- d = load_order_for(order_no, user)
- d["events"] = events_of(d["id"])
- return d
- @router.post("/mine/{order_no}/pay")
- def pay(order_no: str, request: Request):
- """模拟支付。接入真实渠道时(支付宝/微信),在此创建支付单并在回调里落状态。"""
- user = auth.require_user(request)
- with db() as cur:
- cur.execute("SELECT * FROM orders WHERE order_no = %s", (order_no,))
- row = cur.fetchone()
- if not row or (row["user_id"] != user["id"] and user["role"] != "admin"):
- raise HTTPException(status_code=404, detail="订单不存在")
- if row["pay_status"] != "unpaid":
- raise HTTPException(status_code=400, detail="订单不是待支付状态")
- if row["status"] not in ("pending_payment", "cancelled"):
- raise HTTPException(status_code=400, detail="订单状态不允许支付")
- now = int(time.time())
- cur.execute(
- "UPDATE orders SET pay_status='paid', status='producing', updated_at=%s WHERE id=%s",
- (now, row["id"]),
- )
- add_event(row["id"], "payment", "支付成功(模拟)", "¥%.2f" % row["total"], cur=cur)
- add_event(row["id"], "status", "订单进入生产", "", cur=cur)
- cache.invalidate_stats()
- return get_order_by_no(order_no)
- @router.post("/mine/{order_no}/cancel")
- def cancel(order_no: str, request: Request):
- user = auth.require_user(request)
- with db() as cur:
- cur.execute("SELECT * FROM orders WHERE order_no = %s", (order_no,))
- row = cur.fetchone()
- if not row or (row["user_id"] != user["id"] and user["role"] != "admin"):
- raise HTTPException(status_code=404, detail="订单不存在")
- if row["pay_status"] != "unpaid":
- raise HTTPException(status_code=400, detail="已支付订单请联系客服处理")
- if row["status"] in ("shipped", "completed", "cancelled"):
- raise HTTPException(status_code=400, detail="当前状态不可取消")
- now = int(time.time())
- cur.execute(
- "UPDATE orders SET status='cancelled', updated_at=%s WHERE id=%s", (now, row["id"])
- )
- add_event(row["id"], "status", "订单已取消", "", cur=cur)
- cache.invalidate_stats()
- return get_order_by_no(order_no)
|