feat: 新增账号状态管理、头像功能与报表工具,完善账号系统

新增账号状态字段与停用校验,支持账号头像上传管理,新增物料收发汇总表合并工具,优化银行卡检查脚本,新增ERP登录复用模块,重构账号数据库迁移与管理接口
This commit is contained in:
2026-09-16 00:25:13 +08:00
parent 0ab43d0ed8
commit 813bee743b
27 changed files with 2533 additions and 268 deletions
+75 -7
View File
@@ -8,11 +8,13 @@ from __future__ import annotations
import hashlib
import json
from datetime import datetime, timedelta
from pathlib import Path
from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile
from fastapi.responses import FileResponse
from controlplane import config, schemas
from controlplane.core.auth import _require_admin
from controlplane.core.auth import _require_admin, _resolve_login
from controlplane.core.crypto import _hash_password
from controlplane.core.db import _audit, _db, _now
from controlplane.core.pkgutil import (
@@ -31,8 +33,9 @@ def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"
_require_admin(x_admin_token, x_api_token)
with _db() as conn:
rows = [dict(r) for r in conn.execute(
"SELECT account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd "
"FROM accounts ORDER BY account")]
"SELECT id, account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd, "
" avatar, status, created_at "
"FROM accounts ORDER BY id")]
for a in rows:
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
@@ -59,10 +62,10 @@ def admin_account_create(a: schemas.AccountCreateIn,
raise HTTPException(400, f"账号 {account} 已存在")
_hex, _salt = _hash_password(a.password)
with _db() as conn:
conn.execute("INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname) "
"VALUES (?, ?, ?, ?, ?, ?)",
conn.execute("INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
"created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip(),
(a.nickname or "").strip()))
(a.nickname or "").strip(), _now()))
conn.commit()
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
"nickname": (a.nickname or "").strip(), "is_admin": a.is_admin}
@@ -93,6 +96,12 @@ def admin_account_update(a: schemas.AccountUpdateIn,
else:
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?",
(account, login))
if a.status is not None:
# 禁止停用自己,避免把自己锁在门外
if not a.status and account == login:
raise HTTPException(400, "不能停用当前登录的账号")
conn.execute("UPDATE accounts SET status = ? WHERE account = ?",
(int(bool(a.status)), account))
conn.commit()
return {"ok": True, "account": account}
@@ -136,6 +145,64 @@ def admin_account_delete(d: schemas.AccountDelIn,
return {"ok": True, "account": account}
# ==================== 头像(自服务可传自己;管理员可传任意账号) ====================
_AVATAR_EXT = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
@router.post("/api/admin/avatar")
def admin_avatar_upload(file: UploadFile = File(...),
account: str = Query(...),
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token"),
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
"""上传账号头像:自服务传自己;管理员可传任意账号。覆盖旧头像。"""
try:
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
except Exception:
raise HTTPException(401, "登录态无效或已过期,请重新登录")
account = account.strip()
if not account:
raise HTTPException(400, "account 不能为空")
if account != login:
_require_admin(x_admin_token, x_api_token)
ext = Path(file.filename or "").suffix.lower()
if ext not in _AVATAR_EXT:
raise HTTPException(400, "仅支持图片格式(jpg/png/gif/webp)")
content = file.file.read()
if not content or len(content) > 2 * 1024 * 1024:
raise HTTPException(400, "头像文件为空或超过 2MB")
with _db() as conn:
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
raise HTTPException(400, f"账号 {account} 不存在")
old = conn.execute("SELECT avatar FROM accounts WHERE account = ?", (account,)).fetchone()
old_name = (old["avatar"] if old else "") or ""
config.AVATAR_DIR.mkdir(parents=True, exist_ok=True)
fname = f"{account}{ext}"
(config.AVATAR_DIR / fname).write_bytes(content)
if old_name and old_name != fname: # 换扩展名时清掉旧文件,防残留
try:
(config.AVATAR_DIR / old_name).unlink(missing_ok=True)
except OSError:
pass
with _db() as conn:
conn.execute("UPDATE accounts SET avatar = ? WHERE account = ?", (fname, account))
conn.commit()
return {"ok": True, "account": account, "avatar": fname}
@router.get("/api/avatar/{account}")
def admin_avatar_get(account: str) -> FileResponse:
"""读取账号头像(前端 img 直接引用;未设置返回 404)。"""
with _db() as conn:
row = conn.execute("SELECT avatar FROM accounts WHERE account = ?", (account,)).fetchone()
if not row or not row["avatar"]:
raise HTTPException(404, "未设置头像")
path = config.AVATAR_DIR / row["avatar"]
if not path.is_file():
raise HTTPException(404, "头像文件缺失")
return FileResponse(path)
# ==================== 授权 / 插件维护 ====================
@router.post("/api/admin/account_plugins")
def admin_grant(g: schemas.GrantIn,
@@ -366,7 +433,8 @@ def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"
"SELECT account, can_download, can_run FROM plugin_grants "
"WHERE plugin_id = ?", (p["id"],))}
accounts = [dict(r) for r in conn.execute(
"SELECT account, is_admin, dept, nickname FROM accounts ORDER BY account")]
"SELECT id, account, is_admin, dept, nickname, avatar, status, created_at "
"FROM accounts ORDER BY id")]
for a in accounts:
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]