| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627 |
- # -*- coding: utf-8 -*-
- """管理侧路由:统计、用户管理、订单管理、发货、CAD/预览/设计稿下载。"""
- import json
- import os
- import time
- from datetime import datetime
- from fastapi import APIRouter, HTTPException, Request
- from fastapi.responses import FileResponse, HTMLResponse
- from pydantic import BaseModel
- import auth
- import cache
- import dxf_service
- import eps_service
- import email_service
- import production_pdf
- from db import (FILES_DIR, STATUS_LABELS, add_event, add_message, db, events_of,
- messages_of, order_row_to_dict, user_row_to_dict)
- from routes_orders import get_order_by_no, preview_keys
- router = APIRouter(prefix="/api/admin", tags=["admin"])
- # ---------- AI 配置(后台界面可改) ----------
- def _mask_key(key: str) -> str:
- if not key:
- return ""
- if len(key) <= 8:
- return "*" * len(key)
- return key[:3] + "*" * 8 + key[-4:]
- @router.get("/ai-config")
- def get_ai_config(request: Request):
- auth.require_admin(request)
- import ai_service as _ai
- cfg = _ai.get_config()
- from db import get_setting
- return {
- "baseUrl": cfg["baseUrl"],
- "model": cfg["model"],
- "apiKeyMasked": _mask_key(cfg["apiKey"]),
- "hasKey": bool(cfg["apiKey"]),
- "dbOverridden": {k: bool(get_setting(k)) for k in ("ai_base_url", "ai_api_key", "ai_model")},
- "configured": _ai.configured(),
- }
- class AiConfigBody(BaseModel):
- base_url: str = ""
- model: str = ""
- api_key: str = "" # 留空 = 不修改
- @router.put("/ai-config")
- def save_ai_config(body: AiConfigBody, request: Request):
- auth.require_admin(request)
- import ai_service as _ai
- if body.base_url and not body.base_url.strip().startswith(("http://", "https://")):
- raise HTTPException(status_code=400, detail="Base URL 需以 http(s):// 开头")
- if body.model and len(body.model) > 100:
- raise HTTPException(status_code=400, detail="模型名过长")
- _ai.save_config(body.base_url or None, body.api_key or None, body.model or None)
- return {"ok": True}
- @router.post("/ai-config/test")
- def test_ai_config(request: Request):
- """用当前配置发一次最小请求验证连通。"""
- auth.require_admin(request)
- import ai_service as _ai
- cfg = _ai.get_config()
- if not cfg["apiKey"]:
- return {"ok": False, "error": "未配置 API Key"}
- try:
- reply = _ai.chat([{"role": "user", "content": "回复:ok"}], timeout=20, max_tokens=8)
- return {"ok": True, "model": cfg["model"], "reply": reply.strip()[:30]}
- except Exception as e: # noqa: BLE001
- return {"ok": False, "error": str(e)[:200]}
- # ---------- 统计(Redis 缓存 30s,订单写入即失效) ----------
- @router.get("/stats")
- def stats(request: Request):
- auth.require_admin(request)
- cached = cache.get_stats()
- if cached is not None:
- return cached
- now = datetime.now()
- today0 = int(datetime(now.year, now.month, now.day).timestamp())
- with db() as cur:
- cur.execute("SELECT COUNT(*) AS c FROM orders")
- orders_total = cur.fetchone()["c"]
- cur.execute("SELECT COUNT(*) AS c FROM orders WHERE created_at >= %s", (today0,))
- orders_today = cur.fetchone()["c"]
- cur.execute("SELECT COUNT(*) AS c FROM orders WHERE status = 'producing' AND pay_status = 'paid'")
- pending_ship = cur.fetchone()["c"]
- cur.execute("SELECT COALESCE(SUM(total),0) AS c FROM orders WHERE pay_status = 'paid'")
- revenue = float(cur.fetchone()["c"])
- cur.execute("SELECT COUNT(*) AS c FROM users WHERE role = 'user'")
- users_total = cur.fetchone()["c"]
- cur.execute("SELECT COUNT(*) AS c FROM users WHERE role = 'user' AND created_at >= %s", (today0,))
- users_today = cur.fetchone()["c"]
- cur.execute("SELECT COUNT(*) AS c FROM ai_calls WHERE ok = 1 AND created_at >= %s", (today0,))
- ai_today = cur.fetchone()["c"]
- cur.execute("SELECT status, COUNT(*) AS c FROM orders GROUP BY status")
- by_status = {r["status"]: r["c"] for r in cur.fetchall()}
- result = {
- "ordersTotal": orders_total,
- "ordersToday": orders_today,
- "pendingShip": pending_ship,
- "revenue": revenue,
- "usersTotal": users_total,
- "usersToday": users_today,
- "aiCallsToday": ai_today,
- "byStatus": {STATUS_LABELS.get(k, k): v for k, v in by_status.items()},
- }
- cache.set_stats(result)
- return result
- # ---------- 用户管理 ----------
- @router.get("/factory-accounts")
- def factory_accounts(request: Request):
- """工厂账号列表(每家协作工厂一个账号,订单按账号分配)。"""
- auth.require_admin(request)
- with db() as cur:
- cur.execute("SELECT * FROM users WHERE role = 'factory' ORDER BY id ASC")
- rows = cur.fetchall()
- items = []
- for r in rows:
- u = user_row_to_dict(r)
- cur.execute("SELECT COUNT(*) AS c FROM orders WHERE assigned_to = %s", (r["id"],))
- u["orderCount"] = cur.fetchone()["c"]
- items.append(u)
- return {"items": items}
- class FactoryAccountBody(BaseModel):
- username: str
- password: str
- name: str = ""
- @router.post("/factory-accounts")
- def create_factory_account(body: FactoryAccountBody, request: Request):
- auth.require_admin(request)
- import re as _re
- username = body.username.strip()
- if not _re.match(r"^[a-zA-Z0-9_-]{3,30}$", username):
- raise HTTPException(status_code=400, detail="用户名需 3-30 位字母/数字/下划线")
- if len(body.password) < 6:
- raise HTTPException(status_code=400, detail="密码至少 6 位")
- from auth import hash_password
- with db() as cur:
- cur.execute("SELECT id FROM users WHERE username = %s", (username,))
- if cur.fetchone():
- raise HTTPException(status_code=400, detail="用户名已存在")
- cur.execute(
- "INSERT INTO users (phone, username, name, role, status, password_hash, created_at)"
- " VALUES (NULL, %s, %s, 'factory', 'active', %s, %s)",
- (username, (body.name or username).strip()[:50], hash_password(body.password), int(time.time())),
- )
- cur.execute("SELECT * FROM users WHERE username = %s", (username,))
- row = cur.fetchone()
- return user_row_to_dict(row)
- class FactoryAccountPatchBody(BaseModel):
- status: str | None = None
- name: str | None = None
- password: str | None = None
- @router.patch("/factory-accounts/{user_id}")
- def patch_factory_account(user_id: int, body: FactoryAccountPatchBody, request: Request):
- auth.require_admin(request)
- if body.status not in (None, "active", "disabled"):
- raise HTTPException(status_code=400, detail="状态不合法")
- if body.password is not None and len(body.password) < 6:
- raise HTTPException(status_code=400, detail="密码至少 6 位")
- from auth import hash_password
- with db() as cur:
- cur.execute("SELECT * FROM users WHERE id = %s AND role = 'factory'", (user_id,))
- row = cur.fetchone()
- if not row:
- raise HTTPException(status_code=404, detail="工厂账号不存在")
- if body.status is not None:
- cur.execute("UPDATE users SET status = %s WHERE id = %s", (body.status, user_id))
- if body.name is not None:
- cur.execute("UPDATE users SET name = %s WHERE id = %s", (body.name.strip()[:50], user_id))
- if body.password is not None:
- cur.execute("UPDATE users SET password_hash = %s WHERE id = %s",
- (hash_password(body.password), user_id))
- cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
- row = cur.fetchone()
- cache.invalidate_user(user_id)
- return user_row_to_dict(row)
- @router.get("/users")
- def users(request: Request, query: str = "", page: int = 1, page_size: int = 10):
- auth.require_admin(request)
- page = max(1, page)
- page_size = min(50, max(1, page_size))
- where = (
- "WHERE role = 'user' AND (phone LIKE %s OR name LIKE %s OR email LIKE %s)"
- if query.strip() else "WHERE role = 'user'"
- )
- args = ("%" + query.strip() + "%",) * 3 if query.strip() else ()
- with db() as cur:
- cur.execute("SELECT COUNT(*) AS c FROM users %s" % where, args)
- total = cur.fetchone()["c"]
- cur.execute(
- "SELECT * FROM users %s ORDER BY id DESC LIMIT %%s OFFSET %%s" % where,
- args + (page_size, (page - 1) * page_size),
- )
- rows = cur.fetchall()
- items = []
- for r in rows:
- u = user_row_to_dict(r)
- cur.execute("SELECT COUNT(*) AS c FROM orders WHERE user_id = %s", (r["id"],))
- u["orderCount"] = cur.fetchone()["c"]
- cur.execute(
- "SELECT COALESCE(SUM(total),0) AS s FROM orders WHERE user_id = %s AND pay_status='paid'",
- (r["id"],),
- )
- u["paidTotal"] = float(cur.fetchone()["s"])
- items.append(u)
- return {"total": total, "page": page, "pageSize": page_size, "items": items}
- class UserPatchBody(BaseModel):
- status: str | None = None
- name: str | None = None
- ai_quota: int | None = None
- ai_used: int | None = None # 传 0 即重置用量
- @router.patch("/users/{user_id}")
- def patch_user(user_id: int, body: UserPatchBody, request: Request):
- admin = auth.require_admin(request)
- if body.status not in (None, "active", "disabled"):
- raise HTTPException(status_code=400, detail="状态不合法")
- with db() as cur:
- cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
- row = cur.fetchone()
- if not row:
- raise HTTPException(status_code=404, detail="用户不存在")
- if row["id"] == admin["id"] and body.status == "disabled":
- raise HTTPException(status_code=400, detail="不能禁用自己")
- if body.ai_quota is not None and (body.ai_quota < 0 or body.ai_quota > 100000):
- raise HTTPException(status_code=400, detail="额度需在 0-100000 之间")
- cur.execute(
- "UPDATE users SET status = COALESCE(%s, status), name = COALESCE(%s, name),"
- " ai_quota = COALESCE(%s, ai_quota), ai_used = COALESCE(%s, ai_used) WHERE id = %s",
- (body.status, body.name, body.ai_quota, body.ai_used, user_id),
- )
- cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
- row = cur.fetchone()
- cache.invalidate_user(user_id) # 鉴权缓存立即失效(禁用即时生效)
- return user_row_to_dict(row)
- # ---------- 订单管理 ----------
- @router.get("/orders")
- def orders(request: Request, type: str = "", status: str = "", pay_status: str = "",
- user_id: int = 0, query: str = "", page: int = 1, page_size: int = 10):
- auth.require_admin(request)
- page = max(1, page)
- page_size = min(50, max(1, page_size))
- where, args = ["1=1"], []
- if type in ("bag", "box"):
- where.append("o.type = %s")
- args.append(type)
- if status:
- where.append("o.status = %s")
- args.append(status)
- if pay_status:
- where.append("o.pay_status = %s")
- args.append(pay_status)
- if user_id:
- where.append("o.user_id = %s")
- args.append(user_id)
- if query.strip():
- like = "%" + query.strip() + "%"
- where.append("(o.order_no LIKE %s OR o.contact_name LIKE %s OR o.contact_phone LIKE %s)")
- args += [like, like, like]
- clause = " AND ".join(where)
- with db() as cur:
- cur.execute("SELECT COUNT(*) AS c FROM orders o WHERE %s" % clause, args)
- total = cur.fetchone()["c"]
- cur.execute(
- "SELECT o.* FROM orders o WHERE %s ORDER BY o.id DESC LIMIT %%s OFFSET %%s" % clause,
- args + [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"])
- cur.execute("SELECT name, phone FROM users WHERE id = %s", (r["user_id"],))
- owner = cur.fetchone()
- d["ownerName"] = owner["name"] if owner else "-"
- d["ownerPhone"] = owner["phone"] if owner else "-"
- items.append(d)
- return {"total": total, "page": page, "pageSize": page_size, "items": items}
- def _load_order(order_no: str) -> dict:
- d = get_order_by_no(order_no)
- with db() as cur:
- cur.execute(
- "SELECT design_json, dieline_json FROM order_blobs WHERE order_id = %s", (d["id"],)
- )
- row = cur.fetchone()
- d["hasDesign"] = bool(row and row["design_json"])
- d["hasDieline"] = bool(row and row["dieline_json"])
- cur.execute("SELECT name, phone FROM users WHERE id = %s", (d["userId"],))
- owner = cur.fetchone()
- if d.get("assignedTo"):
- cur.execute("SELECT name, username FROM users WHERE id = %s", (d["assignedTo"],))
- fac = cur.fetchone()
- d["assignedName"] = (fac["name"] or fac["username"]) if fac else "-"
- else:
- d["assignedName"] = ""
- d["ownerName"] = owner["name"] if owner else "-"
- d["ownerPhone"] = owner["phone"] if owner else "-"
- d["events"] = events_of(d["id"])
- d["messages"] = messages_of(d["id"])
- return d
- @router.get("/orders/{order_no}")
- def order_detail(order_no: str, request: Request):
- auth.require_admin(request)
- return _load_order(order_no)
- class AdminMessageBody(BaseModel):
- content: str
- @router.post("/orders/{order_no}/messages")
- def admin_post_message(order_no: str, body: AdminMessageBody, request: Request):
- """管理员回复工厂(线程内可见,不触达用户)。"""
- admin = auth.require_admin(request)
- content = body.content.strip()
- if not content:
- raise HTTPException(status_code=400, detail="请填写回复内容")
- d = get_order_by_no(order_no)
- add_message(d["id"], "admin", admin.get("name") or "管理员", content[:2000])
- return {"ok": True, "messages": messages_of(d["id"])}
- class EmailBody(BaseModel):
- subject: str
- body: str
- @router.post("/orders/{order_no}/messages/{message_id}/email")
- def admin_send_email(order_no: str, message_id: int, body: EmailBody, request: Request):
- """把工厂反馈整理成邮件发给用户(模板内容前端可编辑后传入)。
- SMTP 未配置时自动存档(email_status=archived),内容保留在线程中可复制。
- """
- auth.require_admin(request)
- d = get_order_by_no(order_no)
- subject = body.subject.strip()[:200]
- content = body.body.strip()
- if not subject or not content:
- raise HTTPException(status_code=400, detail="请填写邮件主题与内容")
- with db() as cur:
- cur.execute("SELECT id FROM order_messages WHERE id = %s AND order_id = %s",
- (message_id, d["id"]))
- if not cur.fetchone():
- raise HTTPException(status_code=404, detail="反馈不存在")
- to = d.get("contactEmail") or ""
- if to:
- import email_templates
- html_body, text_body = email_templates.order_message(subject, content, {
- "order_no": order_no,
- "total": d.get("total"),
- })
- status, err = email_service.send_email(to, subject, text_body, html_body)
- else:
- status, err = "no_email", None
- email_status = {"sent": "sent", "archived": "archived"}.get(status, "archived")
- with db() as cur:
- cur.execute(
- "UPDATE order_messages SET email_subject=%s, email_body=%s, email_status=%s,"
- " email_to=%s WHERE id=%s",
- (subject, content, email_status, to, message_id),
- )
- add_event(d["id"], "email", "邮件%s(%s)" % ("已发送" if status == "sent" else "已存档", subject[:40]),
- to)
- return {
- "ok": True,
- "emailStatus": email_status,
- "smtpConfigured": email_service.smtp_configured(),
- "hasEmail": bool(to),
- "error": err,
- "messages": messages_of(d["id"]),
- }
- @router.post("/orders/{order_no}/email/preview", response_class=HTMLResponse)
- def admin_preview_email(order_no: str, body: EmailBody, request: Request):
- """渲染品牌邮件 HTML 供后台弹窗实时预览(不发送、不入库)。"""
- auth.require_admin(request)
- d = get_order_by_no(order_no)
- subject = body.subject.strip()[:200] or "邮件预览"
- content = body.body.strip() or "(正文为空)"
- import email_templates
- html_body, _ = email_templates.order_message(subject, content, {
- "order_no": order_no,
- "total": d.get("total"),
- })
- return html_body
- class OrderPatchBody(BaseModel):
- status: str | None = None
- pay_status: str | None = None
- admin_note: str | None = None
- address: str | None = None
- assigned_to: int | None = None
- clear_assignment: bool = False
- @router.patch("/orders/{order_no}")
- def patch_order(order_no: str, body: OrderPatchBody, request: Request):
- auth.require_admin(request)
- if body.status is not None and body.status not in STATUS_LABELS:
- raise HTTPException(status_code=400, detail="订单状态不合法")
- if body.pay_status is not None and body.pay_status not in ("unpaid", "paid", "refunded"):
- raise HTTPException(status_code=400, detail="支付状态不合法")
- 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="订单不存在")
- now = int(time.time())
- sets, args = ["updated_at = %s"], [now]
- if body.status is not None and body.status != row["status"]:
- sets.append("status = %s")
- args.append(body.status)
- add_event(row["id"], "status", "状态变更为「%s」" % STATUS_LABELS[body.status], "管理员操作", cur=cur)
- if body.pay_status is not None and body.pay_status != row["pay_status"]:
- sets.append("pay_status = %s")
- args.append(body.pay_status)
- pay_labels = {"unpaid": "未支付", "paid": "已支付", "refunded": "已退款"}
- add_event(row["id"], "payment", "支付状态变更为「%s」" % pay_labels[body.pay_status], "管理员操作", cur=cur)
- if body.admin_note is not None:
- sets.append("admin_note = %s")
- args.append(body.admin_note)
- if body.address is not None:
- sets.append("address = %s")
- args.append(body.address)
- if body.clear_assignment:
- if row.get("assigned_to"):
- sets.append("assigned_to = NULL")
- add_event(row["id"], "assign", "取消工厂分配", "", cur=cur)
- elif body.assigned_to is not None:
- cur.execute("SELECT name, username FROM users WHERE id = %s AND role = 'factory'", (body.assigned_to,))
- fac = cur.fetchone()
- if not fac:
- raise HTTPException(status_code=400, detail="工厂账号不存在")
- if row.get("assigned_to") != body.assigned_to:
- sets.append("assigned_to = %s")
- args.append(body.assigned_to)
- add_event(row["id"], "assign", "分配给工厂「%s」" % (fac["name"] or fac["username"]), "", cur=cur)
- args.append(row["id"])
- cur.execute("UPDATE orders SET %s WHERE id = %%s" % ", ".join(sets), args)
- cache.invalidate_stats()
- return _load_order(order_no)
- class ShipBody(BaseModel):
- carrier: str
- tracking_no: str
- @router.post("/orders/{order_no}/ship")
- def ship(order_no: str, body: ShipBody, request: Request):
- auth.require_admin(request)
- carrier = body.carrier.strip()
- tracking = body.tracking_no.strip()
- if not carrier or not tracking:
- raise HTTPException(status_code=400, detail="请填写快递公司和运单号")
- 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="订单不存在")
- if row["status"] in ("cancelled",):
- raise HTTPException(status_code=400, detail="订单已取消,不能发货")
- now = int(time.time())
- cur.execute(
- "UPDATE orders SET status='shipped', carrier=%s, tracking_no=%s, updated_at=%s WHERE id=%s",
- (carrier, tracking, now, row["id"]),
- )
- add_event(row["id"], "logistics", "已发货", "%s 运单号 %s" % (carrier, tracking), cur=cur)
- cache.invalidate_stats()
- return _load_order(order_no)
- # ---------- 产物下载 ----------
- @router.get("/orders/{order_no}/dxf")
- def order_dxf(order_no: str, request: Request):
- auth.require_staff(request)
- order = _load_full_order(order_no)
- path = dxf_service.generate(order)
- if not path or not os.path.exists(path):
- raise HTTPException(status_code=500, detail="CAD 图纸生成失败")
- return FileResponse(
- path,
- media_type="application/dxf",
- filename="%s-%s.dxf" % (order_no, "dieline" if order["type"] == "box" else "print"),
- )
- @router.get("/orders/{order_no}/dxf-preview")
- def order_dxf_preview(order_no: str, request: Request):
- """CAD 预览(服务端 ezdxf SVGBackend 渲染的矢量图)。"""
- auth.require_staff(request)
- order = _load_full_order(order_no)
- path = dxf_service.preview_svg_path(order)
- if not path:
- raise HTTPException(status_code=404, detail="CAD 预览生成失败")
- return FileResponse(path, media_type="image/svg+xml")
- @router.get("/orders/{order_no}/pdf")
- def order_production_pdf(order_no: str, request: Request):
- """生产图纸 PDF:刀版展开图 + 尺寸标注 + 技术要求 + 设计预览(指导工厂生产)。"""
- auth.require_staff(request)
- order = _load_full_order(order_no)
- previews = [
- os.path.join(FILES_DIR, order_no, "preview-%s.png" % key)
- for key in (order.get("previews") or [])
- ]
- path = production_pdf.production_pdf_path(order, previews)
- if not path or not os.path.isfile(path):
- raise HTTPException(status_code=500, detail="生产图纸生成失败")
- return FileResponse(path, media_type="application/pdf",
- filename="%s-生产图纸.pdf" % order_no)
- @router.get("/orders/{order_no}/vector-pdf")
- def order_vector_pdf(order_no: str, request: Request):
- """1:1 矢量刀版 PDF(mm 实尺,CorelDRAW/Illustrator 直接打开编辑,CDR 交付替代)。"""
- auth.require_staff(request)
- order = _load_full_order(order_no)
- path = production_pdf.vector_pdf_path(order)
- if not path or not os.path.isfile(path):
- raise HTTPException(status_code=500, detail="矢量刀版生成失败")
- return FileResponse(path, media_type="application/pdf",
- filename="%s-刀版1to1.pdf" % order_no)
- @router.get("/orders/{order_no}/eps")
- def order_eps(order_no: str, request: Request):
- """1:1 EPS 矢量刀版(CorelDRAW/Illustrator 原生导入;打开后另存为 .cdr 即得 CDR)。"""
- auth.require_staff(request)
- order = _load_full_order(order_no)
- path = eps_service.eps_path(order)
- if not path or not os.path.isfile(path):
- raise HTTPException(status_code=500, detail="EPS 生成失败")
- return FileResponse(path, media_type="application/postscript",
- filename="%s-刀版1to1.eps" % order_no)
- def _load_full_order(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="订单不存在")
- cur.execute("SELECT dieline_json FROM order_blobs WHERE order_id = %s", (row["id"],))
- blob = cur.fetchone()
- dieline = json.loads(blob["dieline_json"]) if blob and blob["dieline_json"] else {}
- if not dieline:
- raise HTTPException(status_code=404, detail="该订单没有刀版数据")
- order = order_row_to_dict(row, with_blobs=True)
- order["dieline"] = dieline
- return order
- @router.get("/orders/{order_no}/preview/{key}")
- def order_preview(order_no: str, key: str, request: Request):
- user = auth.user_from_request(request) # 管理员/工厂/订单本人均可
- if user["role"] not in ("admin", "factory"):
- from routes_orders import load_order_for
- load_order_for(order_no, user) # 普通用户仅可看自己的订单
- path = os.path.join(FILES_DIR, order_no, "preview-%s.png" % key)
- if not os.path.isfile(path):
- raise HTTPException(status_code=404, detail="预览图不存在")
- return FileResponse(path, media_type="image/png")
- @router.get("/orders/{order_no}/design")
- def order_design(order_no: str, request: Request):
- auth.require_staff(request)
- 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="订单不存在")
- cur.execute("SELECT design_json FROM order_blobs WHERE order_id = %s", (row["id"],))
- blob = cur.fetchone()
- if not blob or not blob["design_json"]:
- raise HTTPException(status_code=404, detail="该订单没有设计数据")
- folder = os.path.join(FILES_DIR, order_no)
- os.makedirs(folder, exist_ok=True)
- path = os.path.join(folder, "design.json")
- with open(path, "w", encoding="utf-8") as f:
- f.write(blob["design_json"])
- return FileResponse(path, media_type="application/json", filename="%s-design.json" % order_no)
|