Files
jinzuanwork/backend/backend-site/admin.py
T
Suda 1d67fda9d5 backend: 交付网站后端 + 本地自助管理后台 + 测试工程(已脱敏)
范围由店主圈定:网页后端 / 自助后端、本地的自助管理后台、
用于测试的 Blender 工程、以及部署层的反代片段。

出站纪律:所有指向真实环境的值(域名/端口/盘符路径/IP/账户名)已替换为占位;
代码里本来就没有硬编码凭据(令牌走文件与环境变量)。
Blender 工程因内嵌绝对路径,做了等长替换(文件字节数未变,结构完好)。

两份交接文档各含《我们的思路与方法》,并要求对方回:
问题分析 + 改正意见 + 他改了什么(含是否动到接口/字段/数据格式)。
2026-10-05 18:52:33 +08:00

538 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
金钻工坊 · 渲染下单 —— 管理工具(**只在本机跑**,不开公网入口)
python3 admin.py gen 50 --batch 2026-09-30 --value 6 批量生成 50 个码(导出 CSV)
python3 admin.py gen 1 --tpl wheat --n-fix 3 张数卡密:这张码只能出 3 张
python3 admin.py edit <卡密> --n-fix 5 / --unlimited / --lock-tpl / --off
改一张还没用掉的卡密(张数/锁模板/停用)
python3 admin.py codes [--used|--unused] 看码库
python3 admin.py ls [waiting|working|done|failed] 看订单
python3 admin.py show <订单号> 看单详情
python3 admin.py retry <订单号> 把单子退回队列重渲
python3 admin.py calls 看「呼叫金钻」记录
python3 admin.py sweep 清理超过保留期的成品
python3 admin.py stat 概览
python3 admin.py audit [行数] 看兑换码失败/被拒记录
"""
import csv, json, os, shutil, sys, time
from datetime import datetime, timedelta
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import server as S # noqa: E402
def cmd_gen(argv):
# ⚠️ 2026-10-01 实踩:`gen --help` 会被当成普通参数 → **直接生成 10 张真码**。
# 管理工具绝不能"看个帮助就产生副作用"。
if any(a in ("-h", "--help") for a in argv):
print("""gen 用法:
gen 50 生成 50 张(一张码一张图)
gen 20 --platform 爱发电 打平台标记(买家填码时会显示来源并预选模板)
gen 20 --n-fix 1 固定张数:这张码只能出 1 张
gen 5 --n-free 不限张数
gen 20 --unlimited --direct 不限张数 + 直发(不用确认收货,直接给原图)
gen 10 --tpl wheat 预选模板(买家填码自动勾上)
gen 20 --platform 爱发电 --n-fix 1 --export payplatform.txt
★ 顺手导出「一行一码」纯文本,直接贴进爱发电的自动发货卡池""")
return 0
n = int(argv[0]) if argv and argv[0].isdigit() else 10
batch, value, platform, tpl, is_set, direct = "", 6, "", "", False, False
n_fix, n_max, lock_tpl, n_free, export = 0, 0, False, False, ""
for i, a in enumerate(argv):
if a == "--batch" and i + 1 < len(argv):
batch = argv[i + 1]
if a == "--value" and i + 1 < len(argv):
value = argv[i + 1]
# 第三方平台的标记:闲鱼 / B站工坊 …(金钻 2026-09-30)
# 买家填码时页面会显示「来自闲鱼 · 麦田萤火」并自动预选模板,不用他自己挑
if a == "--platform" and i + 1 < len(argv):
platform = argv[i + 1]
# --export 文件名:导出一份「一行一码」的纯文本。
# 金钻 2026-10-01(P4):爱发电的「自动发货」= 你填一池子卡密,买家付款它自己发一张。
# 这里直接产出能整段粘进去的文本,省掉手工挑码。
if a in ("--export", "--dlv") and i + 1 < len(argv):
export = argv[i + 1]
if a == "--tpl" and i + 1 < len(argv):
tpl = argv[i + 1]
# --set = 套装卡密:一张码管一整套(全部皮肤 × 全部模板)
if a == "--set":
is_set = True
# --direct = 金钻自己发的码(个人收款卖的):不用等确认收货,看完预览直接下
if a == "--direct":
direct = True
# 张数卡密(金钻 2026-09-30 晚):
# --n-fix 3 → 这张码**只能出 3 张**(模板随便改,张数不能多也不能少)
# --n-max 10 → 最多 10 张(不限张数也可以封个顶)
# --lock-tpl → 码里带的模板锁死,买家不能改
if a in ("--n-fix", "--n-max") and i + 1 < len(argv):
try:
if a == "--n-fix":
n_fix = int(argv[i + 1])
else:
n_max = int(argv[i + 1])
except ValueError:
print("❌ %s 要跟一个整数" % a)
return
if a == "--lock-tpl":
lock_tpl = True
# --unlimited → 不限张数(买家想出几张出几张;老规矩「一张码一张图」也解除)
if a == "--unlimited":
n_free = True
# --tpl 支持逗号分隔多个(套装卡密:一张码预选一组模板)
tpl_list = [x.strip() for x in tpl.split(",") if x.strip()]
bad = [x for x in tpl_list if x not in S.TPL_KEYS]
if bad:
print("❌ 模板 key 不认识:%s\n 可选:%s" % (",".join(bad), " / ".join(S.TPL_KEYS)))
return
tpl = ",".join(tpl_list)
if lock_tpl and not tpl:
print("❌ --lock-tpl 要跟 --tpl 一起用(没有模板,锁什么?)")
return
if n_free and n_fix:
print("❌「不限张数」和「固定张数」只能选一个")
return
made = S.gen_codes(n, batch, value, platform, tpl, is_set=is_set, direct=direct,
n_fix=n_fix, n_max=n_max, lock_tpl=lock_tpl, n_free=n_free)
stamp = S.now().strftime("%Y%m%d-%H%M%S")
out = os.path.join(S.ROOT, "exports", "codes-%s.csv" % stamp)
os.makedirs(os.path.dirname(out), exist_ok=True)
# ⚠️ 同一秒连开两批会撞名互相覆盖(2026-09-30 实踩)→ 撞了就在后面加 -2/-3
n_dup = 1
while os.path.exists(out):
n_dup += 1
out = os.path.join(S.ROOT, "exports", "codes-%s-%d.csv" % (stamp, n_dup))
with open(out, "w", newline="", encoding="utf-8-sig") as f:
w = csv.writer(f)
w.writerow(["兑换码", "面额", "批次", "平台", "模板", "固定张数", "不限张数",
"最多张数", "锁定模板"])
for c in made:
w.writerow([c, value, batch, platform, tpl, n_fix or "",
"是" if n_free else "", n_max or "", "是" if lock_tpl else ""])
print("已生成 %d 个兑换码(面额 ¥%s,批次 %s,平台 %s,模板 %s%s%s%s%s)"
% (len(made), value, batch or "-", platform or "-", tpl or "-",
",★套装(一张管一整套)" if is_set else "",
",◆直发(不用等收货)" if direct else "",
(",张数固定 %d 张" % n_fix) if n_fix
else ((",不限张数" if n_free else ",最多 %d 张" % n_max) if (n_free or n_max) else ",一张码一张图"),
",🔒模板锁定不能改" if lock_tpl else ""))
for c in made:
print(" " + c)
print("\nCSV: %s" % out)
# ---- 发卡文本(金钻 2026-10-01 P4:爱发电/闲鱼「自动发货」直接整段粘)----
if export:
ex_dir = os.path.join(S.ROOT, "exports")
os.makedirs(ex_dir, exist_ok=True)
p = export if os.path.isabs(export) else os.path.join(ex_dir, export)
with open(p, "w", encoding="utf-8") as f:
f.write("\n".join(made) + "\n")
os.chmod(p, 0o640)
print("""
发卡文本: %s (%d 行,一行一码,可直接整段粘贴)
▸ 爱发电:创作中心 → 商品 → 编辑 → 发货方式「自动发货」→ 把那几行粘进去 → 保存
买家付款后爱发电自动发一张给他,他到 shop.example.com/order/ 点「卡密下单」填码就行
▸ 闲鱼/B站工坊:发货时复制一行发给买家
⚠️ 这份文本等于钱,别发群里、别进公开仓库(已设 640 权限)""" % (p, len(made)))
return 0
def cmd_codes(argv):
codes = S.load_codes()
flt = argv[0] if argv else ""
for c, v in sorted(codes.items()):
if flt == "--used" and not v.get("used"):
continue
if flt == "--unused" and v.get("used"):
continue
q = ("固定 %d 张" % v["n_fix"]) if v.get("n_fix") else \
("不限张数" if v.get("n_free") else (("最多 %d 张" % v["n_max"]) if v.get("n_max") else "1 码 1 张"))
stt = {"active": "可用", "bound": "已激活", "used": "已核销",
"inactive": "停用"}.get(S.code_state(v), "?")
tags = "%s%s%s%s" % (
("【%s】" % v["platform"]) if v.get("platform") else "",
("【%s】" % v["tpl"]) if v.get("tpl") else "",
"🔒" if v.get("lock_tpl") else "",
"◆直发" if v.get("direct") else "")
print("%s %-6s 张数=%-8s %s 订单=%s %s" % (
c, stt, q, tags, v.get("order") or "-",
v.get("ts") or v.get("bound_at") or ""))
stc = [S.code_state(v) for v in codes.values()]
print("\n合计 %d 张:可用 %d / 已激活 %d / 已核销 %d / 停用 %d"
% (len(codes), stc.count("active"), stc.count("bound"),
stc.count("used"), stc.count("inactive")))
def cmd_edit(argv):
"""改一张还没用掉的卡密(张数 / 锁定模板 / 直发 / 停用…)。
金钻 2026-09-30 晚:「这个也给你开 api,方便我管理和你介入」
用法:
admin.py edit <卡密> --n-fix 5 固定出 5 张(不能多也不能少)
admin.py edit <卡密> --unlimited 改成不限张数
admin.py edit <卡密> --n-max 20 封顶 20 张
admin.py edit <卡密> --lock-tpl 模板锁死(要码里已有模板)
admin.py edit <卡密> --unlock-tpl 解锁模板
admin.py edit <卡密> --tpl wheat,sakura 换一组模板
admin.py edit <卡密> --off / --on 停用 / 启用
"""
if not argv:
print(cmd_edit.__doc__)
return
code, p = argv[0], {}
for i, a in enumerate(argv):
nxt = argv[i + 1] if i + 1 < len(argv) else None
if a == "--n-fix" and nxt:
p["n_fix"] = nxt
elif a == "--n-max" and nxt:
p["n_max"] = nxt
elif a == "--unlimited":
p["unlimited"] = True
elif a == "--tpl" and nxt:
p["tpls"] = [x.strip() for x in nxt.split(",") if x.strip()]
elif a == "--lock-tpl":
p["lock_tpl"] = True
elif a == "--unlock-tpl":
p["lock_tpl"] = False
elif a == "--direct":
p["direct"] = True
elif a == "--no-direct":
p["direct"] = False
elif a == "--set":
p["set"] = True
elif a == "--no-set":
p["set"] = False
elif a == "--off":
p["state"] = "inactive"
elif a == "--on":
p["state"] = "active"
elif a == "--platform" and nxt:
p["platform"] = nxt
if not p:
print("没给要改什么 —— 看用法:")
print(cmd_edit.__doc__)
return
ok, e, info = S.edit_code(code, p)
if not ok:
print("❌ " + e)
return
print("✅ %s 改好了:张数 %s | 模板 %s%s | 直发 %s | 状态 %s"
% (info["code"],
(("固定 %d 张" % info["n_fix"]) if info["n_fix"]
else (("最多 %d 张" % info["n_max"]) if info["n_max"] else "不限")),
",".join(info["tpls"]) or "自由选",
"(🔒锁定)" if info["lock_tpl"] else "",
"是" if info["direct"] else "否", info["state"]))
def cmd_ls(argv):
st = argv[0] if argv else None
rows = S.list_orders((st,) if st else None)
if not rows:
print("(没有订单)")
return
for m in sorted(rows, key=lambda x: x.get("created") or ""):
print("%-10s %-8s %-19s %d 张 %s %s" % (
m["oid"], m.get("state"), m.get("created", ""),
len(m.get("templates") or []), m.get("arm"),
",".join(m.get("templates") or [])))
print("\n共 %d 单" % len(rows))
def cmd_show(argv):
if not argv:
sys.exit("用法: admin.py show <订单号>")
m = S.read_meta(argv[0])
if not m:
sys.exit("没有这个订单")
m2 = dict(m)
m2.pop("token", None)
print(json.dumps(m2, ensure_ascii=False, indent=1))
def cmd_retry(argv):
if not argv:
sys.exit("用法: admin.py retry <订单号>")
oid = argv[0]
m = S.read_meta(oid)
if not m:
sys.exit("没有这个订单")
m["state"] = "waiting"
m["note"] = "管理员退回重渲"
m["started"] = m["finished"] = None
S.write_meta(oid, m)
print("%s 已退回队列" % oid)
def cmd_calls(argv):
try:
for line in open(S.CALLS_FILE, encoding="utf-8"):
if line.strip():
r = json.loads(line)
print("%s 订单=%s IP=%s %s" % (r["ts"], r.get("order") or "-",
r.get("ip"), "已通知" if r.get("notified") else "未通知"))
except OSError:
print("(没有呼叫记录)")
def cmd_sweep(argv):
"""清过期成品 + **核销卡密**(金钻 2026-09-30 晚:「核销要等开放下载后 72 小时」)。
到期口径改用 S.expire_at():确认收货/直发出图之后 72 小时(没开放下载的用创建时间兜底)。
⚠️ 删文件之前先把卡密核销 —— 否则文件没了、码还挂在「已激活」,账永远对不上。
"""
n = freed = settled = 0
for oid in list(os.listdir(S.ORDERS)):
d = os.path.join(S.ORDERS, oid)
m = S.read_meta(oid)
if not m:
continue
exp = S.expire_at(m)
if exp is None or exp > datetime.now(S.CST):
continue
settled += S.settle_codes(oid, "订单到期清理(开放下载满 %dh)" % S.KEEP_HOURS)
for root, _, files in os.walk(d):
for f in files:
try:
freed += os.path.getsize(os.path.join(root, f))
except OSError:
pass
shutil.rmtree(d, ignore_errors=True)
n += 1
# 文件还在、但开放下载已满 72 小时的,也一起核销
settled += sum(x[1] for x in S.settle_due())
print("清理 %d 单,释放 %.1f MB,核销卡密 %d 张" % (n, freed / 1048576, settled))
def cmd_audit(argv):
n = int(argv[0]) if argv and argv[0].isdigit() else 40
try:
lines = [l for l in open(S.LOG_FILE, encoding="utf-8").read().splitlines()
if ("兑换码失败" in l or "拒绝" in l)]
except OSError:
lines = []
for l in lines[-n:]:
print(l)
print("\n共 %d 条异常记录" % len(lines))
def cmd_activate(argv):
"""网页下单:买家付了款,激活这一单 → 进队列开渲。"""
oid = (argv[0] if argv else "").strip().upper()
if not oid:
print("用法: activate <订单号>")
return
m = S.read_meta(oid)
if not m:
print("没有这个订单:%s" % oid)
return
st = m.get("state")
if st not in ("unpaid", "paid"):
print("订单 %s 现在是「%s」,不是待付款,没动它" % (oid, st))
return
m["state"] = "waiting"
m["paid_at"] = S.now().isoformat(timespec="seconds")
with S.LOCK:
S.write_meta(oid, m)
print("✅ 订单 %s 已激活 → 进入排队" % oid)
print(" 模板:%s | 分辨率:%s | 码:%s"
% (",".join(m.get("templates") or []), m.get("res"), ",".join(m.get("codes") or [])))
def cmd_pending(argv):
"""列出待付款的网页单(等你收钱激活的)"""
rows = S.list_orders(("unpaid", "paid"))
if not rows:
print("没有待付款 / 待激活的网页单")
return
for m in rows:
tag = "★买家已报付款" if m.get("state") == "paid" else "还没付款"
print("%s %-12s ¥%-5s %s 张 %s 码 %s"
% (m["oid"], tag, m.get("amount") or (S.PRICE_UNIT * len(m.get("templates") or [] or [1])),
len(m.get("templates") or []), ",".join(m.get("templates") or []),
",".join(m.get("codes") or [])))
print("\n共 %d 单 —— 确认到账后跑:python3 admin.py activate <订单号>" % len(rows))
def cmd_stat(argv):
codes = S.load_codes()
st = [S.code_state(v) for v in codes.values()]
print("卡密 %d 张(可用 %d / 已激活 %d / 已核销 %d / 停用 %d)"
% (len(codes), st.count("active"), st.count("bound"),
st.count("used"), st.count("inactive")))
hb = S.heartbeat()
print("渲染机 %s 最后心跳 %s" % ("在线" if hb["online"] else "离线", hb["last_seen"]))
for st in ("unpaid", "paid", "waiting", "working", "done", "failed"):
print("订单 %-8s %d" % (st, len(S.list_orders((st,)))))
total = 0
for root, _, files in os.walk(S.ROOT):
for f in files:
try:
total += os.path.getsize(os.path.join(root, f))
except OSError:
pass
print("数据占用 %.1f MB" % (total / 1048576))
def cmd_price(argv):
"""价格档位(金钻 2026-10-01:「按张数和优惠设置专属购买价格链接」)
看: python3 admin.py price
设: python3 admin.py price set 3 15 http<WIN-PATH>
(第 3 档 = 买 3 张 ¥15,付款按钮就跳这个商品链接;链接可省 = 用总链接)
删: python3 admin.py price rm 3
单价: python3 admin.py price per 6 (没配档位的张数按这个算)
"""
d = S.price_tiers()
tiers = d.get("tiers") or {}
if not argv:
print("单价(没配档位时):¥%g/张" % d["per"])
print("%-6s %-8s %s" % ("张数", "价格", "专属商品链接"))
for k in sorted(tiers, key=lambda x: int(x) if x.isdigit() else 99):
t = tiers[k] or {}
print("%-6s ¥%-7s %s" % (k, t.get("price"), t.get("payplatform") or "(用总链接)"))
if not tiers:
print("(还没配任何档位)")
print("\n设一档:python3 admin.py price set 3 15 http<WIN-PATH>")
return
sub = argv[0]
if sub == "per" and len(argv) > 1:
d["per"] = float(argv[1])
elif sub == "set" and len(argv) > 2:
n, price = argv[1], argv[2]
if not n.isdigit() or int(n) < 1:
raise SystemExit("张数要正整数")
tiers[n] = {"price": float(price), "payplatform": (argv[3] if len(argv) > 3 else "").strip()}
elif sub == "rm" and len(argv) > 1:
tiers.pop(argv[1], None)
else:
raise SystemExit("用法:price / price per N / price set N 价格 [链接] / price rm N")
d["tiers"] = tiers
S.jsave(S.PRICES_FILE, d)
try:
os.chmod(S.PRICES_FILE, 0o644)
except OSError:
pass
print("改好了 —— 现在:")
cmd_price([])
def cmd_gift(argv):
"""福利券(金钻 2026-10-01「赛博鸡蛋」):一批**免费、免付费、只限张数**的码,买家自取。
看: python3 admin.py gift
开一批:python3 admin.py gift new 赛博鸡蛋 --count 50 --n-fix 1
加 --tpl sakura --lock → 只让领的人试这个新模板(试玩券)
加 --days 7 → 7 天后自动收摊
加 --no-direct → 领到的券也要走「确认收货」才给原图(默认直发)
补货:python3 admin.py gift add <批次id> --count 20
收摊:python3 admin.py gift off <批次id> (已领到手的券不受影响)
⚠️ 建/补/收的逻辑全在 server.py(gift_batch_new / gift_batch_add / gift_batch_off)——
金钻电脑上那块**面板**(ys_admin.py 的「免费码」区块)调的是同一批函数。
**改规则只改 server.py 那一处**,别在这儿再写一遍(两边必漂移)。
"""
def show_all():
rows = S.gift_batches()["batches"] # 每次现读:刚建/补完的批次要立刻看见
if not rows:
print("(还没有福利券批次)")
return
print("%-16s %-16s %-6s %-6s %-8s %s" % ("批次", "名字", "总数", "已领", "还剩", "限制"))
for b in rows:
st = S.gift_stat(b["id"])
lim = "%d 张/人" % int(b.get("each") or 1)
lim += ",锁模板 %s" % b["tpl"] if b.get("lock_tpl") else ""
lim += ",%s 到期" % b["expire"] if b.get("expire") else ""
if not b.get("enabled", True):
lim += "(已收摊)"
print("%-16s %-16s %-6d %-6d %-8d %s"
% (b["id"], b.get("name") or "", st["total"], st["claimed"], st["left"], lim))
if not argv:
show_all()
return
sub = argv[0]
if sub == "new" and len(argv) > 1:
name = argv[1]
op = {"count": 20, "n-fix": 1, "each": 1, "tpl": "", "lock": False,
"days": 0, "note": "", "direct": True, "kind": "render", "free": False}
i = 2
while i < len(argv):
a = argv[i]
if a == "--count" and i + 1 < len(argv):
op["count"] = int(argv[i + 1]); i += 2
elif a == "--n-fix" and i + 1 < len(argv):
op["n-fix"] = int(argv[i + 1]); i += 2
elif a == "--each" and i + 1 < len(argv):
op["each"] = int(argv[i + 1]); i += 2
elif a == "--tpl" and i + 1 < len(argv):
op["tpl"] = argv[i + 1]; i += 2
elif a == "--days" and i + 1 < len(argv):
op["days"] = int(argv[i + 1]); i += 2
elif a == "--note" and i + 1 < len(argv):
op["note"] = argv[i + 1]; i += 2
elif a == "--lock":
op["lock"] = True; i += 1
elif a == "--kind" and i + 1 < len(argv):
op["kind"] = argv[i + 1]; i += 2 # render/standee/keychain/poster…
elif a == "--n-free":
op["free"] = True; i += 1 # 不限张数
elif a == "--no-direct":
op["direct"] = False; i += 1
else:
i += 1
try:
bid, codes = S.gift_batch_new(
name, count=op["count"], n_fix=op["n-fix"], n_free=op["free"],
tpl=op["tpl"], lock_tpl=op["lock"], days=op["days"],
note=op["note"], kind=op["kind"], direct=op["direct"], each=op["each"])
except ValueError as e:
raise SystemExit(str(e))
print("批次 id:%s(把这个贴给别人也行:福利页会自动列出来)" % bid)
print("生了 %d 张券。" % len(codes))
show_all()
elif sub == "add" and len(argv) > 1:
bid = argv[1]
n, direct = 20, None
i = 2
while i < len(argv):
if argv[i] == "--count" and i + 1 < len(argv):
n = int(argv[i + 1]); i += 2
elif argv[i] == "--no-direct":
direct = False; i += 1
elif argv[i] == "--direct":
direct = True; i += 1
else:
i += 1
try:
got = S.gift_batch_add(bid, n, direct=direct)
except ValueError as e:
raise SystemExit(str(e))
print("补了 %d 张(批次 %s)" % (len(got), bid))
show_all()
elif sub == "off" and len(argv) > 1:
try:
S.gift_batch_off(argv[1])
except ValueError as e:
raise SystemExit(str(e))
print("已收摊(已领到手的券照常用):%s" % argv[1])
show_all()
else:
raise SystemExit("用法见文件头注释")
CMDS = {"gen": cmd_gen, "codes": cmd_codes, "ls": cmd_ls, "show": cmd_show,
"gift": cmd_gift,
"price": cmd_price,
"retry": cmd_retry, "calls": cmd_calls, "sweep": cmd_sweep, "stat": cmd_stat,
"audit": cmd_audit, "activate": cmd_activate, "pending": cmd_pending,
"edit": cmd_edit}
if __name__ == "__main__":
if len(sys.argv) < 2 or sys.argv[1] not in CMDS:
print(__doc__)
sys.exit(1)
CMDS[sys.argv[1]](sys.argv[2:])