Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

feat: expand admin ops, upstream billing, and usage alerts

yi26f162c96cfd
diff --git a/README.md b/README.md
index c06a1c3..c53e746 100644
--- a/README.md
+++ b/README.md
@@ -27,18 +27,15 @@
- Docker 仅用于 **Postgres / Redis**(见 [deploy/README.md](deploy/README.md))
```bash
-# 中间件
+# 中间件(Postgres + Redis)
cp deploy/.env.prod.example deploy/.env.prod
docker compose -f deploy/docker-compose.yml --env-file deploy/.env.prod up -d
-# 或开发只用 Redis + SQLite
-docker run -d --name printfilm-redis -p 6379:6379 redis:7-alpine
-
cd backend
python -m venv .venv
.\.venv\Scripts\activate
pip install -r requirements.txt
-copy .env.example .env # 填 ARK_API_KEY;正式库见 deploy/.env.prod.example
+copy .env.example .env # 填 DATABASE_URL / ARK_API_KEY;正式库见 deploy/.env.prod.example
uvicorn app.main:app --reload --port 8000
```
@@ -81,7 +78,7 @@ npm run dev
## 架构摘要
-- FastAPI + PostgreSQL(Docker)/ 本地可 SQLite
+- FastAPI + PostgreSQL(Docker)
- Redis(可选):部分进度/基础设施可复用,已不再作为任务平台前提
- 内置任务平台:`scheduler + executor + poller`(随 FastAPI 进程启动)
- 前端:React + TS + Vite(用户端)
diff --git a/admin/package-lock.json b/admin/package-lock.json
index e342d1a..bc453a5 100644
--- a/admin/package-lock.json
+++ b/admin/package-lock.json
@@ -22,6 +22,7 @@
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-router-dom": "^7.18.2",
+ "recharts": "^3.10.1",
"sonner": "^2.0.8",
"tailwind-merge": "^3.6.0"
},
@@ -1243,6 +1244,32 @@
"integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==",
"license": "MIT"
},
+ "node_modules/@reduxjs/toolkit": {
+ "version": "2.12.0",
+ "resolved": "https://registry.npmmirror.com/@reduxjs/toolkit/-/toolkit-2.12.0.tgz",
+ "integrity": "sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw==",
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "^1.0.0",
+ "@standard-schema/utils": "^0.3.0",
+ "immer": "^11.0.0",
+ "redux": "^5.0.1",
+ "redux-thunk": "^3.1.0",
+ "reselect": "^5.1.0"
+ },
+ "peerDependencies": {
+ "react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
+ "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
+ },
+ "peerDependenciesMeta": {
+ "react": {
+ "optional": true
+ },
+ "react-redux": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.2.3",
"resolved": "https://registry.npmmirror.com/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.3.tgz",
@@ -1506,6 +1533,18 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "license": "MIT"
+ },
+ "node_modules/@standard-schema/utils": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmmirror.com/@standard-schema/utils/-/utils-0.3.0.tgz",
+ "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
+ "license": "MIT"
+ },
"node_modules/@tailwindcss/node": {
"version": "4.3.3",
"resolved": "https://registry.npmmirror.com/@tailwindcss/node/-/node-4.3.3.tgz",
@@ -2063,6 +2102,69 @@
"vite": "^5.2.0 || ^6 || ^7 || ^8"
}
},
+ "node_modules/@types/d3-array": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmmirror.com/@types/d3-array/-/d3-array-3.2.2.tgz",
+ "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-color": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmmirror.com/@types/d3-color/-/d3-color-3.1.3.tgz",
+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-ease": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmmirror.com/@types/d3-ease/-/d3-ease-3.0.2.tgz",
+ "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-interpolate": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmmirror.com/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-color": "*"
+ }
+ },
+ "node_modules/@types/d3-path": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmmirror.com/@types/d3-path/-/d3-path-3.1.1.tgz",
+ "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-scale": {
+ "version": "4.0.9",
+ "resolved": "https://registry.npmmirror.com/@types/d3-scale/-/d3-scale-4.0.9.tgz",
+ "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-time": "*"
+ }
+ },
+ "node_modules/@types/d3-shape": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmmirror.com/@types/d3-shape/-/d3-shape-3.2.0.tgz",
+ "integrity": "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-path": "*"
+ }
+ },
+ "node_modules/@types/d3-time": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmmirror.com/@types/d3-time/-/d3-time-3.0.4.tgz",
+ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-timer": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmmirror.com/@types/d3-timer/-/d3-timer-3.0.2.tgz",
+ "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
+ "license": "MIT"
+ },
"node_modules/@types/node": {
"version": "24.13.3",
"resolved": "https://registry.npmmirror.com/@types/node/-/node-24.13.3.tgz",
@@ -2093,6 +2195,12 @@
"@types/react": "^19.2.0"
}
},
+ "node_modules/@types/use-sync-external-store": {
+ "version": "0.0.6",
+ "resolved": "https://registry.npmmirror.com/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
+ "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
+ "license": "MIT"
+ },
"node_modules/@vitejs/plugin-react": {
"version": "6.0.5",
"resolved": "https://registry.npmmirror.com/@vitejs/plugin-react/-/plugin-react-6.0.5.tgz",
@@ -2172,6 +2280,133 @@
"devOptional": true,
"license": "MIT"
},
+ "node_modules/d3-array": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmmirror.com/d3-array/-/d3-array-3.2.4.tgz",
+ "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
+ "license": "ISC",
+ "dependencies": {
+ "internmap": "1 - 2"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-color": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmmirror.com/d3-color/-/d3-color-3.1.0.tgz",
+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-ease": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/d3-ease/-/d3-ease-3.0.1.tgz",
+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-format": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmmirror.com/d3-format/-/d3-format-3.1.2.tgz",
+ "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-interpolate": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-path": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmmirror.com/d3-path/-/d3-path-3.1.0.tgz",
+ "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-scale": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmmirror.com/d3-scale/-/d3-scale-4.0.2.tgz",
+ "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2.10.0 - 3",
+ "d3-format": "1 - 3",
+ "d3-interpolate": "1.2.0 - 3",
+ "d3-time": "2.1.1 - 3",
+ "d3-time-format": "2 - 4"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-shape": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmmirror.com/d3-shape/-/d3-shape-3.2.0.tgz",
+ "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-path": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-time": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmmirror.com/d3-time/-/d3-time-3.1.0.tgz",
+ "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-time-format": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmmirror.com/d3-time-format/-/d3-time-format-4.1.0.tgz",
+ "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-time": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-timer": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/d3-timer/-/d3-timer-3.0.1.tgz",
+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/decimal.js-light": {
+ "version": "2.5.1",
+ "resolved": "https://registry.npmmirror.com/decimal.js-light/-/decimal.js-light-2.5.1.tgz",
+ "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",
+ "license": "MIT"
+ },
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -2202,6 +2437,24 @@
"node": ">=10.13.0"
}
},
+ "node_modules/es-toolkit": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmmirror.com/es-toolkit/-/es-toolkit-1.52.0.tgz",
+ "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==",
+ "license": "MIT",
+ "workspaces": [
+ "docs",
+ "benchmarks",
+ "tests/types",
+ "tests/browser-compat"
+ ]
+ },
+ "node_modules/eventemitter3": {
+ "version": "5.0.4",
+ "resolved": "https://registry.npmmirror.com/eventemitter3/-/eventemitter3-5.0.4.tgz",
+ "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
+ "license": "MIT"
+ },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz",
@@ -2251,6 +2504,25 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/immer": {
+ "version": "11.1.18",
+ "resolved": "https://registry.npmmirror.com/immer/-/immer-11.1.18.tgz",
+ "integrity": "sha512-EQyQtLiYW029lyoczMl/Hh4Xu7cDecSc58JRYpHyL4tIAu3eqd1yJzQX04d2BZHDkzFFvm6qJEJWOtfDSWAXbQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/immer"
+ }
+ },
+ "node_modules/internmap": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmmirror.com/internmap/-/internmap-2.0.3.tgz",
+ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/jiti": {
"version": "2.7.0",
"resolved": "https://registry.npmmirror.com/jiti/-/jiti-2.7.0.tgz",
@@ -2691,6 +2963,36 @@
"react": "^19.2.8"
}
},
+ "node_modules/react-is": {
+ "version": "19.2.8",
+ "resolved": "https://registry.npmmirror.com/react-is/-/react-is-19.2.8.tgz",
+ "integrity": "sha512-s5un28nYxKJw5gvUHyW5PCC28CvBqLu9r3cWgzHT4Vo/5fqqkFcdRYsGcKf50WMPpjjFZS5d76fn3YCo2njKwQ==",
+ "license": "MIT",
+ "peer": true
+ },
+ "node_modules/react-redux": {
+ "version": "9.3.0",
+ "resolved": "https://registry.npmmirror.com/react-redux/-/react-redux-9.3.0.tgz",
+ "integrity": "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/use-sync-external-store": "^0.0.6",
+ "use-sync-external-store": "^1.4.0"
+ },
+ "peerDependencies": {
+ "@types/react": "^18.2.25 || ^19",
+ "react": "^18.0 || ^19",
+ "redux": "^5.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "redux": {
+ "optional": true
+ }
+ }
+ },
"node_modules/react-remove-scroll": {
"version": "2.7.2",
"resolved": "https://registry.npmmirror.com/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",
@@ -2798,6 +3100,57 @@
}
}
},
+ "node_modules/recharts": {
+ "version": "3.10.1",
+ "resolved": "https://registry.npmmirror.com/recharts/-/recharts-3.10.1.tgz",
+ "integrity": "sha512-QXFrvt6IVcw7eeZCoyXTwkIJAX3Dv1nyVhMicXJ47GsGDDpcN8z6o644DibE9XjpBTThtsomLKnTV6lc+cVFUA==",
+ "license": "MIT",
+ "workspaces": [
+ "www"
+ ],
+ "dependencies": {
+ "@reduxjs/toolkit": "^1.9.0 || 2.x.x",
+ "clsx": "^2.1.1",
+ "decimal.js-light": "^2.5.1",
+ "es-toolkit": "^1.39.3",
+ "eventemitter3": "^5.0.1",
+ "immer": "^11.1.8",
+ "react-redux": "8.x.x || 9.x.x",
+ "reselect": "5.2.0",
+ "tiny-invariant": "^1.3.3",
+ "use-sync-external-store": "^1.2.2",
+ "victory-vendor": "^37.0.2"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
+ "node_modules/redux": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmmirror.com/redux/-/redux-5.0.1.tgz",
+ "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
+ "license": "MIT"
+ },
+ "node_modules/redux-thunk": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmmirror.com/redux-thunk/-/redux-thunk-3.1.0.tgz",
+ "integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "redux": "^5.0.0"
+ }
+ },
+ "node_modules/reselect": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmmirror.com/reselect/-/reselect-5.2.0.tgz",
+ "integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==",
+ "license": "MIT"
+ },
"node_modules/rolldown": {
"version": "1.2.3",
"resolved": "https://registry.npmmirror.com/rolldown/-/rolldown-1.2.3.tgz",
@@ -2900,6 +3253,12 @@
"url": "https://opencollective.com/webpack"
}
},
+ "node_modules/tiny-invariant": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmmirror.com/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
+ "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
+ "license": "MIT"
+ },
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -2987,6 +3346,37 @@
}
}
},
+ "node_modules/use-sync-external-store": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmmirror.com/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
+ "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
+ "node_modules/victory-vendor": {
+ "version": "37.3.6",
+ "resolved": "https://registry.npmmirror.com/victory-vendor/-/victory-vendor-37.3.6.tgz",
+ "integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==",
+ "license": "MIT AND ISC",
+ "dependencies": {
+ "@types/d3-array": "^3.0.3",
+ "@types/d3-ease": "^3.0.0",
+ "@types/d3-interpolate": "^3.0.1",
+ "@types/d3-scale": "^4.0.2",
+ "@types/d3-shape": "^3.1.0",
+ "@types/d3-time": "^3.0.0",
+ "@types/d3-timer": "^3.0.0",
+ "d3-array": "^3.1.6",
+ "d3-ease": "^3.0.1",
+ "d3-interpolate": "^3.0.1",
+ "d3-scale": "^4.0.2",
+ "d3-shape": "^3.1.0",
+ "d3-time": "^3.0.0",
+ "d3-timer": "^3.0.1"
+ }
+ },
"node_modules/vite": {
"version": "8.2.1",
"resolved": "https://registry.npmmirror.com/vite/-/vite-8.2.1.tgz",
diff --git a/admin/package.json b/admin/package.json
index 9c98c8e..19ba669 100644
--- a/admin/package.json
+++ b/admin/package.json
@@ -24,6 +24,7 @@
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-router-dom": "^7.18.2",
+ "recharts": "^3.10.1",
"sonner": "^2.0.8",
"tailwind-merge": "^3.6.0"
},
diff --git a/admin/src/App.tsx b/admin/src/App.tsx
index 08a192e..43ab1fe 100644
--- a/admin/src/App.tsx
+++ b/admin/src/App.tsx
@@ -6,6 +6,13 @@ import { LoginPage } from "@/pages/LoginPage";
import { OrdersPage } from "@/pages/OrdersPage";
import { ProjectsPage } from "@/pages/ProjectsPage";
import { DramaProjectsPage } from "@/pages/DramaProjectsPage";
+import { DramaAssetDetailPage } from "@/pages/drama/DramaAssetDetailPage";
+import { DramaAssetsPage } from "@/pages/drama/DramaAssetsPage";
+import { DramaEpisodeDetailPage } from "@/pages/drama/DramaEpisodeDetailPage";
+import { DramaEpisodesPage } from "@/pages/drama/DramaEpisodesPage";
+import { DramaFragmentDetailPage } from "@/pages/drama/DramaFragmentDetailPage";
+import { DramaFragmentsPage } from "@/pages/drama/DramaFragmentsPage";
+import { DramaProjectDetailPage } from "@/pages/drama/DramaProjectDetailPage";
import { QueuesPage } from "@/pages/QueuesPage";
import { SettingsPage } from "@/pages/SettingsPage";
import { TemplatesPage } from "@/pages/TemplatesPage";
@@ -34,6 +41,13 @@ export default function App() {
<Route path="orders" element={<OrdersPage />} />
<Route path="projects" element={<ProjectsPage />} />
<Route path="drama-projects" element={<DramaProjectsPage />} />
+ <Route path="drama-projects/:projectId" element={<DramaProjectDetailPage />} />
+ <Route path="drama-assets" element={<DramaAssetsPage />} />
+ <Route path="drama-assets/:assetId" element={<DramaAssetDetailPage />} />
+ <Route path="drama-episodes" element={<DramaEpisodesPage />} />
+ <Route path="drama-episodes/:episodeId" element={<DramaEpisodeDetailPage />} />
+ <Route path="drama-fragments" element={<DramaFragmentsPage />} />
+ <Route path="drama-fragments/:fragmentId" element={<DramaFragmentDetailPage />} />
<Route path="works" element={<WorksPage />} />
<Route path="templates" element={<TemplatesPage />} />
<Route path="queues" element={<QueuesPage />} />
diff --git a/admin/src/api/client.ts b/admin/src/api/client.ts
index 211a4db..316f4df 100644
--- a/admin/src/api/client.ts
+++ b/admin/src/api/client.ts
@@ -66,12 +66,14 @@ export type AdminUsageBucket = {
key: string;
calls: number;
charge_fen: number;
+ cost_fen?: number;
};
export type AdminDailyUsage = {
date: string;
calls: number;
charge_fen: number;
+ cost_fen?: number;
};
export type AdminTopUser = {
@@ -136,10 +138,35 @@ export type AdminStats = {
top_users_by_charge?: AdminTopUser[];
};
+export type AdminUpstreamUsageDay = {
+ date: string;
+ local_cost_fen: number;
+ local_tokens: number;
+ official_tokens: number;
+ official_cost_fen: number;
+ delta_fen: number;
+ delta_pct?: number | null;
+};
+
+export type AdminUpstreamUsage = {
+ configured: boolean;
+ days: number;
+ last_sync_at?: string | null;
+ series: AdminUpstreamUsageDay[];
+};
+
+export type AdminUpstreamUsageSync = {
+ configured: boolean;
+ synced: number;
+ skipped: number;
+ last_sync_at?: string | null;
+};
+
export type AdminUserRow = {
id: number;
email: string;
nickname: string;
+ phone?: string;
quota_left: number;
balance_fen: number;
frozen_fen: number;
@@ -149,6 +176,7 @@ export type AdminUserRow = {
created_at?: string | null;
};
+/** @deprecated 遗留 Celery 队列快照,任务中心已改用 /api/admin/tasks */
export type AdminOrder = {
id: number;
out_trade_no: string;
@@ -230,6 +258,69 @@ export type AdminDramaProject = {
recent_tasks?: AdminTaskBrief[];
};
+export type AdminDramaAsset = {
+ id: number;
+ project_id: number;
+ project_title?: string | null;
+ user_id?: number | null;
+ user_email?: string | null;
+ type: string;
+ asset_type: string;
+ name?: string | null;
+ cover?: string | null;
+ url?: string | null;
+ has_cover: boolean;
+ generation_status?: string | null;
+ derive_id?: string | null;
+ created_at?: string | null;
+ updated_at?: string | null;
+ params?: Record<string, unknown> | null;
+};
+
+export type AdminDramaEpisode = {
+ id: number;
+ project_id: number;
+ project_title?: string | null;
+ user_id?: number | null;
+ user_email?: string | null;
+ name: string;
+ fragment_count: number;
+ fragment_plan_status?: string | null;
+ created_at?: string | null;
+ updated_at?: string | null;
+ fragments?: {
+ id: number;
+ sort_order: number;
+ content: string;
+ cover: string;
+ video: string;
+ duration_sec?: number | null;
+ generation_status?: string | null;
+ asset_ref_count: number;
+ }[];
+};
+
+export type AdminDramaFragment = {
+ id: number;
+ episode_id: number;
+ episode_name?: string | null;
+ project_id: number;
+ project_title?: string | null;
+ user_id?: number | null;
+ user_email?: string | null;
+ sort_order: number;
+ content: string;
+ cover: string;
+ video: string;
+ duration_sec?: number | null;
+ generation_status?: string | null;
+ asset_ref_count: number;
+ created_at?: string | null;
+ updated_at?: string | null;
+ params?: Record<string, unknown> | null;
+ asset_ids?: number[];
+};
+
export type AdminWork = {
id: number;
project_id: number;
@@ -262,6 +353,7 @@ export type AdminQueueSummary = {
sample: AdminQueueTask[];
};
+/** @deprecated 遗留 Celery 队列快照,任务中心已改用 /api/admin/tasks */
export type AdminQueuesSnapshot = {
ok: boolean;
redis_ok: boolean;
@@ -311,7 +403,10 @@ export type AdminUsageEventBrief = {
model?: string;
total_tokens?: number;
charge_fen?: number;
+ cost_fen?: number;
estimated?: boolean;
+ billing_basis?: string;
+ billing_basis_label?: string;
created_at?: string | null;
};
@@ -328,10 +423,15 @@ export type AdminUsageEvent = {
charge_fen?: number;
cost_fen?: number;
estimated?: boolean;
+ billing_basis?: string;
+ billing_basis_label?: string;
created_at?: string | null;
task_domain?: string | null;
task_type?: string | null;
task_status?: string | null;
+ project_id?: number | null;
+ drama_project_id?: number | null;
+ provider?: string | null;
};
export type AdminUsageEventListRes = {
@@ -501,6 +601,28 @@ export type AdminModelSettings = {
billing_signup_grant_fen: number;
quota_enabled: boolean;
new_user_quota: number;
+ billing_user_alert_enabled: boolean;
+ billing_user_alert_interval_fen: number;
+ billing_admin_cost_alert_enabled: boolean;
+ billing_admin_cost_alert_threshold_fen: number;
+ billing_admin_cost_alert_emails: string;
+ billing_admin_cost_alert_period: string;
+ billing_admin_cost_alert_last_period_key: string;
+ billing_admin_cost_alert_last_level: number;
+ smtp_enabled: boolean;
+ smtp_host: string;
+ smtp_port: number;
+ smtp_user: string;
+ smtp_password: string;
+ smtp_from: string;
+ smtp_use_tls: boolean;
+ has_smtp_password: boolean;
+ volc_access_key_id: string;
+ volc_secret_access_key: string;
+ volc_ark_region: string;
+ volc_ark_usage_enabled: boolean;
+ has_volc_access_key_id: boolean;
+ has_volc_secret_access_key: boolean;
public_base_url: string;
ffmpeg_path: string;
ffprobe_path: string;
diff --git a/admin/src/components/admin/AdminChipFilter.tsx b/admin/src/components/admin/AdminChipFilter.tsx
index 0ab68b3..844a80a 100644
--- a/admin/src/components/admin/AdminChipFilter.tsx
+++ b/admin/src/components/admin/AdminChipFilter.tsx
@@ -16,10 +16,11 @@ type AdminChipFilterProps = {
// 管理端分类 Chip 筛选
export function AdminChipFilter({ label, value, options, onChange, className }: AdminChipFilterProps) {
+ const segment = className?.includes("admin-chip-filter--segment");
return (
<div className={cn("admin-chip-filter", className)}>
{label ? <span className="admin-chip-filter-label">{label}</span> : null}
- <div className="admin-chip-filter-list" role="tablist">
+ <div className={cn("admin-chip-filter-list", segment && "is-segment")} role="tablist">
{options.map((opt) => {
const active = value === opt.value;
return (
@@ -28,7 +29,7 @@ export function AdminChipFilter({ label, value, options, onChange, className }:
type="button"
role="tab"
aria-selected={active}
- className={cn("admin-chip", active && "is-active")}
+ className={cn(segment ? "admin-segment-btn" : "admin-chip", active && "is-active")}
onClick={() => onChange(opt.value)}
>
{opt.label}
diff --git a/admin/src/components/admin/AdminDateRangeFilter.tsx b/admin/src/components/admin/AdminDateRangeFilter.tsx
new file mode 100644
index 0000000..f1e166c
--- /dev/null
+++ b/admin/src/components/admin/AdminDateRangeFilter.tsx
@@ -0,0 +1,35 @@
+import { cn } from "@/lib/utils";
+
+type AdminDateRangeFilterProps = {
+ from: string;
+ to: string;
+ onChange: (next: { from: string; to: string }) => void;
+ className?: string;
+};
+
+/** 日期范围筛选(ISO date 字符串 YYYY-MM-DD) */
+export function AdminDateRangeFilter({ from, to, onChange, className }: AdminDateRangeFilterProps) {
+ return (
+ <div className={cn("admin-date-range", className)}>
+ <label className="admin-field">
+ <span className="admin-field-label">开始</span>
+ <input
+ type="date"
+ className="admin-input"
+ value={from}
+ onChange={(e) => onChange({ from: e.target.value, to })}
+ />
+ </label>
+ <span className="admin-date-range-sep">—</span>
+ <label className="admin-field">
+ <span className="admin-field-label">结束</span>
+ <input
+ type="date"
+ className="admin-input"
+ value={to}
+ onChange={(e) => onChange({ from, to: e.target.value })}
+ />
+ </label>
+ </div>
+ );
+}
diff --git a/admin/src/components/admin/AdminDetailLayout.tsx b/admin/src/components/admin/AdminDetailLayout.tsx
new file mode 100644
index 0000000..3954258
--- /dev/null
+++ b/admin/src/components/admin/AdminDetailLayout.tsx
@@ -0,0 +1,90 @@
+import type { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+
+type MetaItem = {
+ label: string;
+ value: ReactNode;
+ full?: boolean;
+};
+
+type StatItem = {
+ label: string;
+ value: ReactNode;
+};
+
+/** 详情弹窗分区标题 + 内容 */
+export function AdminDetailSection({
+ title,
+ children,
+ className,
+}: {
+ title?: string;
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <section className={cn("admin-detail-section", className)}>
+ {title ? <h4 className="admin-detail-section-title">{title}</h4> : null}
+ {children}
+ </section>
+ );
+}
+
+/** 只读 key-value 网格(基本信息) */
+export function AdminDetailMeta({ items }: { items: MetaItem[] }) {
+ return (
+ <dl className="admin-detail-meta">
+ {items.map((item) => (
+ <div
+ key={item.label}
+ className={cn("admin-detail-meta-item", item.full && "admin-detail-meta-item--full")}
+ >
+ <dt>{item.label}</dt>
+ <dd>{item.value}</dd>
+ </div>
+ ))}
+ </dl>
+ );
+}
+
+/** 费用/指标四宫格 */
+export function AdminDetailStatGrid({ items }: { items: StatItem[] }) {
+ return (
+ <div className="admin-detail-stat-grid">
+ {items.map((item) => (
+ <div key={item.label} className="admin-detail-stat-card">
+ <div className="admin-detail-stat-label">{item.label}</div>
+ <div className="admin-detail-stat-value">{item.value}</div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+/** 弹窗内嵌表格容器 */
+export function AdminDetailTableWrap({
+ children,
+ className,
+}: {
+ children: ReactNode;
+ className?: string;
+}) {
+ return <div className={cn("admin-detail-table-wrap", className)}>{children}</div>;
+}
+
+/** 备注/脚本文本块 */
+export function AdminDetailNote({
+ children,
+ empty = false,
+ className,
+}: {
+ children: ReactNode;
+ empty?: boolean;
+ className?: string;
+}) {
+ return (
+ <div className={cn("admin-detail-note", empty && "admin-detail-note--empty", className)}>
+ {children}
+ </div>
+ );
+}
diff --git a/admin/src/components/admin/AdminEntityLink.tsx b/admin/src/components/admin/AdminEntityLink.tsx
new file mode 100644
index 0000000..14ca161
--- /dev/null
+++ b/admin/src/components/admin/AdminEntityLink.tsx
@@ -0,0 +1,60 @@
+import { Link } from "react-router-dom";
+import { cn } from "@/lib/utils";
+import { formatAccountId } from "@/lib/admin-account";
+
+type EntityKind = "user" | "project" | "drama" | "drama_asset" | "task" | "order";
+
+type AdminEntityLinkProps = {
+ kind: EntityKind;
+ id: number;
+ label?: string;
+ className?: string;
+};
+
+function buildHref(kind: EntityKind, id: number): string {
+ switch (kind) {
+ case "user":
+ return `/users?user=${id}`;
+ case "project":
+ return `/projects?open=${id}`;
+ case "drama":
+ return `/drama-projects/${id}`;
+ case "drama_asset":
+ return `/drama-assets/${id}`;
+ case "task":
+ return `/queues?task=${id}`;
+ case "order":
+ return `/orders?tab=orders&order=${id}`;
+ default:
+ return "#";
+ }
+}
+
+function defaultLabel(kind: EntityKind, id: number): string {
+ switch (kind) {
+ case "user":
+ return `ID:${formatAccountId(id)}`;
+ case "project":
+ return `科普#${id}`;
+ case "drama":
+ return `漫剧#${id}`;
+ case "drama_asset":
+ return `资产#${id}`;
+ case "task":
+ return `任务#${id}`;
+ case "order":
+ return `订单#${id}`;
+ default:
+ return String(id);
+ }
+}
+
+/** 跨页实体跳转链接 */
+export function AdminEntityLink({ kind, id, label, className }: AdminEntityLinkProps) {
+ if (!id) return <span className="text-[var(--admin-muted)]">—</span>;
+ return (
+ <Link to={buildHref(kind, id)} className={cn("admin-link font-medium", className)}>
+ {label ?? defaultLabel(kind, id)}
+ </Link>
+ );
+}
diff --git a/admin/src/components/admin/AdminFilterBar.tsx b/admin/src/components/admin/AdminFilterBar.tsx
index 173d532..97810d3 100644
--- a/admin/src/components/admin/AdminFilterBar.tsx
+++ b/admin/src/components/admin/AdminFilterBar.tsx
@@ -7,12 +7,28 @@ type AdminFilterBarProps = {
className?: string;
};
-// 管理端列表筛选条容器
+/** 管理端列表筛选条:单行紧凑横排,空间不足时自动换行 */
export function AdminFilterBar({ children, trailing, className }: AdminFilterBarProps) {
return (
- <div className={cn("admin-filter-panel", className)}>
- <div className="admin-filter-panel-main">{children}</div>
- {trailing ? <div className="admin-filter-panel-trailing">{trailing}</div> : null}
+ <div className={cn("admin-filter-bar", className)}>
+ <div className="admin-filter-bar-main">{children}</div>
+ {trailing ? <div className="admin-filter-bar-trailing">{trailing}</div> : null}
</div>
);
}
+
+type AdminFilterFieldProps = {
+ label?: string;
+ children: ReactNode;
+ className?: string;
+};
+
+/** 筛选条内联字段:标签与控件同一行 */
+export function AdminFilterField({ label, children, className }: AdminFilterFieldProps) {
+ return (
+ <label className={cn("admin-filter-inline", className)}>
+ {label ? <span className="admin-filter-inline-label">{label}</span> : null}
+ {children}
+ </label>
+ );
+}
diff --git a/admin/src/components/admin/AdminListStats.tsx b/admin/src/components/admin/AdminListStats.tsx
new file mode 100644
index 0000000..6641412
--- /dev/null
+++ b/admin/src/components/admin/AdminListStats.tsx
@@ -0,0 +1,29 @@
+import type { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+
+export type AdminListStatItem = {
+ label: string;
+ value: ReactNode;
+ hint?: string;
+};
+
+type AdminListStatsProps = {
+ items: AdminListStatItem[];
+ className?: string;
+};
+
+/** 列表页顶部指标卡(白底简洁样式) */
+export function AdminListStats({ items, className }: AdminListStatsProps) {
+ if (items.length === 0) return null;
+ return (
+ <div className={cn("admin-list-stats", className)}>
+ {items.map((item) => (
+ <div key={item.label} className="admin-list-stat-card">
+ <div className="admin-list-stat-label">{item.label}</div>
+ <div className="admin-list-stat-value">{item.value}</div>
+ {item.hint ? <div className="admin-list-stat-hint">{item.hint}</div> : null}
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/admin/src/components/admin/AdminSearchInput.tsx b/admin/src/components/admin/AdminSearchInput.tsx
index 3819a2e..a6eaa3e 100644
--- a/admin/src/components/admin/AdminSearchInput.tsx
+++ b/admin/src/components/admin/AdminSearchInput.tsx
@@ -1,10 +1,12 @@
import { cn } from "@/lib/utils";
+import type { KeyboardEventHandler } from "react";
type AdminSearchInputProps = {
value: string;
onChange: (value: string) => void;
placeholder?: string;
className?: string;
+ onKeyDown?: KeyboardEventHandler<HTMLInputElement>;
};
// 管理端搜索框(带图标)
@@ -13,9 +15,10 @@ export function AdminSearchInput({
onChange,
placeholder = "搜索…",
className,
+ onKeyDown,
}: AdminSearchInputProps) {
return (
- <div className={cn("admin-input-search-wrap", className)}>
+ <div className={cn("admin-input-search-wrap admin-filter-search", className)}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden>
<path
d="M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm10 2-4.35-4.35"
@@ -29,6 +32,7 @@ export function AdminSearchInput({
placeholder={placeholder}
value={value}
onChange={(e) => onChange(e.target.value)}
+ onKeyDown={onKeyDown}
/>
</div>
);
diff --git a/admin/src/components/admin/AdminUserSearchSelect.tsx b/admin/src/components/admin/AdminUserSearchSelect.tsx
new file mode 100644
index 0000000..2637f3c
--- /dev/null
+++ b/admin/src/components/admin/AdminUserSearchSelect.tsx
@@ -0,0 +1,132 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { api, type AdminUserRow, type PageMeta } from "@/api/client";
+import { formatAccountId, parseAccountIdQuery } from "@/lib/admin-account";
+import { cn } from "@/lib/utils";
+
+type ListRes = { items: AdminUserRow[]; meta: PageMeta };
+
+type AdminUserSearchSelectProps = {
+ value: number | null;
+ onChange: (userId: number | null, user?: AdminUserRow | null) => void;
+ placeholder?: string;
+ className?: string;
+};
+
+/** 远程搜索用户(账号 ID + 邮箱) */
+export function AdminUserSearchSelect({
+ value,
+ onChange,
+ placeholder = "搜索用户邮箱 / 账号 ID",
+ className,
+}: AdminUserSearchSelectProps) {
+ const [query, setQuery] = useState("");
+ const [options, setOptions] = useState<AdminUserRow[]>([]);
+ const [open, setOpen] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [selectedLabel, setSelectedLabel] = useState("");
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const loadSelected = useCallback(async (userId: number) => {
+ try {
+ const res = await api<ListRes>(
+ `/api/admin/users?page=1&page_size=1&q=${encodeURIComponent(String(userId))}`,
+ );
+ const hit = res.items.find((u) => u.id === userId) ?? res.items[0];
+ if (hit) {
+ setSelectedLabel(`${hit.email} · ID:${formatAccountId(hit.id)}`);
+ }
+ } catch {
+ setSelectedLabel(`ID:${formatAccountId(userId)}`);
+ }
+ }, []);
+
+ useEffect(() => {
+ if (value) void loadSelected(value);
+ else setSelectedLabel("");
+ }, [value, loadSelected]);
+
+ const search = useCallback((raw: string) => {
+ if (debounceRef.current) clearTimeout(debounceRef.current);
+ debounceRef.current = setTimeout(async () => {
+ const q = raw.trim();
+ if (!q) {
+ setOptions([]);
+ return;
+ }
+ setLoading(true);
+ try {
+ const accountId = parseAccountIdQuery(q);
+ const searchQ = accountId != null ? String(accountId) : q;
+ const res = await api<ListRes>(
+ `/api/admin/users?page=1&page_size=10&q=${encodeURIComponent(searchQ)}`,
+ );
+ setOptions(res.items);
+ } catch {
+ setOptions([]);
+ } finally {
+ setLoading(false);
+ }
+ }, 280);
+ }, []);
+
+ return (
+ <div className={cn("admin-user-search", className)}>
+ <input
+ className="admin-input"
+ placeholder={value ? selectedLabel || placeholder : placeholder}
+ value={open ? query : value ? selectedLabel : query}
+ onChange={(e) => {
+ setQuery(e.target.value);
+ setOpen(true);
+ search(e.target.value);
+ }}
+ onFocus={() => setOpen(true)}
+ onBlur={() => {
+ setTimeout(() => setOpen(false), 150);
+ }}
+ />
+ {value ? (
+ <button
+ type="button"
+ className="admin-user-search-clear"
+ onClick={() => {
+ onChange(null, null);
+ setQuery("");
+ setSelectedLabel("");
+ }}
+ aria-label="清除用户"
+ >
+ ×
+ </button>
+ ) : null}
+ {open && (query.trim() || options.length > 0) ? (
+ <div className="admin-user-search-dropdown">
+ {loading ? <div className="admin-user-search-empty">搜索中…</div> : null}
+ {!loading && options.length === 0 ? (
+ <div className="admin-user-search-empty">无匹配用户</div>
+ ) : null}
+ {options.map((u) => (
+ <button
+ key={u.id}
+ type="button"
+ className="admin-user-search-option"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => {
+ onChange(u.id, u);
+ setSelectedLabel(`${u.email} · ID:${formatAccountId(u.id)}`);
+ setQuery("");
+ setOpen(false);
+ }}
+ >
+ <span className="font-medium">{u.email}</span>
+ <span className="text-xs text-[var(--admin-muted)]">
+ ID:{formatAccountId(u.id)}
+ {u.nickname ? ` · ${u.nickname}` : ""}
+ </span>
+ </button>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/admin/src/components/admin/UserDetailDrawer.tsx b/admin/src/components/admin/UserDetailDrawer.tsx
new file mode 100644
index 0000000..24b98b4
--- /dev/null
+++ b/admin/src/components/admin/UserDetailDrawer.tsx
@@ -0,0 +1,221 @@
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import {
+ api,
+ type AdminLedger,
+ type AdminOrder,
+ type AdminUsageEvent,
+ type AdminUserRow,
+ type PageMeta,
+} from "@/api/client";
+import {
+ AdminDetailMeta,
+ AdminDetailSection,
+ AdminDetailTableWrap,
+} from "@/components/admin/AdminDetailLayout";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { AdminModal } from "@/components/admin/AdminModal";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { formatAccountId } from "@/lib/admin-account";
+import { fenToYuan } from "@/lib/utils";
+import { ledgerKindLabel, orderStatusLabel } from "@/lib/statusLabels";
+
+type ListRes<T> = { items: T[]; meta: PageMeta };
+
+type UserDetailDrawerProps = {
+ userId: number | null;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ initialUser?: AdminUserRow | null;
+};
+
+/** 用户只读明细:基本信息 + 订单/流水/用量聚合 */
+export function UserDetailDrawer({ userId, open, onOpenChange, initialUser }: UserDetailDrawerProps) {
+ const [user, setUser] = useState<AdminUserRow | null>(initialUser ?? null);
+ const [orders, setOrders] = useState<AdminOrder[]>([]);
+ const [ledger, setLedger] = useState<AdminLedger[]>([]);
+ const [usage, setUsage] = useState<AdminUsageEvent[]>([]);
+ const [loading, setLoading] = useState(false);
+
+ useEffect(() => {
+ if (!open || !userId) return;
+ setLoading(true);
+ void (async () => {
+ try {
+ const [userRes, orderRes, ledgerRes, usageRes] = await Promise.all([
+ initialUser?.id === userId
+ ? Promise.resolve({ items: [initialUser], meta: { page: 1, page_size: 1, total: 1 } })
+ : api<ListRes<AdminUserRow>>(`/api/admin/users?page=1&page_size=1&q=${userId}`),
+ api<ListRes<AdminOrder>>(`/api/admin/orders?page=1&page_size=8&user_id=${userId}`),
+ api<ListRes<AdminLedger>>(`/api/admin/ledger?page=1&page_size=8&user_id=${userId}`),
+ api<ListRes<AdminUsageEvent>>(`/api/admin/usage-events?page=1&page_size=20&user_id=${userId}`),
+ ]);
+ setUser(userRes.items[0] ?? initialUser ?? null);
+ setOrders(orderRes.items);
+ setLedger(ledgerRes.items);
+ setUsage(usageRes.items);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "加载用户明细失败");
+ } finally {
+ setLoading(false);
+ }
+ })();
+ }, [open, userId, initialUser]);
+
+ return (
+ <AdminModal
+ open={open}
+ onOpenChange={onOpenChange}
+ size="xl"
+ title="用户明细"
+ subtitle={
+ user
+ ? `${user.email} · ID:${formatAccountId(user.id)}`
+ : loading
+ ? "加载中…"
+ : "—"
+ }
+ bodyClassName="!pt-2"
+ >
+ {user ? (
+ <Tabs defaultValue="info" className="admin-detail-tabs">
+ <TabsList>
+ <TabsTrigger value="info">基本信息</TabsTrigger>
+ <TabsTrigger value="orders">最近订单</TabsTrigger>
+ <TabsTrigger value="ledger">钱包流水</TabsTrigger>
+ <TabsTrigger value="usage">用量摘要</TabsTrigger>
+ </TabsList>
+ <TabsContent value="info">
+ <AdminDetailSection>
+ <AdminDetailMeta
+ items={[
+ { label: "昵称", value: user.nickname || "—" },
+ { label: "手机", value: user.phone || "—" },
+ { label: "套餐", value: user.plan },
+ { label: "角色", value: user.role },
+ { label: "余额", value: `¥${fenToYuan(user.balance_fen)}` },
+ { label: "冻结", value: `¥${fenToYuan(user.frozen_fen)}` },
+ { label: "剩余额度", value: user.quota_left },
+ { label: "无限额度", value: user.billing_unlimited ? "是" : "否" },
+ {
+ label: "注册时间",
+ value: user.created_at ? new Date(user.created_at).toLocaleString() : "—",
+ full: true,
+ },
+ ]}
+ />
+ </AdminDetailSection>
+ </TabsContent>
+ <TabsContent value="orders">
+ <AdminDetailTableWrap>
+ <table>
+ <thead>
+ <tr>
+ <th>单号</th>
+ <th>金额</th>
+ <th>状态</th>
+ <th>时间</th>
+ </tr>
+ </thead>
+ <tbody>
+ {orders.length === 0 ? (
+ <tr>
+ <td colSpan={4} className="!text-center text-[var(--admin-muted)]">
+ 暂无订单
+ </td>
+ </tr>
+ ) : (
+ orders.map((o) => (
+ <tr key={o.id}>
+ <td className="font-mono text-xs">{o.out_trade_no}</td>
+ <td>¥{fenToYuan(o.amount_fen)}</td>
+ <td>{orderStatusLabel(o.status)}</td>
+ <td className="text-xs">{new Date(o.created_at).toLocaleString()}</td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </AdminDetailTableWrap>
+ </TabsContent>
+ <TabsContent value="ledger">
+ <AdminDetailTableWrap>
+ <table>
+ <thead>
+ <tr>
+ <th>类型</th>
+ <th>变动</th>
+ <th>余额后</th>
+ <th>备注</th>
+ </tr>
+ </thead>
+ <tbody>
+ {ledger.length === 0 ? (
+ <tr>
+ <td colSpan={4} className="!text-center text-[var(--admin-muted)]">
+ 暂无流水
+ </td>
+ </tr>
+ ) : (
+ ledger.map((row) => (
+ <tr key={row.id}>
+ <td>{ledgerKindLabel(row.kind)}</td>
+ <td>¥{fenToYuan(row.delta_fen)}</td>
+ <td>¥{fenToYuan(row.balance_after)}</td>
+ <td className="max-w-[200px] truncate text-xs">{row.note || "—"}</td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </AdminDetailTableWrap>
+ </TabsContent>
+ <TabsContent value="usage">
+ <AdminDetailTableWrap>
+ <table>
+ <thead>
+ <tr>
+ <th>时间</th>
+ <th>能力</th>
+ <th>扣费</th>
+ <th>成本</th>
+ <th>任务</th>
+ </tr>
+ </thead>
+ <tbody>
+ {usage.length === 0 ? (
+ <tr>
+ <td colSpan={5} className="!text-center text-[var(--admin-muted)]">
+ 暂无用量
+ </td>
+ </tr>
+ ) : (
+ usage.map((row) => (
+ <tr key={row.id}>
+ <td className="text-xs">
+ {row.created_at ? new Date(row.created_at).toLocaleString() : "—"}
+ </td>
+ <td>{row.capability || "—"}</td>
+ <td>¥{fenToYuan(row.charge_fen ?? 0)}</td>
+ <td>¥{fenToYuan(row.cost_fen ?? 0)}</td>
+ <td>
+ {row.task_run_id ? (
+ <AdminEntityLink kind="task" id={row.task_run_id} />
+ ) : (
+ "—"
+ )}
+ </td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </AdminDetailTableWrap>
+ </TabsContent>
+ </Tabs>
+ ) : loading ? (
+ <div className="py-10 text-center text-sm text-[var(--admin-muted)]">加载中…</div>
+ ) : null}
+ </AdminModal>
+ );
+}
diff --git a/admin/src/components/layout/AdminLayout.tsx b/admin/src/components/layout/AdminLayout.tsx
index 3be767a..a92cc63 100644
--- a/admin/src/components/layout/AdminLayout.tsx
+++ b/admin/src/components/layout/AdminLayout.tsx
@@ -12,10 +12,14 @@ import {
Film,
+ Image,
+
Layers,
LayoutDashboard,
+ ListVideo,
+
LogOut,
Maximize2,
@@ -48,6 +52,8 @@ type NavItem = {
end?: boolean;
+ matchPrefix?: boolean;
+
};
@@ -84,14 +90,30 @@ const navGroups: NavGroup[] = [
{ to: "/projects", label: "科普项目", icon: Clapperboard },
- { to: "/drama-projects", label: "漫剧项目", icon: Film },
-
{ to: "/works", label: "作品审核", icon: FileVideo },
],
},
+ {
+
+ label: "漫剧",
+
+ items: [
+
+ { to: "/drama-projects", label: "漫剧项目", icon: Film, matchPrefix: true },
+
+ { to: "/drama-assets", label: "资产库", icon: Image, matchPrefix: true },
+
+ { to: "/drama-episodes", label: "分集管理", icon: ListVideo, matchPrefix: true },
+
+ { to: "/drama-fragments", label: "分镜管理", icon: Layers, matchPrefix: true },
+
+ ],
+
+ },
+
{
label: "资源",
@@ -130,6 +152,12 @@ const titles: Record<string, string> = {
"/drama-projects": "漫剧项目",
+ "/drama-assets": "资产库",
+
+ "/drama-episodes": "分集管理",
+
+ "/drama-fragments": "分镜管理",
+
"/works": "作品审核",
"/templates": "模板管理",
@@ -142,6 +170,22 @@ const titles: Record<string, string> = {
+function resolveTitle(pathname: string): string {
+
+ if (pathname.startsWith("/drama-projects/")) return "漫剧项目详情";
+
+ if (pathname.startsWith("/drama-assets/")) return "资产详情";
+
+ if (pathname.startsWith("/drama-episodes/")) return "分集详情";
+
+ if (pathname.startsWith("/drama-fragments/")) return "分镜详情";
+
+ return titles[pathname] ?? "管理后台";
+
+}
+
+
+
// Admin shell: dark sidebar + glass top bar
export function AdminLayout() {
@@ -174,7 +218,7 @@ export function AdminLayout() {
- const title = titles[location.pathname] ?? "管理后台";
+ const title = resolveTitle(location.pathname);
const initial = (user?.nickname || user?.email || "A").slice(0, 1).toUpperCase();
@@ -220,9 +264,21 @@ export function AdminLayout() {
to={item.to}
- end={item.end}
+ end={item.end ?? !item.matchPrefix}
+
+ className={({ isActive }) =>
+
+ cn(
+
+ "admin-nav-item",
+
+ (isActive || (item.matchPrefix && location.pathname.startsWith(`${item.to}/`))) &&
+
+ "is-active",
+
+ )
- className={({ isActive }) => cn("admin-nav-item", isActive && "is-active")}
+ }
title={item.label}
diff --git a/admin/src/components/settings/ArkVolcMediaPanel.tsx b/admin/src/components/settings/ArkVolcMediaPanel.tsx
new file mode 100644
index 0000000..fbdda71
--- /dev/null
+++ b/admin/src/components/settings/ArkVolcMediaPanel.tsx
@@ -0,0 +1,238 @@
+import { useCallback, useMemo, useState } from "react";
+import { Loader2, RefreshCw } from "lucide-react";
+import { toast } from "sonner";
+import { api } from "@/api/client";
+import { LabeledControl, SettingsPanel } from "@/components/settings/SettingsPanel";
+import { SecretField } from "@/components/settings/SecretField";
+
+export const ARK_VOLC_CHANNEL_ID = "ark-volc-media";
+export const ARK_BASE = "https://ark.cn-beijing.volces.com/api/v3";
+export const DEFAULT_VIDEO_MODEL = "doubao-seedance-2-5-260628";
+export const DEFAULT_IMAGE_MODEL = "doubao-seedream-5-0-260128";
+
+type ArkModelOption = { id: string; label: string; capability: string };
+
+export type VolcMediaDraft = {
+ imageModel: string;
+ image45Model: string;
+ videoModel: string;
+};
+
+type ArkVolcMediaPanelProps = {
+ channelId: string;
+ hasApiKey: boolean;
+ apiKeyInput: string;
+ onApiKeyChange: (value: string) => void;
+ draft: VolcMediaDraft;
+ onDraftChange: (patch: Partial<VolcMediaDraft>) => void;
+};
+
+function modelOptions(
+ fetched: ArkModelOption[],
+ current: string,
+ capability: string,
+): ArkModelOption[] {
+ if (fetched.length > 0) return fetched;
+ if (!current) return [];
+ return [{ id: current, label: current, capability }];
+}
+
+/** 火山方舟生图/视频:固定渠道 + 手动拉取模型 */
+export function ArkVolcMediaPanel({
+ channelId,
+ hasApiKey,
+ apiKeyInput,
+ onApiKeyChange,
+ draft,
+ onDraftChange,
+}: ArkVolcMediaPanelProps) {
+ const [imageModels, setImageModels] = useState<ArkModelOption[]>([]);
+ const [videoModels, setVideoModels] = useState<ArkModelOption[]>([]);
+ const [fetching, setFetching] = useState(false);
+
+ const canFetch = useMemo(
+ () => hasApiKey || apiKeyInput.trim().length > 0,
+ [apiKeyInput, hasApiKey],
+ );
+
+ const fetchModels = useCallback(async () => {
+ if (!canFetch) {
+ toast.error("请先填写方舟 API Key");
+ return;
+ }
+ setFetching(true);
+ try {
+ const body: { capability: string; api_key?: string } = { capability: "image" };
+ const videoBody: { capability: string; api_key?: string } = { capability: "video" };
+ if (apiKeyInput.trim()) {
+ body.api_key = apiKeyInput.trim();
+ videoBody.api_key = apiKeyInput.trim();
+ }
+ const [imageRes, videoRes] = await Promise.all([
+ api<{ models: ArkModelOption[] }>("/api/admin/settings/ark/models", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ api<{ models: ArkModelOption[] }>("/api/admin/settings/ark/models", {
+ method: "POST",
+ body: JSON.stringify(videoBody),
+ }),
+ ]);
+ setImageModels(imageRes.models);
+ setVideoModels(videoRes.models);
+ toast.success(`已拉取 ${imageRes.models.length} 个生图、${videoRes.models.length} 个视频模型`);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "拉取模型失败");
+ } finally {
+ setFetching(false);
+ }
+ }, [apiKeyInput, canFetch]);
+
+ const imageOptions = modelOptions(imageModels, draft.imageModel, "image");
+ const videoOptions = modelOptions(videoModels, draft.videoModel, "video");
+
+ return (
+ <SettingsPanel
+ className="settings-panel--compact"
+ title="火山方舟(生图 / 视频)"
+ description={`固定 Base URL · ${ARK_BASE} · 渠道 ${channelId}`}
+ actions={
+ <button
+ type="button"
+ className="admin-quick-btn !inline-flex !w-auto items-center gap-1.5 px-3 py-1.5 text-xs"
+ disabled={fetching || !canFetch}
+ onClick={() => void fetchModels()}
+ >
+ {fetching ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
+ 拉取模型
+ </button>
+ }
+ >
+ <div className="settings-ark-compact">
+ <div className="settings-ark-key-row">
+ <SecretField
+ label="方舟 API Key"
+ value={apiKeyInput}
+ configured={hasApiKey}
+ onChange={onApiKeyChange}
+ onClear={() => onApiKeyChange("")}
+ />
+ {!canFetch ? (
+ <p className="settings-ark-hint">填写 Key 后可拉取上游模型列表;未拉取时仍可使用已保存的模型 ID。</p>
+ ) : imageModels.length === 0 && videoModels.length === 0 ? (
+ <p className="settings-ark-hint">尚未拉取模型,点击右上角「拉取模型」更新下拉选项。</p>
+ ) : null}
+ </div>
+
+ <div className="settings-field-grid settings-field-grid--3">
+ <LabeledControl label="默认生图(Seedream)">
+ <select
+ className="settings-select font-mono text-xs"
+ value={draft.imageModel}
+ onChange={(e) => onDraftChange({ imageModel: e.target.value })}
+ >
+ <option value="">— 请选择 —</option>
+ {imageOptions.map((item) => (
+ <option key={item.id} value={item.id}>
+ {item.label !== item.id ? `${item.label} · ${item.id}` : item.id}
+ </option>
+ ))}
+ </select>
+ </LabeledControl>
+ <LabeledControl label="Seedream 4.5(可选)">
+ <select
+ className="settings-select font-mono text-xs"
+ value={draft.image45Model}
+ onChange={(e) => onDraftChange({ image45Model: e.target.value })}
+ >
+ <option value="">— 不单独配置 —</option>
+ {imageOptions.map((item) => (
+ <option key={`45-${item.id}`} value={item.id}>
+ {item.label !== item.id ? `${item.label} · ${item.id}` : item.id}
+ </option>
+ ))}
+ </select>
+ </LabeledControl>
+ <LabeledControl label="默认视频(Seedance)" hint="视频生成依赖此模型">
+ <select
+ className="settings-select font-mono text-xs"
+ value={draft.videoModel}
+ onChange={(e) => onDraftChange({ videoModel: e.target.value })}
+ >
+ <option value="">— 请选择 —</option>
+ {videoOptions.map((item) => (
+ <option key={item.id} value={item.id}>
+ {item.label !== item.id ? `${item.label} · ${item.id}` : item.id}
+ </option>
+ ))}
+ </select>
+ </LabeledControl>
+ </div>
+ </div>
+ </SettingsPanel>
+ );
+}
+
+/** 从渠道 models 推断生图/视频草稿 */
+export function inferVolcMediaDraft(
+ models: string[],
+ inferCapability: (model: string, protocol: string) => "text" | "image" | "video" | "audio",
+): VolcMediaDraft {
+ const images = models.filter((m) => inferCapability(m, "ark") === "image");
+ const videos = models.filter((m) => inferCapability(m, "ark") === "video");
+ const imageModel = images.find((m) => m.includes("5-0") || m.includes("5.0")) ?? images[0] ?? DEFAULT_IMAGE_MODEL;
+ const image45Model = images.find((m) => m !== imageModel && (m.includes("4-5") || m.includes("4.5"))) ?? "";
+ const videoModel = videos[0] ?? DEFAULT_VIDEO_MODEL;
+ return { imageModel, image45Model, videoModel };
+}
+
+/** 合并为单一方舟渠道,移除多余 ARK 渠道 */
+export function consolidateArkVolcChannels<
+ T extends { id: string; protocol: string; models: string[]; name: string; base_url: string; api_format: string; enabled: boolean; sort_order: number },
+>(channels: T[], volcDraft: VolcMediaDraft, existing?: T): { channels: T[]; volcChannelId: string } {
+ const models = [...new Set([volcDraft.imageModel, volcDraft.image45Model, volcDraft.videoModel].filter(Boolean))];
+ const otherArk = channels.filter((c) => c.protocol === "ark");
+ const base = existing ?? otherArk[0];
+ const volcChannel = {
+ ...(base as T),
+ id: ARK_VOLC_CHANNEL_ID,
+ name: "火山方舟(生图/视频)",
+ base_url: ARK_BASE,
+ api_format: "ark",
+ protocol: "ark",
+ models,
+ enabled: true,
+ sort_order: base?.sort_order ?? 1,
+ } as T;
+ const rest = channels.filter((c) => c.protocol !== "ark" || c.id === ARK_VOLC_CHANNEL_ID);
+ const withoutDup = rest.filter((c) => c.id !== ARK_VOLC_CHANNEL_ID);
+ return { channels: [volcChannel, ...withoutDup], volcChannelId: ARK_VOLC_CHANNEL_ID };
+}
+
+export function resolveDefaultModelsFromUpstream(
+ settings: {
+ logical_models: Array<{
+ id: string;
+ capability: string;
+ bindings: Array<{ upstream_model: string }>;
+ }>;
+ default_models: { image_model: string; video_model: string; text_model: string; audio_model: string };
+ },
+ draft: VolcMediaDraft,
+) {
+ const findLogical = (capability: string, upstream: string) =>
+ settings.logical_models.find(
+ (m) => m.capability === capability && m.bindings.some((b) => b.upstream_model === upstream),
+ )?.id ?? "";
+
+ const next = { ...settings.default_models };
+ if (draft.imageModel) {
+ const id = findLogical("image", draft.imageModel);
+ if (id) next.image_model = id;
+ }
+ if (draft.videoModel) {
+ const id = findLogical("video", draft.videoModel);
+ if (id) next.video_model = id;
+ }
+ return next;
+}
diff --git a/admin/src/components/settings/OssSettingsPanel.tsx b/admin/src/components/settings/OssSettingsPanel.tsx
index c92e589..6b7275f 100644
--- a/admin/src/components/settings/OssSettingsPanel.tsx
+++ b/admin/src/components/settings/OssSettingsPanel.tsx
@@ -1,6 +1,6 @@
import { useMemo, useState } from "react";
-import { Cloud, Loader2, Save } from "lucide-react";
-import { LabeledControl, SectionTitle, SettingsPanel, SettingsSurface } from "@/components/settings/SettingsPanel";
+import { Cloud } from "lucide-react";
+import { LabeledControl, SectionTitle, SettingsLoading, SettingsPanel, SettingsSurface, SettingsTabShell } from "@/components/settings/SettingsPanel";
import { SecretField } from "@/components/settings/SecretField";
import { Switch } from "@/components/ui/switch";
import { useAdminModelSettings } from "@/hooks/useAdminModelSettings";
@@ -64,35 +64,14 @@ export function OssSettingsPanel() {
}
if (loading || !form) {
- return (
- <div className="admin-panel flex items-center justify-center py-16 text-[#909399]">
- <Loader2 className="mr-2 h-5 w-5 animate-spin" />
- 加载中…
- </div>
- );
+ return <SettingsLoading />;
}
return (
- <div className="space-y-5">
- <div className="flex flex-wrap items-end justify-between gap-3">
- <div>
- <h2 className="text-xl font-semibold text-[#303133]">存储与 CDN</h2>
- <p className="mt-1 text-sm text-[#909399]">阿里云 OSS 成片上传;TOS / CDN 为可选扩展</p>
- </div>
- <button
- type="button"
- className="admin-quick-btn !inline-flex !w-auto items-center gap-2 px-4 py-2.5"
- disabled={saving}
- onClick={() => void handleSave()}
- >
- {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
- 保存
- </button>
- </div>
-
+ <SettingsTabShell onSave={() => void handleSave()} saving={saving}>
<SettingsSurface>
<SectionTitle icon={<Cloud className="h-4 w-4" />} title="OSS 状态" />
- <div className="mt-4 flex flex-wrap items-center gap-3">
+ <div className="mt-2 flex flex-wrap items-center gap-2">
<span className={cn("admin-status-pill", ossReady ? "is-done" : form.oss_enabled ? "is-warn" : "")}>
{form.oss_enabled ? (ossReady ? "OSS 已就绪" : "已启用但凭证不完整") : "OSS 未启用"}
</span>
@@ -100,16 +79,15 @@ export function OssSettingsPanel() {
</div>
</SettingsSurface>
- <SettingsPanel title="阿里云 OSS" description="生成文件先落本地 /static,再异步上传 OSS 并回填 URL。">
- <SettingsSurface>
- <div className="settings-toggle-row">
- <div>
- <strong>启用 OSS</strong>
- <span>关闭后仅使用本地静态目录</span>
- </div>
- <Switch checked={form.oss_enabled} onCheckedChange={(v) => patchField("oss_enabled", v)} />
+ <SettingsPanel title="阿里云 OSS" description="生成文件先落本地,再异步上传 OSS">
+ <div className="settings-toggle-row">
+ <div>
+ <strong>启用 OSS</strong>
+ <span>关闭后仅使用本地静态目录</span>
</div>
- <div className="settings-field-grid mt-4">
+ <Switch checked={form.oss_enabled} onCheckedChange={(v) => patchField("oss_enabled", v)} />
+ </div>
+ <div className="settings-field-grid mt-2">
<LabeledControl label="Endpoint">
<input
className="settings-input"
@@ -177,19 +155,17 @@ export function OssSettingsPanel() {
}}
/>
</div>
- <div className="settings-toggle-row mt-4">
- <div>
- <strong>异步上传</strong>
- <span>先返回本地 URL,后台队列上传 OSS</span>
- </div>
- <Switch checked={form.oss_upload_async} onCheckedChange={(v) => patchField("oss_upload_async", v)} />
+ <div className="settings-toggle-row mt-2">
+ <div>
+ <strong>异步上传</strong>
+ <span>先返回本地 URL,后台队列上传 OSS</span>
</div>
- </SettingsSurface>
+ <Switch checked={form.oss_upload_async} onCheckedChange={(v) => patchField("oss_upload_async", v)} />
+ </div>
</SettingsPanel>
- <SettingsPanel title="火山 TOS(可选)" description="历史存储方案,新项目可只配 OSS。">
- <SettingsSurface>
- <div className="settings-field-grid">
+ <SettingsPanel title="火山 TOS(可选)" description="历史存储方案,新项目可只配 OSS">
+ <div className="settings-field-grid">
<LabeledControl label="Endpoint">
<input
className="settings-input"
@@ -231,10 +207,9 @@ export function OssSettingsPanel() {
setTosSecretInput("");
setClearTosSecret(true);
}}
- />
- </div>
- </SettingsSurface>
+ />
+ </div>
</SettingsPanel>
- </div>
+ </SettingsTabShell>
);
}
diff --git a/admin/src/components/settings/PaymentSettingsPanel.tsx b/admin/src/components/settings/PaymentSettingsPanel.tsx
index 8e57055..750c320 100644
--- a/admin/src/components/settings/PaymentSettingsPanel.tsx
+++ b/admin/src/components/settings/PaymentSettingsPanel.tsx
@@ -1,6 +1,6 @@
import { useMemo, useState } from "react";
-import { CreditCard, Loader2, Save, Wallet } from "lucide-react";
-import { LabeledControl, SectionTitle, SettingsPanel, SettingsSurface } from "@/components/settings/SettingsPanel";
+import { BarChart3, Bell, CreditCard, Mail, Wallet } from "lucide-react";
+import { LabeledControl, SectionTitle, SettingsLoading, SettingsPanel, SettingsSurface, SettingsTabShell } from "@/components/settings/SettingsPanel";
import { SecretField } from "@/components/settings/SecretField";
import { Switch } from "@/components/ui/switch";
import { useAdminModelSettings } from "@/hooks/useAdminModelSettings";
@@ -11,6 +11,12 @@ export function PaymentSettingsPanel() {
const { form, loading, saving, patchField, save } = useAdminModelSettings();
const [epayKeyInput, setEpayKeyInput] = useState("");
const [clearEpayKey, setClearEpayKey] = useState(false);
+ const [volcAkInput, setVolcAkInput] = useState("");
+ const [volcSkInput, setVolcSkInput] = useState("");
+ const [clearVolcAk, setClearVolcAk] = useState(false);
+ const [clearVolcSk, setClearVolcSk] = useState(false);
+ const [smtpPasswordInput, setSmtpPasswordInput] = useState("");
+ const [clearSmtpPassword, setClearSmtpPassword] = useState(false);
const epayReady = useMemo(() => {
if (!form) return false;
@@ -43,43 +49,48 @@ export function PaymentSettingsPanel() {
billing_signup_grant_fen: form.billing_signup_grant_fen,
quota_enabled: form.quota_enabled,
new_user_quota: form.new_user_quota,
+ volc_access_key_id: volcAkInput.trim() || undefined,
+ volc_secret_access_key: volcSkInput.trim() || undefined,
+ clear_volc_access_key_id: clearVolcAk,
+ clear_volc_secret_access_key: clearVolcSk,
+ volc_ark_region: form.volc_ark_region,
+ volc_ark_usage_enabled: form.volc_ark_usage_enabled,
+ billing_user_alert_enabled: form.billing_user_alert_enabled,
+ billing_user_alert_interval_fen: form.billing_user_alert_interval_fen,
+ billing_admin_cost_alert_enabled: form.billing_admin_cost_alert_enabled,
+ billing_admin_cost_alert_threshold_fen: form.billing_admin_cost_alert_threshold_fen,
+ billing_admin_cost_alert_emails: form.billing_admin_cost_alert_emails,
+ billing_admin_cost_alert_period: form.billing_admin_cost_alert_period,
+ smtp_enabled: form.smtp_enabled,
+ smtp_host: form.smtp_host,
+ smtp_port: form.smtp_port,
+ smtp_user: form.smtp_user,
+ smtp_password: smtpPasswordInput.trim() || undefined,
+ clear_smtp_password: clearSmtpPassword,
+ smtp_from: form.smtp_from,
+ smtp_use_tls: form.smtp_use_tls,
},
"支付与计费已保存",
);
setEpayKeyInput("");
setClearEpayKey(false);
+ setVolcAkInput("");
+ setVolcSkInput("");
+ setClearVolcAk(false);
+ setClearVolcSk(false);
+ setSmtpPasswordInput("");
+ setClearSmtpPassword(false);
}
if (loading || !form) {
- return (
- <div className="admin-panel flex items-center justify-center py-16 text-[#909399]">
- <Loader2 className="mr-2 h-5 w-5 animate-spin" />
- 加载中…
- </div>
- );
+ return <SettingsLoading />;
}
return (
- <div className="space-y-5">
- <div className="flex flex-wrap items-end justify-between gap-3">
- <div>
- <h2 className="text-xl font-semibold text-[#303133]">支付与计费</h2>
- <p className="mt-1 text-sm text-[#909399]">易支付充值、Token 扣费与注册赠送</p>
- </div>
- <button
- type="button"
- className="admin-quick-btn !inline-flex !w-auto items-center gap-2 px-4 py-2.5"
- disabled={saving}
- onClick={() => void handleSave()}
- >
- {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
- 保存
- </button>
- </div>
-
+ <SettingsTabShell onSave={() => void handleSave()} saving={saving}>
<SettingsSurface>
<SectionTitle icon={<CreditCard className="h-4 w-4" />} title="支付就绪" />
- <div className="mt-4 flex flex-wrap gap-3">
+ <div className="mt-2 flex flex-wrap gap-2">
<span className={cn("admin-status-pill", epayReady ? "is-done" : "is-warn")}>
{epayReady ? "易支付已配置" : "易支付未完整配置"}
</span>
@@ -89,9 +100,8 @@ export function PaymentSettingsPanel() {
</div>
</SettingsSurface>
- <SettingsPanel title="易支付 Epay" description="生产环境回调请用 /epay/notify,勿含 /api/ 前缀。">
- <SettingsSurface>
- <div className="settings-field-grid">
+ <SettingsPanel title="易支付 Epay" description="生产回调请用 /epay/notify,勿含 /api/">
+ <div className="settings-field-grid">
<LabeledControl label="网关地址">
<input
className="settings-input"
@@ -132,20 +142,18 @@ export function PaymentSettingsPanel() {
/>
</LabeledControl>
</div>
- </SettingsSurface>
</SettingsPanel>
- <SettingsPanel title="Token 计费" description="按上游成本 × markup 扣费;未返回 usage 时用估算 token。">
- <SettingsSurface>
- <SectionTitle icon={<Wallet className="h-4 w-4" />} title="开关与系数" />
- <div className="settings-toggle-row mt-4">
+ <SettingsPanel title="Token 计费" description="按上游成本 × markup 扣费">
+ <SectionTitle icon={<Wallet className="h-4 w-4" />} title="开关与系数" />
+ <div className="settings-toggle-row">
<div>
<strong>启用 Token 计费</strong>
<span>关闭后生成不扣余额(管理员可单独豁免)</span>
</div>
<Switch checked={form.billing_enabled} onCheckedChange={(v) => patchField("billing_enabled", v)} />
</div>
- <div className="settings-field-grid mt-4">
+ <div className="settings-field-grid mt-2">
<LabeledControl label="加价系数 markup">
<input
className="settings-input"
@@ -178,7 +186,7 @@ export function PaymentSettingsPanel() {
</div>
<SectionTitle icon={<Wallet className="h-4 w-4" />} title="单价(元 / 百万 token)" />
- <div className="settings-field-grid mt-4">
+ <div className="settings-field-grid mt-2">
<LabeledControl label="LLM">
<input
className="settings-input"
@@ -227,7 +235,7 @@ export function PaymentSettingsPanel() {
</div>
<SectionTitle icon={<Wallet className="h-4 w-4" />} title="估算 token(缺 usage 时)" />
- <div className="settings-field-grid mt-4">
+ <div className="settings-field-grid mt-2">
<LabeledControl label="LLM 估算">
<input
className="settings-input"
@@ -262,14 +270,14 @@ export function PaymentSettingsPanel() {
</LabeledControl>
</div>
- <div className="settings-toggle-row mt-4">
+ <div className="settings-toggle-row mt-2">
<div>
<strong>旧版次数配额(quota_enabled)</strong>
<span>与 Token 计费并存时以 billing_enabled 为准</span>
</div>
<Switch checked={form.quota_enabled} onCheckedChange={(v) => patchField("quota_enabled", v)} />
</div>
- <div className="settings-field-grid mt-4">
+ <div className="settings-field-grid mt-2">
<LabeledControl label="新用户默认次数">
<input
className="settings-input"
@@ -280,8 +288,186 @@ export function PaymentSettingsPanel() {
/>
</LabeledControl>
</div>
- </SettingsSurface>
</SettingsPanel>
- </div>
+
+ <SettingsPanel title="额度告警" description="用户消费提醒与平台费用邮件告警">
+ <SectionTitle icon={<Bell className="h-4 w-4" />} title="用户消费提醒" />
+ <div className="settings-toggle-row">
+ <div>
+ <strong>启用用户弹窗提醒</strong>
+ <span>用户累计扣费每达间隔档位弹出一次提示</span>
+ </div>
+ <Switch
+ checked={form.billing_user_alert_enabled}
+ onCheckedChange={(v) => patchField("billing_user_alert_enabled", v)}
+ />
+ </div>
+ <div className="settings-field-grid mt-2">
+ <LabeledControl label="提醒间隔(分)" hint="1000 = ¥10;100000 = ¥1000">
+ <input
+ className="settings-input"
+ type="number"
+ min={1}
+ value={form.billing_user_alert_interval_fen}
+ onChange={(e) => patchField("billing_user_alert_interval_fen", Number(e.target.value))}
+ />
+ </LabeledControl>
+ </div>
+
+ <SectionTitle icon={<Mail className="h-4 w-4" />} title="平台费用邮件告警" />
+ <div className="settings-toggle-row">
+ <div>
+ <strong>启用管理员邮件告警</strong>
+ <span>按上游 cost 汇总,达到阈值后发送邮件</span>
+ </div>
+ <Switch
+ checked={form.billing_admin_cost_alert_enabled}
+ onCheckedChange={(v) => patchField("billing_admin_cost_alert_enabled", v)}
+ />
+ </div>
+ <div className="settings-field-grid mt-2">
+ <LabeledControl label="告警阈值(分)" hint="例:500000 = ¥5000">
+ <input
+ className="settings-input"
+ type="number"
+ min={0}
+ value={form.billing_admin_cost_alert_threshold_fen}
+ onChange={(e) =>
+ patchField("billing_admin_cost_alert_threshold_fen", Number(e.target.value))
+ }
+ />
+ </LabeledControl>
+ <LabeledControl label="统计周期">
+ <select
+ className="settings-input"
+ value={form.billing_admin_cost_alert_period}
+ onChange={(e) => patchField("billing_admin_cost_alert_period", e.target.value)}
+ >
+ <option value="daily">每日</option>
+ <option value="monthly">每月</option>
+ <option value="all_time">累计</option>
+ </select>
+ </LabeledControl>
+ <LabeledControl label="收件邮箱" hint="逗号分隔;留空则发给全部管理员">
+ <input
+ className="settings-input"
+ value={form.billing_admin_cost_alert_emails}
+ onChange={(e) => patchField("billing_admin_cost_alert_emails", e.target.value)}
+ />
+ </LabeledControl>
+ </div>
+ {(form.billing_admin_cost_alert_last_period_key || form.billing_admin_cost_alert_last_level > 0) && (
+ <p className="mt-2 text-xs text-[#909399]">
+ 上次告警:周期 {form.billing_admin_cost_alert_last_period_key || "—"},档位{" "}
+ {form.billing_admin_cost_alert_last_level}
+ </p>
+ )}
+
+ <SectionTitle icon={<Mail className="h-4 w-4" />} title="SMTP 发信" />
+ <div className="settings-toggle-row">
+ <div>
+ <strong>启用 SMTP</strong>
+ <span>邮件告警依赖 SMTP 配置</span>
+ </div>
+ <Switch checked={form.smtp_enabled} onCheckedChange={(v) => patchField("smtp_enabled", v)} />
+ </div>
+ <div className="settings-field-grid mt-2">
+ <LabeledControl label="SMTP 主机">
+ <input
+ className="settings-input"
+ placeholder="smtp.example.com"
+ value={form.smtp_host}
+ onChange={(e) => patchField("smtp_host", e.target.value)}
+ />
+ </LabeledControl>
+ <LabeledControl label="端口">
+ <input
+ className="settings-input"
+ type="number"
+ min={1}
+ value={form.smtp_port}
+ onChange={(e) => patchField("smtp_port", Number(e.target.value))}
+ />
+ </LabeledControl>
+ <LabeledControl label="发件人地址">
+ <input
+ className="settings-input"
+ placeholder="[email protected]"
+ value={form.smtp_from}
+ onChange={(e) => patchField("smtp_from", e.target.value)}
+ />
+ </LabeledControl>
+ <LabeledControl label="SMTP 用户名">
+ <input
+ className="settings-input"
+ value={form.smtp_user}
+ onChange={(e) => patchField("smtp_user", e.target.value)}
+ />
+ </LabeledControl>
+ <SecretField
+ label="SMTP 密码"
+ value={smtpPasswordInput}
+ configured={form.has_smtp_password && !clearSmtpPassword}
+ onChange={setSmtpPasswordInput}
+ onClear={() => {
+ setSmtpPasswordInput("");
+ setClearSmtpPassword(true);
+ }}
+ />
+ <LabeledControl label="TLS">
+ <div className="settings-toggle-row !mt-0">
+ <Switch
+ checked={form.smtp_use_tls}
+ onCheckedChange={(v) => patchField("smtp_use_tls", v)}
+ />
+ </div>
+ </LabeledControl>
+ </div>
+ </SettingsPanel>
+
+ <SettingsPanel title="上游成本监控" description="火山 GetInferenceUsage,与方舟 API Key 分离">
+ <SectionTitle icon={<BarChart3 className="h-4 w-4" />} title="火山 Access Key" />
+ <div className="settings-toggle-row">
+ <div>
+ <strong>启用官方用量拉取</strong>
+ <span>关闭后仪表盘仅展示本地 seedance 成本</span>
+ </div>
+ <Switch
+ checked={form.volc_ark_usage_enabled}
+ onCheckedChange={(v) => patchField("volc_ark_usage_enabled", v)}
+ />
+ </div>
+ <div className="settings-field-grid mt-2">
+ <SecretField
+ label="Access Key ID"
+ value={volcAkInput}
+ configured={form.has_volc_access_key_id && !clearVolcAk}
+ onChange={setVolcAkInput}
+ onClear={() => {
+ setVolcAkInput("");
+ setClearVolcAk(true);
+ }}
+ />
+ <SecretField
+ label="Secret Access Key"
+ value={volcSkInput}
+ configured={form.has_volc_secret_access_key && !clearVolcSk}
+ onChange={setVolcSkInput}
+ onClear={() => {
+ setVolcSkInput("");
+ setClearVolcSk(true);
+ }}
+ />
+ <LabeledControl label="区域" hint="默认 cn-beijing">
+ <input
+ className="settings-input"
+ value={form.volc_ark_region}
+ onChange={(e) => patchField("volc_ark_region", e.target.value)}
+ />
+ </LabeledControl>
+ </div>
+ </SettingsPanel>
+ </SettingsTabShell>
);
}
diff --git a/admin/src/components/settings/RoutingSettingsPanel.tsx b/admin/src/components/settings/RoutingSettingsPanel.tsx
index c46d544..1f78cd6 100644
--- a/admin/src/components/settings/RoutingSettingsPanel.tsx
+++ b/admin/src/components/settings/RoutingSettingsPanel.tsx
@@ -1,8 +1,19 @@
import { useCallback, useEffect, useMemo, useState } from "react";
-import { Clapperboard, Image as ImageIcon, Loader2, Mic, Plus, Save, Trash2, Type } from "lucide-react";
+import { Mic, Plus, Trash2, Type } from "lucide-react";
import { toast } from "sonner";
import { api, type AdminRoutingSettings } from "@/api/client";
-import { LabeledControl, SectionTitle, SettingsPanel, SettingsSurface } from "@/components/settings/SettingsPanel";
+import {
+ ArkVolcMediaPanel,
+ ARK_BASE,
+ ARK_VOLC_CHANNEL_ID,
+ consolidateArkVolcChannels,
+ DEFAULT_IMAGE_MODEL,
+ DEFAULT_VIDEO_MODEL,
+ inferVolcMediaDraft,
+ resolveDefaultModelsFromUpstream,
+ type VolcMediaDraft,
+} from "@/components/settings/ArkVolcMediaPanel";
+import { LabeledControl, SectionTitle, SettingsLoading, SettingsPanel, SettingsSurface, SettingsTabShell } from "@/components/settings/SettingsPanel";
import { cn } from "@/lib/utils";
type ChannelDraft = AdminRoutingSettings["system_channels"][number] & {
@@ -18,10 +29,6 @@ const CAPABILITY_LABELS: Record<Capability, string> = {
audio: "语音",
};
-const ARK_BASE = "https://ark.cn-beijing.volces.com/api/v3";
-const DEFAULT_VIDEO_MODEL = "doubao-seedance-2-5-260628";
-const DEFAULT_IMAGE_MODEL = "doubao-seedream-5-0-260128";
-
// 与后端 infer_model_capability 对齐,用于渠道能力徽标
function inferCapability(model: string, protocol: string): Capability {
const mid = (model || "").trim().toLowerCase().replace(/\s+/g, "");
@@ -56,11 +63,20 @@ export function RoutingSettingsPanel() {
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [selectedChannelId, setSelectedChannelId] = useState("");
+ const [volcDraft, setVolcDraft] = useState<VolcMediaDraft>({
+ imageModel: "",
+ image45Model: "",
+ videoModel: "",
+ });
const load = useCallback(async () => {
setLoading(true);
try {
const res = await api<AdminRoutingSettings>("/api/admin/settings/routing");
+ const arkChannel =
+ res.system_channels.find((c) => c.id === ARK_VOLC_CHANNEL_ID) ??
+ res.system_channels.find((c) => c.protocol === "ark");
+ setVolcDraft(inferVolcMediaDraft(arkChannel?.models ?? [], inferCapability));
setData(res);
setSelectedChannelId((prev) => prev || res.system_channels[0]?.id || "");
setApiKeyInputs({});
@@ -84,8 +100,15 @@ export function RoutingSettingsPanel() {
[apiKeyInputs, data],
);
- const selectedChannel = channels.find((item) => item.id === selectedChannelId) ?? channels[0];
- const hasVideoChannel = channels.some((ch) => channelCapabilities(ch).includes("video"));
+ const otherChannels = useMemo(
+ () => channels.filter((item) => item.id !== ARK_VOLC_CHANNEL_ID),
+ [channels],
+ );
+ const selectedChannel =
+ otherChannels.find((item) => item.id === selectedChannelId) ?? otherChannels[0];
+ const arkVolcChannel =
+ channels.find((c) => c.id === ARK_VOLC_CHANNEL_ID) ?? channels.find((c) => c.protocol === "ark");
+ const hasVideoChannel = Boolean(volcDraft.videoModel || arkVolcChannel);
const videoLogicalModels = (data?.logical_models ?? []).filter((m) => m.capability === "video");
function updateChannel(channelId: string, patch: Partial<AdminRoutingSettings["system_channels"][number]>) {
@@ -216,35 +239,73 @@ export function RoutingSettingsPanel() {
if (!data) return;
setSaving(true);
try {
- const nextDefaults = { ...data.default_models };
- // 保存时若未设默认视频模型,且渠道含视频能力,尽量落到 seedance / 首个视频逻辑模型
- if (!nextDefaults.video_model) {
- const preferred =
- data.logical_models.find((m) => m.capability === "video" && m.id === "seedance-2.5") ??
- data.logical_models.find((m) => m.capability === "video");
- if (preferred) nextDefaults.video_model = preferred.id;
- }
+ const existingArk = data.system_channels.find((c) => c.id === ARK_VOLC_CHANNEL_ID) ?? arkVolcChannel;
+ const { channels: mergedChannels } = consolidateArkVolcChannels(
+ data.system_channels,
+ volcDraft,
+ existingArk,
+ );
const res = await api<{ settings: AdminRoutingSettings }>("/api/admin/settings/routing", {
method: "PATCH",
body: JSON.stringify({
- system_channels: data.system_channels.map((channel) => ({
+ system_channels: mergedChannels.map((channel) => ({
id: channel.id,
name: channel.name,
base_url: channel.base_url,
api_key: apiKeyInputs[channel.id]?.trim() || undefined,
api_format: channel.api_format,
protocol: channel.protocol,
- models: channel.models,
+ models: channel.id === ARK_VOLC_CHANNEL_ID
+ ? [...new Set([volcDraft.imageModel, volcDraft.image45Model, volcDraft.videoModel].filter(Boolean))]
+ : channel.models,
enabled: channel.enabled,
sort_order: channel.sort_order,
})),
logical_models: data.logical_models,
- default_models: nextDefaults,
+ default_models: data.default_models,
}),
});
- setData(res.settings);
+
+ let nextDefaults = resolveDefaultModelsFromUpstream(res.settings, volcDraft);
+ if (!nextDefaults.video_model) {
+ const preferred =
+ res.settings.logical_models.find((m) => m.capability === "video" && m.id === "seedance-2.5") ??
+ res.settings.logical_models.find((m) => m.capability === "video");
+ if (preferred) nextDefaults = { ...nextDefaults, video_model: preferred.id };
+ }
+
+ const arkKey = apiKeyInputs[ARK_VOLC_CHANNEL_ID]?.trim();
+ if (
+ nextDefaults.image_model !== res.settings.default_models.image_model ||
+ nextDefaults.video_model !== res.settings.default_models.video_model
+ ) {
+ const res2 = await api<{ settings: AdminRoutingSettings }>("/api/admin/settings/routing", {
+ method: "PATCH",
+ body: JSON.stringify({
+ default_models: nextDefaults,
+ }),
+ });
+ setData(res2.settings);
+ } else {
+ setData(res.settings);
+ }
+
+ if (arkKey || volcDraft.imageModel || volcDraft.videoModel) {
+ await api("/api/admin/settings/models", {
+ method: "PATCH",
+ body: JSON.stringify({
+ ark_api_key: arkKey || undefined,
+ ark_base_url: ARK_BASE,
+ model_image: volcDraft.imageModel || undefined,
+ model_image_45: volcDraft.image45Model || undefined,
+ model_video: volcDraft.videoModel || undefined,
+ }),
+ });
+ }
+
setApiKeyInputs({});
+ await load();
toast.success("路由配置已保存");
} catch (err) {
toast.error(err instanceof Error ? err.message : "保存失败");
@@ -254,38 +315,15 @@ export function RoutingSettingsPanel() {
}
if (loading && !data) {
- return (
- <div className="admin-panel flex items-center justify-center py-16 text-[#909399]">
- <Loader2 className="mr-2 h-5 w-5 animate-spin" />
- 加载路由配置…
- </div>
- );
+ return <SettingsLoading label="加载路由配置…" />;
}
return (
- <div className="space-y-5">
- <div className="flex flex-wrap items-end justify-between gap-3">
- <div>
- <h2 className="text-xl font-semibold text-[#303133]">模型路由</h2>
- <p className="mt-1 text-sm text-[#909399]">
- 上游渠道(含视频)+ 逻辑模型绑定 + 默认模型。视频须用 ARK 协议与 Seedance 模型 ID。
- </p>
- </div>
- <button
- type="button"
- className="admin-quick-btn !inline-flex !w-auto items-center gap-2 px-4 py-2.5"
- disabled={saving}
- onClick={() => void handleSave()}
- >
- {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
- 保存路由
- </button>
- </div>
-
+ <SettingsTabShell onSave={() => void handleSave()} saving={saving} saveLabel="保存路由">
{(data?.validation_errors.length ?? 0) > 0 ? (
<SettingsSurface className="border-[#fde2e2] bg-[#fef0f0]">
- <div className="text-sm font-medium text-[#f56c6c]">配置校验</div>
- <ul className="mt-2 space-y-1 text-xs text-[#f56c6c]">
+ <div className="text-xs font-medium text-[#f56c6c]">配置校验</div>
+ <ul className="mt-1 space-y-0.5 text-xs text-[#f56c6c]">
{data?.validation_errors.map((item) => (
<li key={item}>· {item}</li>
))}
@@ -293,48 +331,27 @@ export function RoutingSettingsPanel() {
</SettingsSurface>
) : null}
+ <ArkVolcMediaPanel
+ channelId={ARK_VOLC_CHANNEL_ID}
+ hasApiKey={Boolean(arkVolcChannel?.has_api_key)}
+ apiKeyInput={apiKeyInputs[ARK_VOLC_CHANNEL_ID] ?? ""}
+ onApiKeyChange={(value) => setApiKeyInputs((prev) => ({ ...prev, [ARK_VOLC_CHANNEL_ID]: value }))}
+ draft={volcDraft}
+ onDraftChange={(patch) => setVolcDraft((prev) => ({ ...prev, ...patch }))}
+ />
+
{!hasVideoChannel ? (
<SettingsSurface className="border-[#faecd8] bg-[#fdf6ec]">
- <div className="flex flex-wrap items-center justify-between gap-3">
- <div>
- <div className="text-sm font-medium text-[#e6a23c]">尚未配置视频渠道</div>
- <div className="mt-1 text-xs text-[#909399]">
- 点击「添加视频渠道」,填入火山方舟 API Key,保存后即可生成 Seedance 视频。
- </div>
- </div>
- <button
- type="button"
- className="admin-quick-btn !inline-flex !w-auto items-center gap-2 px-3 py-2"
- onClick={() => addPreset("video")}
- >
- <Clapperboard className="h-4 w-4" />
- 添加视频渠道
- </button>
- </div>
+ <div className="text-xs font-medium text-[#e6a23c]">请在上方选择默认视频模型并保存</div>
</SettingsSurface>
) : null}
<SettingsPanel
- title="上游渠道"
- description="物理网关:Base URL、协议、上游模型列表。视频请用「添加视频渠道」或协议选 ARK。"
+ className="settings-panel--compact"
+ title="其他上游渠道"
+ description="文本 LLM、语音 TTS 等"
>
- <div className="mb-3 flex flex-wrap gap-2">
- <button
- type="button"
- className="admin-quick-btn !inline-flex !w-auto !flex-row items-center gap-1.5 px-3 py-1.5 text-xs"
- onClick={() => addPreset("video")}
- >
- <Clapperboard className="h-3.5 w-3.5" />
- 添加视频渠道
- </button>
- <button
- type="button"
- className="admin-quick-btn !inline-flex !w-auto !flex-row items-center gap-1.5 px-3 py-1.5 text-xs"
- onClick={() => addPreset("image")}
- >
- <ImageIcon className="h-3.5 w-3.5" />
- 添加生图渠道
- </button>
+ <div className="mb-2 flex flex-wrap gap-1.5">
<button
type="button"
className="admin-quick-btn !inline-flex !w-auto !flex-row items-center gap-1.5 px-3 py-1.5 text-xs"
@@ -361,16 +378,16 @@ export function RoutingSettingsPanel() {
</button>
</div>
- <div className="grid gap-4 xl:grid-cols-[260px_minmax(0,1fr)]">
- <div className="space-y-2">
- {channels.map((channel) => {
+ <div className="grid gap-2 xl:grid-cols-[200px_minmax(0,1fr)]">
+ <div className="space-y-1.5">
+ {otherChannels.map((channel) => {
const caps = channelCapabilities(channel);
return (
<button
key={channel.id}
type="button"
className={cn(
- "w-full rounded-lg border px-3 py-2 text-left text-sm transition-colors",
+ "w-full rounded-lg border px-2.5 py-1.5 text-left text-sm transition-colors",
selectedChannel?.id === channel.id
? "border-[#67c23a] bg-[#f0f9eb]"
: "border-[#ebeef5] bg-white hover:border-[#dcdfe6]",
@@ -495,11 +512,12 @@ export function RoutingSettingsPanel() {
/>
</LabeledControl>
<LabeledControl
+ className="settings-field-span-full"
label="上游模型(每行一个)"
hint="视频示例:doubao-seedance-2-5-260628"
>
<textarea
- className="settings-input min-h-[120px] py-2 font-mono text-xs"
+ className="settings-input min-h-[96px] py-2 font-mono text-xs"
value={selectedChannel.models.join("\n")}
onChange={(e) =>
updateChannel(selectedChannel.id, {
@@ -517,8 +535,12 @@ export function RoutingSettingsPanel() {
</div>
</SettingsPanel>
- <SettingsPanel title="逻辑模型" description="保存渠道后自动 sync;视频能力会出现在下方「视频」分组。">
- <div className="space-y-4">
+ <SettingsPanel
+ className="settings-panel--compact"
+ title="逻辑模型"
+ description="保存渠道后自动同步"
+ >
+ <div className="space-y-3">
{(["video", "image", "text", "audio"] as const).map((cap) => {
const models = (data?.logical_models ?? []).filter((m) => m.capability === cap);
if (models.length === 0 && cap !== "video") return null;
@@ -579,8 +601,8 @@ export function RoutingSettingsPanel() {
</div>
</SettingsPanel>
- <SettingsPanel title="默认模型" description="各能力默认逻辑模型 ID。视频未就绪时下拉为空。">
- <div className="settings-field-grid">
+ <SettingsPanel className="settings-panel--compact" title="默认模型" description="各能力默认逻辑模型">
+ <div className="settings-field-grid settings-field-grid--4">
{(["text_model", "image_model", "video_model", "audio_model"] as const).map((key) => {
const cap = key.replace("_model", "") as Capability;
const options = (data?.logical_models ?? []).filter((model) => model.capability === cap);
@@ -617,6 +639,6 @@ export function RoutingSettingsPanel() {
})}
</div>
</SettingsPanel>
- </div>
+ </SettingsTabShell>
);
}
diff --git a/admin/src/components/settings/RuntimeSettingsPanel.tsx b/admin/src/components/settings/RuntimeSettingsPanel.tsx
index f6d1155..aa83d4b 100644
--- a/admin/src/components/settings/RuntimeSettingsPanel.tsx
+++ b/admin/src/components/settings/RuntimeSettingsPanel.tsx
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useMemo, useState } from "react";
-import { Activity, CircleGauge, Loader2, Save, SlidersHorizontal, Sparkles } from "lucide-react";
+import { Activity, CircleGauge, SlidersHorizontal, Sparkles } from "lucide-react";
import { toast } from "sonner";
import { api, type AdminModelSettings } from "@/api/client";
-import { LabeledControl, SectionTitle, SettingsPanel, SettingsSurface } from "@/components/settings/SettingsPanel";
+import { LabeledControl, SectionTitle, SettingsLoading, SettingsPanel, SettingsSurface, SettingsTabShell } from "@/components/settings/SettingsPanel";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";
@@ -70,40 +70,19 @@ export function RuntimeSettingsPanel() {
}
if (loading || !form) {
- return (
- <div className="admin-panel flex items-center justify-center py-16 text-[#909399]">
- <Loader2 className="mr-2 h-5 w-5 animate-spin" />
- 加载中…
- </div>
- );
+ return <SettingsLoading />;
}
return (
- <div className="space-y-5">
- <div className="flex flex-wrap items-end justify-between gap-3">
- <div>
- <h2 className="text-xl font-semibold text-[#303133]">运行参数</h2>
- <p className="mt-1 text-sm text-[#909399]">质量默认值、并发上限与 Mock 开关</p>
- </div>
- <button
- type="button"
- className="admin-quick-btn !inline-flex !w-auto items-center gap-2 px-4 py-2.5"
- disabled={saving}
- onClick={() => void handleSave()}
- >
- {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
- 保存
- </button>
- </div>
-
+ <SettingsTabShell onSave={() => void handleSave()} saving={saving}>
<SettingsSurface>
<SectionTitle icon={<Sparkles className="h-4 w-4" />} title="路由就绪状态" />
- <div className="mt-4 flex flex-wrap items-center justify-between gap-2">
+ <div className="mt-2 flex flex-wrap items-center justify-between gap-2">
<span className={cn("admin-status-pill", readinessReady ? "is-done" : "is-warn")}>
{readinessReady ? "四类能力已就绪" : "请在「模型路由」补全渠道"}
</span>
</div>
- <div className="settings-readiness mt-4">
+ <div className="settings-readiness mt-2">
{(form.readiness ?? []).map((item) => (
<div key={item.capability} className={cn("settings-readiness-card", item.ready && "is-ready")}>
<div className="flex items-center justify-between gap-2">
@@ -119,10 +98,9 @@ export function RuntimeSettingsPanel() {
</div>
</SettingsSurface>
- <SettingsPanel title="质量与默认值" description="生图尺寸、视频清晰度、Seedance 时长与轮询参数。">
- <SettingsSurface>
- <SectionTitle icon={<SlidersHorizontal className="h-4 w-4" />} title="生成默认值" />
- <div className="settings-field-grid">
+ <SettingsPanel title="质量与默认值" description="生图尺寸、视频清晰度、Seedance 时长与轮询">
+ <SectionTitle icon={<SlidersHorizontal className="h-4 w-4" />} title="生成默认值" />
+ <div className="settings-field-grid">
<LabeledControl label="默认生图尺寸">
<input className="settings-input" value={form.ark_image_size} onChange={(e) => patchField("ark_image_size", e.target.value)} />
</LabeledControl>
@@ -145,13 +123,11 @@ export function RuntimeSettingsPanel() {
<input className="settings-input" type="number" value={form.ark_video_poll_timeout} onChange={(e) => patchField("ark_video_poll_timeout", Number(e.target.value))} />
</LabeledControl>
</div>
- </SettingsSurface>
</SettingsPanel>
- <SettingsPanel title="并发与限制" description="管线并发、任务平台槽位与漫剧分镜上限。">
- <SettingsSurface>
- <SectionTitle icon={<CircleGauge className="h-4 w-4" />} title="并发上限" />
- <div className="settings-field-grid">
+ <SettingsPanel title="并发与限制" description="管线并发、任务槽位与漫剧分镜上限">
+ <SectionTitle icon={<CircleGauge className="h-4 w-4" />} title="并发上限" />
+ <div className="settings-field-grid">
<LabeledControl label="生图并发">
<input className="settings-input" type="number" min={1} value={form.pipeline_image_concurrency} onChange={(e) => patchField("pipeline_image_concurrency", Number(e.target.value))} />
</LabeledControl>
@@ -177,20 +153,19 @@ export function RuntimeSettingsPanel() {
<input className="settings-input" type="number" min={1} value={form.drama_fragment_max_attempts} onChange={(e) => patchField("drama_fragment_max_attempts", Number(e.target.value))} />
</LabeledControl>
</div>
- <div className="settings-toggle-row mt-4">
- <div>
- <strong>ARK Mock 模式</strong>
- <span>开发环境模拟生成,不调用真实上游</span>
- </div>
- <Switch checked={form.ark_mock} onCheckedChange={(v) => patchField("ark_mock", v)} />
+ <div className="settings-toggle-row mt-2">
+ <div>
+ <strong>ARK Mock 模式</strong>
+ <span>开发环境模拟生成,不调用真实上游</span>
</div>
- </SettingsSurface>
+ <Switch checked={form.ark_mock} onCheckedChange={(v) => patchField("ark_mock", v)} />
+ </div>
</SettingsPanel>
- <SettingsPanel title="运行时" description="Worker 槽位与 Selector 轮询(NIO:注册项不占 Worker)。">
- <div className="flex flex-col gap-2 text-sm text-[#606266]">
+ <SettingsPanel title="运行时" description="Worker 槽位与 Selector 轮询">
+ <div className="flex flex-col gap-1.5 text-sm text-[#606266]">
<div className="flex items-center gap-2">
- <Activity className="h-4 w-4 text-[#67c23a]" />
+ <Activity className="h-3.5 w-3.5 text-[#67c23a]" />
Worker 槽位 {form.task_runtime_max_concurrency} · 单用户 {form.task_user_max_concurrency}
</div>
<div className="text-xs text-[#909399]">
@@ -198,6 +173,6 @@ export function RuntimeSettingsPanel() {
</div>
</div>
</SettingsPanel>
- </div>
+ </SettingsTabShell>
);
}
diff --git a/admin/src/components/settings/SecretField.tsx b/admin/src/components/settings/SecretField.tsx
index d58fff5..ee01ef8 100644
--- a/admin/src/components/settings/SecretField.tsx
+++ b/admin/src/components/settings/SecretField.tsx
@@ -1,5 +1,4 @@
import { LabeledControl } from "@/components/settings/SettingsPanel";
-import { cn } from "@/lib/utils";
type SecretFieldProps = {
label: string;
@@ -24,27 +23,25 @@ export function SecretField({
return (
<LabeledControl
label={label}
- hint={hint ?? (configured ? "已配置;留空保存则不修改,可点清除后保存" : undefined)}
+ hint={hint ?? (configured ? "已配置;留空保存则不修改" : undefined)}
>
- <div className="flex flex-col gap-2">
- <div className="flex gap-2">
+ <div className="admin-secret-field">
+ <div className="admin-secret-field-row">
<input
type="password"
- className="settings-input flex-1"
+ className="settings-input is-secret"
placeholder={placeholder ?? (configured ? "留空则不修改" : "填写密钥")}
value={value}
onChange={(e) => onChange(e.target.value)}
autoComplete="new-password"
/>
{configured && onClear ? (
- <button type="button" className="admin-quick-btn shrink-0 px-3" onClick={onClear}>
+ <button type="button" className="admin-quick-btn shrink-0 px-3 text-xs" onClick={onClear}>
清除
</button>
) : null}
</div>
- {configured ? (
- <span className={cn("text-xs font-medium text-[#67c23a]")}>● 已配置</span>
- ) : null}
+ {configured ? <span className="admin-secret-status">已配置</span> : null}
</div>
</LabeledControl>
);
diff --git a/admin/src/components/settings/SettingsPanel.tsx b/admin/src/components/settings/SettingsPanel.tsx
index e7394a3..9c36155 100644
--- a/admin/src/components/settings/SettingsPanel.tsx
+++ b/admin/src/components/settings/SettingsPanel.tsx
@@ -1,20 +1,23 @@
import type { ReactNode } from "react";
+import { Loader2, Save } from "lucide-react";
+import { cn } from "@/lib/utils";
type PanelProps = {
title: string;
- description: string;
+ description?: string;
actions?: ReactNode;
children: ReactNode;
+ className?: string;
};
-// VOZEB 风格配置面板容器
-export function SettingsPanel({ title, description, actions, children }: PanelProps) {
+// 配置分区面板:标题 + 内容
+export function SettingsPanel({ title, description, actions, children, className }: PanelProps) {
return (
- <section className="settings-panel">
+ <section className={cn("settings-panel", className)}>
<div className="settings-panel-header">
<div className="min-w-0">
<h3 className="settings-panel-title">{title}</h3>
- <p className="settings-panel-desc">{description}</p>
+ {description ? <p className="settings-panel-desc">{description}</p> : null}
</div>
{actions ? <div className="settings-panel-actions">{actions}</div> : null}
</div>
@@ -23,6 +26,45 @@ export function SettingsPanel({ title, description, actions, children }: PanelPr
);
}
+type SettingsTabShellProps = {
+ children: ReactNode;
+ onSave?: () => void | Promise<void>;
+ saving?: boolean;
+ saveLabel?: string;
+};
+
+// Tab 内容区:右上角统一保存按钮
+export function SettingsTabShell({ children, onSave, saving, saveLabel = "保存" }: SettingsTabShellProps) {
+ return (
+ <div className="settings-tab-shell">
+ {onSave ? (
+ <div className="settings-tab-toolbar">
+ <button
+ type="button"
+ className="admin-quick-btn settings-save-btn"
+ disabled={saving}
+ onClick={() => void onSave()}
+ >
+ {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}
+ {saveLabel}
+ </button>
+ </div>
+ ) : null}
+ <div className="settings-tab-body">{children}</div>
+ </div>
+ );
+}
+
+// 加载占位
+export function SettingsLoading({ label = "加载中…" }: { label?: string }) {
+ return (
+ <div className="settings-loading">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ {label}
+ </div>
+ );
+}
+
// 带图标的区块标题
export function SectionTitle({ icon, title }: { icon: ReactNode; title: string }) {
return (
@@ -34,9 +76,19 @@ export function SectionTitle({ icon, title }: { icon: ReactNode; title: string }
}
// 表单标签 + 控件
-export function LabeledControl({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) {
+export function LabeledControl({
+ label,
+ hint,
+ children,
+ className,
+}: {
+ label: string;
+ hint?: string;
+ children: ReactNode;
+ className?: string;
+}) {
return (
- <label className="settings-field">
+ <label className={cn("settings-field", className)}>
<span className="settings-field-label">{label}</span>
{children}
{hint ? <span className="settings-field-hint">{hint}</span> : null}
@@ -44,7 +96,7 @@ export function LabeledControl({ label, hint, children }: { label: string; hint?
);
}
-// 内嵌子面板(VOZEB settingsPanelSurfaceClass 风格)
+// 内嵌子面板(浅灰底,用于状态条或独立分组)
export function SettingsSurface({ children, className = "" }: { children: ReactNode; className?: string }) {
- return <div className={`settings-surface ${className}`.trim()}>{children}</div>;
+ return <div className={cn("settings-surface", className)}>{children}</div>;
}
diff --git a/admin/src/components/settings/SiteSettingsPanel.tsx b/admin/src/components/settings/SiteSettingsPanel.tsx
index 9f2b313..fda8bee 100644
--- a/admin/src/components/settings/SiteSettingsPanel.tsx
+++ b/admin/src/components/settings/SiteSettingsPanel.tsx
@@ -1,5 +1,5 @@
-import { Globe, Loader2, Save, Wrench } from "lucide-react";
-import { LabeledControl, SectionTitle, SettingsPanel, SettingsSurface } from "@/components/settings/SettingsPanel";
+import { Globe, Wrench } from "lucide-react";
+import { LabeledControl, SectionTitle, SettingsLoading, SettingsPanel, SettingsTabShell } from "@/components/settings/SettingsPanel";
import { useAdminModelSettings } from "@/hooks/useAdminModelSettings";
// 站点 URL 与本地工具路径
@@ -19,73 +19,48 @@ export function SiteSettingsPanel() {
}
if (loading || !form) {
- return (
- <div className="admin-panel flex items-center justify-center py-16 text-[#909399]">
- <Loader2 className="mr-2 h-5 w-5 animate-spin" />
- 加载中…
- </div>
- );
+ return <SettingsLoading />;
}
return (
- <div className="space-y-5">
- <div className="flex flex-wrap items-end justify-between gap-3">
- <div>
- <h2 className="text-xl font-semibold text-[#303133]">站点与工具</h2>
- <p className="mt-1 text-sm text-[#909399]">公网基址、回调拼接与 FFmpeg 可执行路径</p>
+ <SettingsTabShell onSave={() => void handleSave()} saving={saving}>
+ <SettingsPanel title="公网地址" description="支付回调、分享链接与 OSS 回填">
+ <SectionTitle icon={<Globe className="h-4 w-4" />} title="PUBLIC_BASE_URL" />
+ <div className="settings-field-grid">
+ <LabeledControl label="后端公网基址" hint="例:https://api.example.com">
+ <input
+ className="settings-input"
+ value={form.public_base_url}
+ onChange={(e) => patchField("public_base_url", e.target.value)}
+ />
+ </LabeledControl>
</div>
- <button
- type="button"
- className="admin-quick-btn !inline-flex !w-auto items-center gap-2 px-4 py-2.5"
- disabled={saving}
- onClick={() => void handleSave()}
- >
- {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
- 保存
- </button>
- </div>
-
- <SettingsPanel title="公网地址" description="用于支付回调、分享链接与 OSS 回填后的绝对 URL。">
- <SettingsSurface>
- <SectionTitle icon={<Globe className="h-4 w-4" />} title="PUBLIC_BASE_URL" />
- <div className="settings-field-grid mt-4">
- <LabeledControl label="后端公网基址" hint="例:https://api.example.com 或 http://127.0.0.1:8000">
- <input
- className="settings-input"
- value={form.public_base_url}
- onChange={(e) => patchField("public_base_url", e.target.value)}
- />
- </LabeledControl>
- </div>
- <p className="mt-3 text-xs leading-relaxed text-[#909399]">
- 数据库、Redis、SECRET_KEY 等基础设施仍通过服务器环境变量配置,不在此页修改。
- </p>
- </SettingsSurface>
+ <p className="mt-2 text-xs leading-relaxed text-[#909399]">
+ 数据库、Redis、SECRET_KEY 等基础设施仍通过服务器环境变量配置,不在此页修改。
+ </p>
</SettingsPanel>
- <SettingsPanel title="媒体工具" description="合成与抽帧依赖本机 ffmpeg / ffprobe。">
- <SettingsSurface>
- <SectionTitle icon={<Wrench className="h-4 w-4" />} title="FFmpeg" />
- <div className="settings-field-grid mt-4">
- <LabeledControl label="ffmpeg 路径">
- <input
- className="settings-input"
- placeholder="ffmpeg"
- value={form.ffmpeg_path}
- onChange={(e) => patchField("ffmpeg_path", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="ffprobe 路径">
- <input
- className="settings-input"
- placeholder="ffprobe"
- value={form.ffprobe_path}
- onChange={(e) => patchField("ffprobe_path", e.target.value)}
- />
- </LabeledControl>
- </div>
- </SettingsSurface>
+ <SettingsPanel title="媒体工具" description="合成与抽帧依赖本机 ffmpeg / ffprobe">
+ <SectionTitle icon={<Wrench className="h-4 w-4" />} title="FFmpeg" />
+ <div className="settings-field-grid">
+ <LabeledControl label="ffmpeg 路径">
+ <input
+ className="settings-input"
+ placeholder="ffmpeg"
+ value={form.ffmpeg_path}
+ onChange={(e) => patchField("ffmpeg_path", e.target.value)}
+ />
+ </LabeledControl>
+ <LabeledControl label="ffprobe 路径">
+ <input
+ className="settings-input"
+ placeholder="ffprobe"
+ value={form.ffprobe_path}
+ onChange={(e) => patchField("ffprobe_path", e.target.value)}
+ />
+ </LabeledControl>
+ </div>
</SettingsPanel>
- </div>
+ </SettingsTabShell>
);
}
diff --git a/admin/src/components/tasks/TaskDetailDialog.tsx b/admin/src/components/tasks/TaskDetailDialog.tsx
index e223c0b..49630de 100644
--- a/admin/src/components/tasks/TaskDetailDialog.tsx
+++ b/admin/src/components/tasks/TaskDetailDialog.tsx
@@ -329,14 +329,15 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta
<th>billing_key</th>
<th>模型</th>
<th>Tokens</th>
- <th>费用</th>
- <th>估算</th>
+ <th>扣费</th>
+ <th>上游成本</th>
+ <th>计费依据</th>
</tr>
</thead>
<tbody>
{(task.usage_lines?.length ?? 0) === 0 ? (
<tr>
- <td colSpan={7} className="text-center text-sm text-[#909399]">
+ <td colSpan={8} className="text-center text-sm text-[#909399]">
暂无用量记录
</td>
</tr>
@@ -349,7 +350,8 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta
<td className="max-w-[120px] truncate text-xs">{line.model || "—"}</td>
<td>{line.total_tokens ?? 0}</td>
<td>¥{fenToYuan(line.charge_fen ?? 0)}</td>
- <td>{line.estimated ? "估算" : "实测"}</td>
+ <td>¥{fenToYuan(line.cost_fen ?? 0)}</td>
+ <td>{line.billing_basis_label ?? (line.estimated ? "估算" : "实测")}</td>
</tr>
))
)}
diff --git a/admin/src/components/templates/TemplateEditorDialog.tsx b/admin/src/components/templates/TemplateEditorDialog.tsx
index 9a231cf..14d1948 100644
--- a/admin/src/components/templates/TemplateEditorDialog.tsx
+++ b/admin/src/components/templates/TemplateEditorDialog.tsx
@@ -273,6 +273,31 @@ export function TemplateEditorDialog({
</div>
<Switch checked={form.is_premium} onCheckedChange={(v) => onChange({ is_premium: v })} />
</div>
+ {editing ? (
+ <details className="mt-4 rounded-lg border p-3">
+ <summary className="cursor-pointer text-sm font-medium">高级配置(只读)</summary>
+ <div className="mt-3 space-y-3">
+ <div>
+ <div className="mb-1 text-xs text-[var(--admin-muted)]">seedance_config</div>
+ <pre className="admin-json-readonly">
+ {JSON.stringify(editing.seedance_config ?? {}, null, 2)}
+ </pre>
+ </div>
+ <div>
+ <div className="mb-1 text-xs text-[var(--admin-muted)]">audio_config</div>
+ <pre className="admin-json-readonly">
+ {JSON.stringify(editing.audio_config ?? {}, null, 2)}
+ </pre>
+ </div>
+ <div>
+ <div className="mb-1 text-xs text-[var(--admin-muted)]">subtitle_config</div>
+ <pre className="admin-json-readonly">
+ {JSON.stringify(editing.subtitle_config ?? {}, null, 2)}
+ </pre>
+ </div>
+ </div>
+ </details>
+ ) : null}
</div>
) : null}
</div>
diff --git a/admin/src/components/ui/badge.tsx b/admin/src/components/ui/badge.tsx
index fb0a9a2..b43b15f 100644
--- a/admin/src/components/ui/badge.tsx
+++ b/admin/src/components/ui/badge.tsx
@@ -10,18 +10,18 @@ export function Badge({
variant?: "default" | "secondary" | "outline" | "destructive" | "success" | "warning" | "info";
}) {
const variants = {
- default: "border-transparent bg-[#303133] text-white",
- secondary: "border-transparent bg-[#f4f4f5] text-[#606266]",
- outline: "border-[#dcdfe6] bg-white text-[#606266]",
- destructive: "border-transparent bg-[#fef0f0] text-[#f56c6c]",
- success: "border-transparent bg-[#f0f9eb] text-[#67c23a]",
- warning: "border-transparent bg-[#fdf6ec] text-[#e6a23c]",
- info: "border-transparent bg-[#ecf5ff] text-[#409eff]",
+ default: "border-transparent bg-[var(--admin-text)] text-white",
+ secondary: "border-transparent bg-[#f1f5f9] text-[var(--admin-muted)]",
+ outline: "border-[var(--admin-border)] bg-white text-[var(--admin-muted)]",
+ destructive: "border-transparent bg-[#fef2f2] text-[#dc2626]",
+ success: "border-transparent bg-[var(--admin-accent-soft)] text-[var(--admin-forest)]",
+ warning: "border-transparent bg-[#fff7ed] text-[#c2410c]",
+ info: "border-transparent bg-[var(--admin-tag-bg)] text-[var(--admin-tag-text)]",
};
return (
<span
className={cn(
- "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium tracking-wide",
+ "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold tracking-wide",
variants[variant],
className,
)}
diff --git a/admin/src/components/ui/button.tsx b/admin/src/components/ui/button.tsx
index 805d5f3..b7c678c 100644
--- a/admin/src/components/ui/button.tsx
+++ b/admin/src/components/ui/button.tsx
@@ -4,25 +4,25 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
- "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-sm font-medium transition-all duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#c2e7b0] focus-visible:ring-offset-1 disabled:pointer-events-none disabled:opacity-45 active:scale-[0.98]",
+ "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-[10px] text-sm font-semibold transition-all duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--admin-accent-ring)] focus-visible:ring-offset-1 disabled:pointer-events-none disabled:opacity-45 active:scale-[0.98]",
{
variants: {
variant: {
default:
- "bg-[#67c23a] text-white shadow-sm shadow-[#67c23a]/25 hover:bg-[#85ce61]",
+ "bg-[var(--admin-forest)] text-white shadow-[0_4px_12px_rgba(31,92,72,0.22)] hover:bg-[var(--admin-forest-deep)]",
secondary:
- "bg-[#f4f4f5] text-[#606266] hover:bg-[#e9e9eb] hover:text-[#303133]",
+ "border border-[var(--admin-border)] bg-white text-[var(--admin-text)] hover:border-[#c5d4cc] hover:bg-[#f8fafc]",
outline:
- "border border-[#dcdfe6] bg-white text-[#606266] hover:border-[#c2e7b0] hover:text-[#67c23a]",
- ghost: "text-[#606266] hover:bg-[#f5f7fa] hover:text-[#303133]",
+ "border border-[var(--admin-border)] bg-white text-[var(--admin-muted)] hover:border-[rgba(61,154,114,0.35)] hover:text-[var(--admin-forest)]",
+ ghost: "text-[var(--admin-muted)] hover:bg-[var(--admin-accent-soft)] hover:text-[var(--admin-forest)]",
destructive:
- "bg-[#f56c6c] text-white shadow-sm shadow-[#f56c6c]/20 hover:bg-[#f78989]",
- soft: "bg-[#f0f9eb] text-[#67c23a] hover:bg-[#e1f3d8]",
+ "bg-[#ef4444] text-white shadow-sm hover:bg-[#dc2626]",
+ soft: "bg-[var(--admin-accent-soft)] text-[var(--admin-forest)] hover:bg-[rgba(61,154,114,0.18)]",
},
size: {
default: "h-9 px-4",
- sm: "h-8 rounded-md px-3 text-xs",
- lg: "h-10 rounded-lg px-6",
+ sm: "h-8 rounded-[9px] px-3 text-xs",
+ lg: "h-10 rounded-[10px] px-6",
icon: "h-9 w-9",
},
},
diff --git a/admin/src/components/ui/dialog.tsx b/admin/src/components/ui/dialog.tsx
index fbe40ff..b7faa52 100644
--- a/admin/src/components/ui/dialog.tsx
+++ b/admin/src/components/ui/dialog.tsx
@@ -17,13 +17,13 @@ export function DialogContent({
<DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-[#0f172a]/40 backdrop-blur-[2px] data-[state=open]:animate-in data-[state=closed]:animate-out" />
<DialogPrimitive.Content
className={cn(
- "fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-5 border border-[#ebeef5] bg-white p-6 shadow-[0_20px_50px_rgba(15,23,42,0.16)] sm:rounded-2xl",
+ "fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-5 bg-white p-6 shadow-[0_20px_50px_rgba(15,23,42,0.16)] sm:rounded-2xl max-h-[min(90vh,calc(100vh-32px))]",
className,
)}
{...props}
>
{children}
- <DialogPrimitive.Close className="absolute right-4 top-4 rounded-lg p-1.5 text-[#909399] transition-colors hover:bg-[#f5f7fa] hover:text-[#303133]">
+ <DialogPrimitive.Close className="absolute right-4 top-4 z-10 rounded-lg p-1.5 text-[#909399] transition-colors hover:bg-[#f5f7fa] hover:text-[#303133]">
<X className="h-4 w-4" />
</DialogPrimitive.Close>
</DialogPrimitive.Content>
diff --git a/admin/src/components/ui/input.tsx b/admin/src/components/ui/input.tsx
index 7f80d06..cf81f1d 100644
--- a/admin/src/components/ui/input.tsx
+++ b/admin/src/components/ui/input.tsx
@@ -1,15 +1,12 @@
import * as React from "react";
import { cn } from "@/lib/utils";
-// Text input with soft focus ring
+// 管理端统一文本输入
export function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
- className={cn(
- "flex h-9 w-full rounded-lg border border-[#dcdfe6] bg-white px-3 text-sm text-[#303133] shadow-[0_1px_2px_rgba(16,24,40,0.03)] transition-all placeholder:text-[#c0c4cc] hover:border-[#c0c4cc] focus-visible:border-[#67c23a] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#e1f3d8] disabled:cursor-not-allowed disabled:bg-[#f5f7fa] disabled:opacity-60",
- className,
- )}
+ className={cn("admin-control", className)}
{...props}
/>
);
diff --git a/admin/src/components/ui/page.tsx b/admin/src/components/ui/page.tsx
index 3160c07..41422d9 100644
--- a/admin/src/components/ui/page.tsx
+++ b/admin/src/components/ui/page.tsx
@@ -45,7 +45,11 @@ type ToolbarProps = {
className?: string;
};
-// 筛选 / 搜索工具条
+// 筛选 / 搜索工具条(与 AdminFilterBar 一致)
export function Toolbar({ children, className }: ToolbarProps) {
- return <div className={cn("admin-filter-bar", className)}>{children}</div>;
+ return (
+ <div className={cn("admin-filter-bar", className)}>
+ <div className="admin-filter-bar-main">{children}</div>
+ </div>
+ );
}
diff --git a/admin/src/components/ui/select.tsx b/admin/src/components/ui/select.tsx
index 8ef64b5..e4d49f8 100644
--- a/admin/src/components/ui/select.tsx
+++ b/admin/src/components/ui/select.tsx
@@ -1,32 +1,12 @@
import * as React from "react";
import { cn } from "@/lib/utils";
-// Native select with admin chrome
+// 管理端统一下拉选择
export function Select({ className, ...props }: React.ComponentProps<"select">) {
- return (
- <select
- className={cn(
- "flex h-9 w-full appearance-none rounded-lg border border-[#dcdfe6] bg-white bg-[length:12px] bg-[right_12px_center] bg-no-repeat px-3 pr-8 text-sm text-[#303133] shadow-[0_1px_2px_rgba(16,24,40,0.03)] transition-all hover:border-[#c0c4cc] focus-visible:border-[#67c23a] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#e1f3d8] disabled:cursor-not-allowed disabled:bg-[#f5f7fa] disabled:opacity-60",
- className,
- )}
- style={{
- backgroundImage:
- "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%909399' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E\")",
- }}
- {...props}
- />
- );
+ return <select className={cn("admin-control admin-select", className)} {...props} />;
}
-// Multi-line text area
+// 管理端统一多行文本
export function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
- return (
- <textarea
- className={cn(
- "flex min-h-[96px] w-full rounded-lg border border-[#dcdfe6] bg-white px-3 py-2.5 text-sm text-[#303133] shadow-[0_1px_2px_rgba(16,24,40,0.03)] transition-all placeholder:text-[#c0c4cc] hover:border-[#c0c4cc] focus-visible:border-[#67c23a] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#e1f3d8] disabled:cursor-not-allowed disabled:bg-[#f5f7fa] disabled:opacity-60",
- className,
- )}
- {...props}
- />
- );
+ return <textarea className={cn("admin-control admin-textarea", className)} {...props} />;
}
diff --git a/admin/src/components/ui/switch.tsx b/admin/src/components/ui/switch.tsx
index 6127551..62eb91d 100644
--- a/admin/src/components/ui/switch.tsx
+++ b/admin/src/components/ui/switch.tsx
@@ -2,17 +2,17 @@ import * as React from "react";
import * as SwitchPrimitive from "@radix-ui/react-switch";
import { cn } from "@/lib/utils";
-// Soft green toggle switch
+// 管理端开关:与主题森林绿一致
export function Switch({ className, ...props }: React.ComponentProps<typeof SwitchPrimitive.Root>) {
return (
<SwitchPrimitive.Root
className={cn(
- "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent bg-[#dcdfe6] transition-colors data-[state=checked]:bg-[#67c23a] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#e1f3d8]",
+ "peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent bg-[#e2e8f0] transition-colors data-[state=checked]:bg-[var(--admin-forest)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--admin-accent-ring)]",
className,
)}
{...props}
>
- <SwitchPrimitive.Thumb className="pointer-events-none block h-4 w-4 rounded-full bg-white shadow-md ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0" />
+ <SwitchPrimitive.Thumb className="pointer-events-none block h-5 w-5 rounded-full bg-white shadow-sm ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0" />
</SwitchPrimitive.Root>
);
}
diff --git a/admin/src/components/ui/table.tsx b/admin/src/components/ui/table.tsx
index 794f561..5fd9c1b 100644
--- a/admin/src/components/ui/table.tsx
+++ b/admin/src/components/ui/table.tsx
@@ -4,14 +4,14 @@ import { cn } from "@/lib/utils";
// Table primitives tuned for admin lists
export function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
- <div className="relative w-full overflow-auto rounded-xl border border-[#ebeef5] bg-white">
+ <div className="admin-data-table">
<table className={cn("w-full caption-bottom text-sm", className)} {...props} />
</div>
);
}
export function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
- return <thead className={cn("bg-[#fafbfc] [&_tr]:border-b [&_tr]:border-[#ebeef5]", className)} {...props} />;
+ return <thead className={cn("admin-data-table-head [&_tr]:border-0", className)} {...props} />;
}
export function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
@@ -22,7 +22,7 @@ export function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
className={cn(
- "border-b border-[#f2f3f5] transition-colors hover:bg-[#f8fafc] data-[state=selected]:bg-[#f0f9eb]",
+ "border-b border-[var(--admin-border)] transition-colors hover:bg-[#f8fbfd] data-[state=selected]:bg-[var(--admin-accent-soft)]",
className,
)}
{...props}
@@ -34,7 +34,7 @@ export function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
className={cn(
- "h-11 px-4 text-left align-middle text-xs font-medium tracking-wide text-[#909399]",
+ "h-11 px-4 text-left align-middle text-xs font-semibold tracking-wide text-[var(--admin-table-head-text)]",
className,
)}
{...props}
@@ -43,5 +43,5 @@ export function TableHead({ className, ...props }: React.ComponentProps<"th">) {
}
export function TableCell({ className, ...props }: React.ComponentProps<"td">) {
- return <td className={cn("px-4 py-3.5 align-middle text-[#303133]", className)} {...props} />;
+ return <td className={cn("px-4 py-3.5 align-middle text-[var(--admin-text)]", className)} {...props} />;
}
diff --git a/admin/src/components/ui/tabs.tsx b/admin/src/components/ui/tabs.tsx
index b637a08..a65854e 100644
--- a/admin/src/components/ui/tabs.tsx
+++ b/admin/src/components/ui/tabs.tsx
@@ -8,7 +8,7 @@ export function TabsList({ className, ...props }: React.ComponentProps<typeof Ta
return (
<TabsPrimitive.List
className={cn(
- "inline-flex h-10 items-center gap-1 rounded-xl border border-[#ebeef5] bg-[#f5f7fa] p-1 text-[#909399]",
+ "inline-flex h-10 items-center gap-1 rounded-[10px] bg-[#f1f5f9] p-1 text-[var(--admin-muted)]",
className,
)}
{...props}
@@ -20,7 +20,7 @@ export function TabsTrigger({ className, ...props }: React.ComponentProps<typeof
return (
<TabsPrimitive.Trigger
className={cn(
- "inline-flex items-center justify-center whitespace-nowrap rounded-lg px-3.5 py-1.5 text-sm font-medium transition-all data-[state=active]:bg-white data-[state=active]:text-[#303133] data-[state=active]:shadow-sm hover:text-[#606266]",
+ "inline-flex items-center justify-center whitespace-nowrap rounded-[8px] px-3.5 py-1.5 text-sm font-semibold transition-all data-[state=active]:bg-white data-[state=active]:text-[var(--admin-forest)] data-[state=active]:shadow-sm hover:text-[var(--admin-text)] focus-visible:outline-none",
className,
)}
{...props}
diff --git a/admin/src/hooks/useAdminDetailQuery.ts b/admin/src/hooks/useAdminDetailQuery.ts
new file mode 100644
index 0000000..bc1ea80
--- /dev/null
+++ b/admin/src/hooks/useAdminDetailQuery.ts
@@ -0,0 +1,41 @@
+import { useCallback, useMemo } from "react";
+import { useSearchParams } from "react-router-dom";
+
+/** 通过 URL query 打开/关闭详情弹层(可刷新恢复) */
+export function useAdminDetailQuery(paramKey: string) {
+ const [searchParams, setSearchParams] = useSearchParams();
+
+ const id = useMemo(() => {
+ const raw = searchParams.get(paramKey);
+ if (!raw) return null;
+ const n = Number(raw);
+ return Number.isFinite(n) && n > 0 ? n : null;
+ }, [paramKey, searchParams]);
+
+ const open = useCallback(
+ (nextId: number) => {
+ setSearchParams(
+ (prev) => {
+ const p = new URLSearchParams(prev);
+ p.set(paramKey, String(nextId));
+ return p;
+ },
+ { replace: false },
+ );
+ },
+ [paramKey, setSearchParams],
+ );
+
+ const close = useCallback(() => {
+ setSearchParams(
+ (prev) => {
+ const p = new URLSearchParams(prev);
+ p.delete(paramKey);
+ return p;
+ },
+ { replace: true },
+ );
+ }, [paramKey, setSearchParams]);
+
+ return { id, open, close, isOpen: id != null };
+}
diff --git a/admin/src/index.css b/admin/src/index.css
index 4b82bff..9abea16 100644
--- a/admin/src/index.css
+++ b/admin/src/index.css
@@ -289,24 +289,29 @@
/* ---- Admin console shell ---- */
.admin-app {
- --admin-bg: #eef1ef;
- --admin-bg-subtle: #e4eae6;
+ --admin-bg: #e9eef5;
+ --admin-bg-subtle: #dfe6f0;
--admin-card: #ffffff;
--admin-text: #1a211c;
- --admin-muted: #6b756e;
- --admin-border: #dde4df;
+ --admin-muted: #64748b;
+ --admin-border: #e2e8f0;
+ --color-border: #e2e8f0;
+ --admin-table-head: #e9f0fb;
+ --admin-table-head-text: #5b6b7c;
+ --admin-tag-bg: #e8f1ff;
+ --admin-tag-text: #3d6ea8;
--admin-forest: #1f5c48;
--admin-forest-deep: #163f33;
--admin-accent: #3d9a72;
--admin-accent-soft: rgba(61, 154, 114, 0.12);
- --admin-accent-ring: rgba(31, 92, 72, 0.18);
- --admin-sidebar: #121a16;
+ --admin-accent-ring: rgba(31, 92, 72, 0.16);
+ --admin-sidebar: #142820;
--admin-sidebar-border: rgba(255, 255, 255, 0.06);
--admin-sidebar-text: rgba(240, 245, 242, 0.72);
--admin-sidebar-muted: rgba(240, 245, 242, 0.42);
--admin-sidebar-w: 232px;
- --admin-radius: 14px;
- --admin-shadow: 0 1px 2px rgba(18, 26, 22, 0.04), 0 8px 24px rgba(18, 26, 22, 0.04);
+ --admin-radius: 12px;
+ --admin-shadow: 0 1px 3px rgba(15, 23, 42, 0.04), 0 8px 24px rgba(15, 23, 42, 0.05);
display: flex;
min-height: 100vh;
background:
@@ -396,6 +401,7 @@
}
.admin-nav-item {
+ position: relative;
display: flex;
align-items: center;
gap: 10px;
@@ -415,9 +421,20 @@
}
.admin-nav-item.is-active {
- background: var(--admin-accent-soft);
+ background: rgba(61, 154, 114, 0.16);
color: #e8f5ee;
- box-shadow: inset 0 0 0 1px rgba(61, 154, 114, 0.28);
+ box-shadow: inset 0 0 0 1px rgba(61, 154, 114, 0.22);
+}
+
+.admin-nav-item.is-active::before {
+ content: "";
+ position: absolute;
+ left: 0;
+ top: 9px;
+ bottom: 9px;
+ width: 3px;
+ border-radius: 0 3px 3px 0;
+ background: #6fd4a8;
}
.admin-nav-item.is-active svg {
@@ -461,7 +478,7 @@
align-items: center;
justify-content: space-between;
padding: 0 22px;
- background: rgba(255, 255, 255, 0.82);
+ background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--admin-border);
position: sticky;
@@ -503,7 +520,268 @@
.admin-content {
flex: 1;
overflow: auto;
- padding: 14px 18px 20px;
+ padding: 16px 20px 24px;
+}
+
+.admin-list-page {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ width: 100%;
+}
+
+.admin-list-stats {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 12px;
+}
+
+.admin-list-stat-card {
+ background: var(--admin-card);
+ border-radius: var(--admin-radius);
+ padding: 16px 18px;
+ box-shadow: var(--admin-shadow);
+}
+
+.admin-list-stat-label {
+ font-size: 13px;
+ color: var(--admin-muted);
+}
+
+.admin-list-stat-value {
+ margin-top: 8px;
+ font-family: var(--font-display);
+ font-size: 1.75rem;
+ font-weight: 700;
+ line-height: 1;
+ letter-spacing: -0.03em;
+ color: var(--admin-text);
+}
+
+.admin-list-stat-hint {
+ margin-top: 6px;
+ font-size: 11px;
+ color: var(--admin-muted);
+}
+
+.admin-data-table {
+ overflow: auto;
+ border-radius: var(--admin-radius);
+ border: 1px solid var(--admin-border);
+ background: var(--admin-card);
+ box-shadow: var(--admin-shadow);
+}
+
+.admin-data-table table {
+ width: 100%;
+ border-collapse: collapse;
+}
+
+.admin-data-table-head {
+ background: var(--admin-table-head);
+}
+
+.admin-list-page .admin-pagination {
+ padding: 12px 16px;
+ border-radius: var(--admin-radius);
+ border: 1px solid var(--admin-border);
+ background: var(--admin-card);
+ box-shadow: var(--admin-shadow);
+}
+
+.admin-user-search {
+ position: relative;
+ min-width: 220px;
+ flex: 1;
+ max-width: 320px;
+}
+
+.admin-user-search .admin-input {
+ width: 100%;
+ padding-right: 2rem;
+}
+
+.admin-user-search-clear {
+ position: absolute;
+ right: 8px;
+ top: 50%;
+ transform: translateY(-50%);
+ border: none;
+ background: transparent;
+ color: var(--admin-muted);
+ cursor: pointer;
+ font-size: 1.1rem;
+ line-height: 1;
+ padding: 0 4px;
+}
+
+.admin-user-search-dropdown {
+ position: absolute;
+ z-index: 40;
+ left: 0;
+ right: 0;
+ top: calc(100% + 4px);
+ max-height: 240px;
+ overflow: auto;
+ border: 1px solid var(--admin-border);
+ border-radius: var(--admin-radius);
+ background: var(--admin-card);
+ box-shadow: var(--admin-shadow);
+}
+
+.admin-user-search-option {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 2px;
+ width: 100%;
+ padding: 8px 12px;
+ border: none;
+ background: transparent;
+ text-align: left;
+ cursor: pointer;
+}
+
+.admin-user-search-option:hover {
+ background: var(--admin-table-head);
+}
+
+.admin-user-search-empty {
+ padding: 10px 12px;
+ font-size: 12px;
+ color: var(--admin-muted);
+}
+
+.admin-date-range {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-end;
+ gap: 8px;
+}
+
+.admin-date-range-sep {
+ padding-bottom: 10px;
+ color: var(--admin-muted);
+ font-size: 12px;
+}
+
+.admin-thumb {
+ width: 48px;
+ height: 48px;
+ object-fit: cover;
+ border-radius: 6px;
+ border: 1px solid var(--admin-border);
+ background: var(--admin-table-head);
+}
+
+.admin-native-select {
+ height: 36px;
+ padding: 0 10px;
+ border-radius: var(--admin-radius);
+ border: 1px solid var(--admin-border);
+ background: #fff;
+ font-size: 13px;
+ color: var(--admin-text);
+}
+
+.admin-detail-page {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+}
+
+.admin-detail-page-loading {
+ padding: 48px 0;
+ text-align: center;
+ font-size: 14px;
+ color: var(--admin-muted);
+}
+
+.admin-detail-page-toolbar {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-start;
+ gap: 12px 16px;
+ padding: 16px 18px;
+ border-radius: var(--admin-radius-lg);
+ background: #fff;
+ box-shadow: var(--admin-shadow);
+}
+
+.admin-detail-back {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--admin-muted);
+}
+
+.admin-detail-page-heading {
+ flex: 1;
+ min-width: 200px;
+}
+
+.admin-detail-page-title {
+ margin: 0;
+ font-size: 18px;
+ font-weight: 600;
+ line-height: 1.35;
+ color: var(--admin-text);
+}
+
+.admin-detail-page-sub {
+ margin: 4px 0 0;
+ font-size: 13px;
+ color: var(--admin-muted);
+}
+
+.admin-detail-page-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.admin-detail-tabs {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.admin-detail-tabs-list {
+ align-self: flex-start;
+}
+
+.admin-detail-tab-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ margin-top: 0;
+}
+
+.admin-json-preview {
+ max-height: 320px;
+ overflow: auto;
+ border-radius: var(--admin-radius);
+ background: #f8fafc;
+ padding: 12px 14px;
+ font-family: ui-monospace, monospace;
+ font-size: 11px;
+ line-height: 1.45;
+ white-space: pre-wrap;
+ word-break: break-all;
+}
+
+.admin-json-readonly {
+ max-height: 200px;
+ overflow: auto;
+ border-radius: var(--admin-radius);
+ border: 1px solid var(--admin-border);
+ background: #f8fafc;
+ padding: 10px 12px;
+ font-family: ui-monospace, monospace;
+ font-size: 11px;
+ line-height: 1.45;
+ white-space: pre-wrap;
+ word-break: break-all;
}
.admin-page {
@@ -536,7 +814,6 @@
.admin-panel {
background: var(--admin-card);
- border: 1px solid var(--admin-border);
border-radius: var(--admin-radius);
padding: 14px 16px;
box-shadow: var(--admin-shadow);
@@ -759,70 +1036,339 @@
background: rgba(239, 68, 68, 0.14);
}
-.admin-filter-bar {
+.admin-filter-bar,
+.admin-filter-panel {
display: flex;
flex-wrap: wrap;
- align-items: flex-end;
- gap: 12px;
- padding: 14px;
- border-radius: 12px;
- border: 1px solid var(--admin-border);
- background: #f8faf9;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px 10px;
+ padding: 10px 14px;
+ border-radius: var(--admin-radius);
+ background: var(--admin-card);
+ box-shadow: var(--admin-shadow);
}
-.admin-field {
+.admin-filter-bar-main,
+.admin-filter-panel-main {
display: flex;
- flex-direction: column;
- gap: 6px;
+ flex: 1 1 auto;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
min-width: 0;
}
-.admin-field-label {
- font-size: 11px;
- font-weight: 600;
- letter-spacing: 0.04em;
- text-transform: uppercase;
+.admin-filter-bar-trailing,
+.admin-filter-panel-trailing {
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ gap: 6px;
+ margin-left: auto;
+ font-size: 12px;
color: var(--admin-muted);
}
-.admin-input,
-.admin-select {
- height: 36px;
- min-width: 120px;
- border-radius: 9px;
- border: 1px solid #cfd8d2;
- background: #fff;
- padding: 0 10px;
- font-size: 13px;
- color: var(--admin-text);
- outline: none;
- transition: border-color 0.15s, box-shadow 0.15s;
+.admin-filter-search,
+.admin-filter-bar .admin-filter-search,
+.admin-filter-bar .admin-input-search-wrap,
+.admin-filter-panel .admin-filter-search,
+.admin-filter-panel .admin-input-search-wrap {
+ flex: 1 1 220px;
+ width: auto;
+ min-width: 180px;
+ max-width: 300px;
}
-.admin-input:focus,
-.admin-select:focus {
- border-color: var(--admin-accent);
- box-shadow: 0 0 0 3px var(--admin-accent-ring);
+.admin-filter-bar .admin-filter-search .admin-input,
+.admin-filter-bar .admin-input-search-wrap .admin-input,
+.admin-filter-panel .admin-filter-search .admin-input,
+.admin-filter-panel .admin-input-search-wrap .admin-input {
+ width: 100%;
}
-.admin-input-search-wrap {
- position: relative;
- flex: 1;
- min-width: 200px;
-}
+.admin-filter-bar .admin-control,
+.admin-filter-bar .admin-select,
+.admin-filter-bar .admin-input,
+.admin-filter-bar select,
+.admin-filter-bar input:not([type="checkbox"]):not([type="radio"]),
+.admin-filter-panel .admin-control,
+.admin-filter-panel .admin-select,
+.admin-filter-panel .admin-input,
+.admin-filter-panel select,
+.admin-filter-panel input:not([type="checkbox"]):not([type="radio"]) {
+ width: auto;
+ flex: 0 1 auto;
+ min-width: 112px;
+ max-width: 200px;
+}
+
+.admin-filter-bar .admin-user-search,
+.admin-filter-panel .admin-user-search {
+ flex: 0 1 220px;
+ width: auto;
+ min-width: 180px;
+ max-width: 260px;
+}
+
+.admin-filter-bar .admin-date-range,
+.admin-filter-panel .admin-date-range {
+ flex: 1 1 320px;
+ min-width: 260px;
+ max-width: 420px;
+}
+
+.admin-filter-bar > button,
+.admin-filter-bar-main > button,
+.admin-filter-bar .admin-btn,
+.admin-filter-bar .admin-filter-action,
+.admin-filter-panel > button,
+.admin-filter-panel-main > button,
+.admin-filter-panel .admin-btn,
+.admin-filter-panel .admin-filter-action {
+ flex-shrink: 0;
+ height: 36px;
+}
+
+.admin-filter-inline {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ flex: 0 1 auto;
+ min-width: 0;
+}
+
+.admin-filter-inline-label {
+ flex-shrink: 0;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ white-space: nowrap;
+}
+
+.admin-filter-inline .admin-control,
+.admin-filter-inline .admin-select,
+.admin-filter-inline .admin-input,
+.admin-filter-inline select,
+.admin-filter-inline input {
+ min-width: 108px;
+ max-width: 168px;
+}
+
+.admin-field {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ min-width: 0;
+}
+
+.admin-field-label,
+.settings-field-label {
+ display: block;
+ margin-bottom: 0;
+ font-size: 13px;
+ font-weight: 500;
+ letter-spacing: 0;
+ text-transform: none;
+ color: #475569;
+}
+
+.settings-field {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ min-width: 0;
+}
+
+.admin-control,
+.admin-input,
+.admin-select,
+.settings-input,
+.settings-select {
+ width: 100%;
+ height: 36px;
+ min-width: 0;
+ border-radius: 10px;
+ border: 1px solid #e2e8f0;
+ background: #fff;
+ padding: 0 12px;
+ font-size: 13px;
+ line-height: 1.4;
+ color: var(--admin-text);
+ outline: none;
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.6);
+ transition: border-color 0.15s ease, box-shadow 0.15s ease, background 0.15s ease;
+}
+
+.admin-control:hover,
+.admin-input:hover,
+.admin-select:hover,
+.settings-input:hover,
+.settings-select:hover {
+ border-color: #cbd5e1;
+}
+
+.admin-control:focus,
+.admin-input:focus,
+.admin-select:focus,
+.settings-input:focus,
+.settings-select:focus {
+ border-color: var(--admin-forest);
+ box-shadow: 0 0 0 3px var(--admin-accent-ring);
+}
+
+.admin-control::placeholder,
+.admin-input::placeholder,
+.settings-input::placeholder {
+ color: #94a3b8;
+}
+
+.admin-control:disabled,
+.admin-input:disabled,
+.admin-select:disabled,
+.settings-input:disabled,
+.settings-select:disabled {
+ cursor: not-allowed;
+ background: #f8fafc;
+ color: #94a3b8;
+ opacity: 1;
+}
+
+.admin-textarea,
+.settings-input[type="textarea"],
+textarea.settings-input,
+textarea.admin-control {
+ min-height: 88px;
+ height: auto;
+ padding: 10px 12px;
+ resize: vertical;
+ font-family: inherit;
+}
+
+.admin-select,
+.settings-select {
+ appearance: none;
+ padding-right: 32px;
+ cursor: pointer;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right 10px center;
+ background-size: 14px;
+}
+
+.admin-field-hint,
+.settings-field-hint {
+ margin: 0;
+ font-size: 12px;
+ line-height: 1.45;
+ color: #94a3b8;
+}
+
+.admin-form-grid {
+ display: grid;
+ gap: 12px;
+}
+
+.admin-form-grid--2 {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+}
+
+.admin-form-grid--full {
+ grid-column: 1 / -1;
+}
+
+@media (max-width: 640px) {
+ .admin-form-grid--2 {
+ grid-template-columns: 1fr;
+ }
+}
+
+.admin-form-switch-row,
+.settings-toggle-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 14px;
+ padding: 12px 14px;
+ border-radius: 12px;
+ background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
+}
+
+.admin-form-switch-row strong,
+.settings-toggle-row strong {
+ display: block;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--admin-text);
+}
+
+.admin-form-switch-row p,
+.settings-toggle-row span {
+ margin: 3px 0 0;
+ font-size: 12px;
+ line-height: 1.45;
+ color: var(--admin-muted);
+}
+
+.admin-secret-field {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.admin-secret-field-row {
+ display: flex;
+ gap: 8px;
+ align-items: stretch;
+}
+
+.admin-secret-field-row .admin-control,
+.admin-secret-field-row .settings-input {
+ flex: 1;
+}
+
+.admin-secret-status {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ align-self: flex-start;
+ padding: 2px 8px;
+ border-radius: 999px;
+ font-size: 11px;
+ font-weight: 600;
+ background: rgba(61, 154, 114, 0.1);
+ color: var(--admin-forest);
+}
+
+.admin-secret-status::before {
+ content: "";
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--admin-accent);
+}
+
+.admin-input-search-wrap {
+ position: relative;
+ flex: 1;
+ min-width: 200px;
+}
.admin-input-search-wrap svg {
position: absolute;
- left: 10px;
+ right: 12px;
+ left: auto;
top: 50%;
transform: translateY(-50%);
- color: #9aa39c;
+ color: #9aa3ad;
pointer-events: none;
}
.admin-input-search-wrap .admin-input {
width: 100%;
- padding-left: 32px;
+ padding-right: 38px;
+ padding-left: 12px;
}
.admin-select-wrap {
@@ -854,42 +1400,18 @@
.admin-field-hint {
margin: 0;
- font-size: 11px;
- line-height: 1.5;
- color: #909399;
-}
-
-.admin-filter-panel {
- display: flex;
- flex-direction: column;
- gap: 12px;
- padding: 14px;
- border-radius: 12px;
- border: 1px solid var(--admin-border);
- background: #f8faf9;
-}
-
-.admin-filter-panel-main {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: 12px;
-}
-
-.admin-filter-panel-trailing {
- display: flex;
- align-items: center;
- gap: 8px;
font-size: 12px;
- color: #909399;
+ line-height: 1.45;
+ color: #94a3b8;
}
.admin-chip-filter {
- display: flex;
+ display: inline-flex;
flex-wrap: wrap;
align-items: center;
- gap: 8px;
- width: 100%;
+ gap: 6px;
+ width: auto;
+ flex: 0 1 auto;
}
.admin-chip-filter-label {
@@ -932,26 +1454,334 @@
font-weight: 600;
}
-.admin-chip-count {
- min-width: 18px;
- height: 18px;
- padding: 0 5px;
- border-radius: 999px;
- background: rgba(0, 0, 0, 0.06);
- font-size: 10px;
- font-weight: 700;
- line-height: 18px;
- text-align: center;
+.admin-chip-count {
+ min-width: 18px;
+ height: 18px;
+ padding: 0 5px;
+ border-radius: 999px;
+ background: rgba(0, 0, 0, 0.06);
+ font-size: 10px;
+ font-weight: 700;
+ line-height: 18px;
+ text-align: center;
+}
+
+.admin-chip.is-active .admin-chip-count {
+ background: rgba(61, 154, 114, 0.18);
+}
+
+.admin-chip-filter-list.is-segment {
+ gap: 0;
+ padding: 3px;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.72);
+ border: 1px solid var(--admin-border);
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8);
+}
+
+.admin-segment-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 30px;
+ padding: 0 14px;
+ border: none;
+ border-radius: 999px;
+ background: transparent;
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--admin-muted);
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s, box-shadow 0.15s;
+ white-space: nowrap;
+}
+
+.admin-segment-btn:hover {
+ color: var(--admin-forest);
+}
+
+.admin-segment-btn.is-active {
+ background: linear-gradient(180deg, #2d6b55 0%, var(--admin-forest-deep) 100%);
+ color: #fff;
+ font-weight: 600;
+ box-shadow: 0 4px 12px rgba(31, 92, 72, 0.28);
+}
+
+.admin-dashboard-page {
+ gap: 16px;
+}
+
+.admin-dashboard-kpi-grid {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 12px;
+}
+
+.admin-dashboard-kpi {
+ position: relative;
+ overflow: hidden;
+ min-height: 118px;
+ padding: 16px 16px 14px;
+ border-radius: 16px;
+ border: 1px solid rgba(255, 255, 255, 0.55);
+ box-shadow: 0 10px 28px rgba(18, 26, 22, 0.06);
+}
+
+.admin-dashboard-kpi.tone-teal {
+ background: linear-gradient(145deg, #d8f0e6 0%, #b8e0cf 48%, #9fd4bf 100%);
+}
+
+.admin-dashboard-kpi.tone-blue {
+ background: linear-gradient(145deg, #dcecff 0%, #c4ddff 48%, #a8ccff 100%);
+}
+
+.admin-dashboard-kpi.tone-purple {
+ background: linear-gradient(145deg, #ebe4f8 0%, #ddd0f0 48%, #cfc0e8 100%);
+}
+
+.admin-dashboard-kpi.tone-sand {
+ background: linear-gradient(145deg, #f4ecdc 0%, #ebe0ca 48%, #e2d4b8 100%);
+}
+
+.admin-dashboard-kpi-icon {
+ position: absolute;
+ top: 14px;
+ right: 14px;
+ width: 38px;
+ height: 38px;
+ display: grid;
+ place-items: center;
+ border-radius: 12px;
+ background: rgba(255, 255, 255, 0.42);
+ color: var(--admin-forest-deep);
+ backdrop-filter: blur(6px);
+}
+
+.admin-dashboard-kpi-label {
+ font-size: 13px;
+ font-weight: 500;
+ color: rgba(22, 40, 32, 0.68);
+}
+
+.admin-dashboard-kpi-value {
+ margin-top: 8px;
+ font-family: var(--font-display);
+ font-size: 1.75rem;
+ font-weight: 700;
+ line-height: 1;
+ letter-spacing: -0.03em;
+ color: #142820;
+}
+
+.admin-dashboard-kpi-foot {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ margin-top: 10px;
+ font-size: 11px;
+ color: rgba(22, 40, 32, 0.58);
+}
+
+.admin-dashboard-kpi-trend {
+ font-weight: 600;
+ color: var(--admin-forest);
+}
+
+.admin-dashboard-section-tabs {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 10px;
+}
+
+.admin-dashboard-section-tab {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-height: 58px;
+ padding: 10px 14px;
+ border-radius: 14px;
+ border: 1px solid var(--admin-border);
+ background: rgba(255, 255, 255, 0.72);
+ text-align: left;
+ cursor: pointer;
+ transition: border-color 0.15s, background 0.15s, box-shadow 0.15s, transform 0.15s;
+}
+
+.admin-dashboard-section-tab:hover {
+ border-color: #c5d4cc;
+ background: #fff;
+}
+
+.admin-dashboard-section-tab.is-active {
+ border-color: rgba(31, 92, 72, 0.28);
+ background: linear-gradient(135deg, #ffffff 0%, #f2f8f5 100%);
+ box-shadow: 0 8px 22px rgba(31, 92, 72, 0.1);
+}
+
+.admin-dashboard-section-tab-icon {
+ display: grid;
+ place-items: center;
+ width: 34px;
+ height: 34px;
+ border-radius: 10px;
+ background: var(--admin-accent-soft);
+ color: var(--admin-forest);
+ flex-shrink: 0;
+}
+
+.admin-dashboard-section-tab.is-active .admin-dashboard-section-tab-icon {
+ background: linear-gradient(180deg, #3d9a72, var(--admin-forest));
+ color: #fff;
+}
+
+.admin-dashboard-section-tab-text {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+}
+
+.admin-dashboard-section-tab-label {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--admin-text);
+}
+
+.admin-dashboard-section-tab-desc {
+ font-size: 11px;
+ color: var(--admin-muted);
+}
+
+.admin-dashboard-glass {
+ background: rgba(255, 255, 255, 0.82);
+ backdrop-filter: blur(10px);
+ border-color: rgba(221, 228, 223, 0.9);
+}
+
+.admin-dashboard-mini-row {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 12px;
+}
+
+.admin-dashboard-mini-wide {
+ grid-column: span 1;
+}
+
+.admin-dashboard-mini-metric {
+ font-family: var(--font-display);
+ font-size: 1.5rem;
+ font-weight: 700;
+ color: var(--admin-text);
+}
+
+.admin-dashboard-mini-desc {
+ margin: 6px 0 0;
+ font-size: 12px;
+ color: var(--admin-muted);
+}
+
+.admin-dashboard-rank-list {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.admin-dashboard-rank-item {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 10px;
+ border-radius: 10px;
+ background: color-mix(in srgb, var(--admin-bg-subtle) 55%, transparent);
+}
+
+.admin-dashboard-rank-no {
+ width: 22px;
+ height: 22px;
+ display: grid;
+ place-items: center;
+ border-radius: 999px;
+ background: var(--admin-accent-soft);
+ color: var(--admin-forest);
+ font-size: 11px;
+ font-weight: 700;
+}
+
+.admin-dashboard-rank-amount {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--admin-forest);
+ font-variant-numeric: tabular-nums;
+}
+
+.admin-dashboard-project-row {
+ display: grid;
+ grid-template-columns: minmax(0, 1.2fr) minmax(240px, 0.8fr);
+ gap: 12px;
+}
+
+.admin-dashboard-stat-grid {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 10px;
+}
+
+.admin-dashboard-stat-grid-label {
+ font-size: 12px;
+ color: var(--admin-muted);
+}
+
+.admin-dashboard-stat-grid-value {
+ margin-top: 6px;
+ font-family: var(--font-display);
+ font-size: 1.35rem;
+ font-weight: 700;
+ color: var(--admin-text);
+}
+
+.admin-dashboard-tools {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 10px;
+}
+
+.admin-dashboard-tool-btn {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 88px;
+ padding: 14px 10px;
+ border-radius: 14px;
+ background: linear-gradient(180deg, #ffffff 0%, #f7faf8 100%);
+ color: var(--admin-text);
+ text-decoration: none;
+ font-size: 12px;
+ font-weight: 600;
+ box-shadow: var(--admin-shadow);
+ transition: transform 0.15s, box-shadow 0.15s;
+}
+
+.admin-dashboard-tool-btn:hover {
+ box-shadow: 0 8px 18px rgba(31, 92, 72, 0.08);
+ transform: translateY(-1px);
+ color: var(--admin-forest);
}
-.admin-chip.is-active .admin-chip-count {
- background: rgba(61, 154, 114, 0.18);
+.admin-dashboard-body--finance {
+ grid-template-columns: minmax(0, 1.4fr) minmax(280px, 0.8fr);
+ gap: 12px;
}
.admin-modal {
gap: 0 !important;
padding: 0 !important;
overflow: hidden;
+ border: none !important;
+ box-shadow: 0 20px 50px rgba(15, 23, 42, 0.16) !important;
}
.admin-modal--md {
@@ -972,7 +1802,7 @@
.admin-modal-header {
padding: 18px 22px 14px !important;
- border-bottom: 1px solid var(--admin-border);
+ border-bottom: none;
}
.admin-modal-title {
@@ -989,6 +1819,7 @@
.admin-modal-body {
padding: 18px 22px;
overflow-y: auto;
+ max-height: min(70vh, calc(100vh - 180px));
}
.admin-modal-footer {
@@ -996,10 +1827,174 @@
justify-content: flex-end;
gap: 10px;
padding: 14px 22px;
- border-top: 1px solid var(--admin-border);
+ border-top: none;
background: #fafbfa;
}
+.admin-modal .admin-detail-tabs {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+
+.admin-modal .admin-detail-tabs [role="tablist"] {
+ margin-bottom: 16px;
+ flex-wrap: wrap;
+}
+
+.admin-detail-section {
+ padding: 14px 16px;
+ border-radius: 12px;
+ background: #fafbfc;
+}
+
+.admin-detail-section + .admin-detail-section {
+ margin-top: 12px;
+}
+
+.admin-detail-section-title {
+ margin: 0 0 12px;
+ font-size: 12px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ color: var(--admin-muted);
+}
+
+.admin-detail-meta {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 12px 24px;
+ margin: 0;
+}
+
+.admin-detail-meta-item {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-width: 0;
+}
+
+.admin-detail-meta-item dt {
+ font-size: 12px;
+ color: var(--admin-muted);
+}
+
+.admin-detail-meta-item dd {
+ margin: 0;
+ font-size: 14px;
+ line-height: 1.45;
+ color: var(--admin-text);
+ word-break: break-word;
+}
+
+.admin-detail-meta-item--full {
+ grid-column: 1 / -1;
+}
+
+.admin-detail-stat-grid {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 10px;
+}
+
+.admin-detail-stat-card {
+ padding: 12px 14px;
+ border-radius: 10px;
+ background: #fff;
+}
+
+.admin-detail-stat-label {
+ font-size: 11px;
+ color: var(--admin-muted);
+}
+
+.admin-detail-stat-value {
+ margin-top: 6px;
+ font-size: 15px;
+ font-weight: 600;
+ color: var(--admin-text);
+ word-break: break-word;
+}
+
+.admin-detail-table-wrap {
+ overflow: auto;
+ max-height: 220px;
+ border-radius: 10px;
+ background: #fff;
+}
+
+.admin-detail-table-wrap table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 12px;
+}
+
+.admin-detail-table-wrap th {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ padding: 8px 10px;
+ border-bottom: none;
+ background: var(--admin-table-head);
+ color: var(--admin-muted);
+ font-weight: 600;
+ text-align: left;
+}
+
+.admin-detail-table-wrap td {
+ padding: 8px 10px;
+ border-bottom: none;
+ color: var(--admin-text);
+}
+
+.admin-detail-table-wrap tr:last-child td {
+ border-bottom: none;
+}
+
+.admin-detail-note {
+ padding: 12px 14px;
+ border-radius: 10px;
+ background: #fff;
+ font-size: 12px;
+ line-height: 1.6;
+ color: var(--admin-text);
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+.admin-detail-note--empty {
+ color: var(--admin-muted);
+}
+
+.admin-detail-media {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+}
+
+.admin-detail-media img,
+.admin-detail-media video {
+ max-height: 200px;
+ border-radius: 10px;
+ background: #000;
+}
+
+@media (max-width: 768px) {
+ .admin-detail-stat-grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+}
+
+@media (max-width: 640px) {
+ .admin-detail-meta {
+ grid-template-columns: 1fr;
+ }
+
+ .admin-form-grid--2 {
+ grid-template-columns: 1fr;
+ }
+}
+
.admin-page-btn {
min-width: 32px;
height: 32px;
@@ -1037,8 +2032,9 @@
.admin-table-wrap {
overflow: auto;
- border-radius: 12px;
- border: 1px solid var(--admin-border);
+ border-radius: var(--admin-radius);
+ background: var(--admin-card);
+ box-shadow: var(--admin-shadow);
}
.admin-table-wrap table {
@@ -1050,18 +2046,18 @@
.admin-table-wrap th {
text-align: left;
padding: 11px 14px;
- background: #f5f8f6;
- color: var(--admin-muted);
+ background: var(--admin-table-head);
+ color: var(--admin-table-head-text);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
- border-bottom: 1px solid var(--admin-border);
+ border-bottom: none;
}
.admin-table-wrap td {
padding: 12px 14px;
- border-bottom: 1px solid #eef2ef;
+ border-bottom: none;
color: var(--admin-text);
}
@@ -1070,7 +2066,7 @@
}
.admin-table-wrap tbody tr:hover td {
- background: #f8fbf9;
+ background: #f8fbfd;
}
.admin-table-wrap tr:last-child td {
@@ -1145,24 +2141,192 @@
padding: 12px 14px;
}
-.admin-dashboard-top {
- display: grid;
- grid-template-columns: repeat(3, minmax(0, 1fr));
- gap: 12px;
+.admin-dashboard-top {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 10px;
+}
+
+.admin-dashboard-top .admin-stat-card,
+.admin-dashboard-top .admin-panel.admin-stat-card {
+ min-height: 108px;
+ padding: 14px 14px 12px;
+}
+
+.admin-dashboard-top .admin-stat-value {
+ font-size: 1.45rem;
+}
+
+.admin-dashboard-top .admin-stat-icon {
+ top: 14px;
+ right: 12px;
+ width: 36px;
+ height: 36px;
+ border-radius: 10px;
+}
+
+.admin-dashboard-top .admin-stat-icon svg {
+ width: 18px;
+ height: 18px;
+}
+
+.admin-dashboard-status-card {
+ grid-column: span 2;
+}
+
+.admin-dashboard-body {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(260px, 320px);
+ gap: 12px;
+ align-items: stretch;
+}
+
+.admin-dashboard-filters {
+ margin-top: 10px;
+}
+
+.admin-dashboard-filters.admin-filter-bar {
+ padding: 10px 12px;
+ background: rgba(255, 255, 255, 0.78);
+ backdrop-filter: blur(8px);
+}
+
+.admin-dashboard-filters .admin-filter-bar-main {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px 14px;
+ width: 100%;
+}
+
+.admin-dashboard-filters .admin-chip-filter--segment {
+ display: grid;
+ grid-template-columns: 72px minmax(0, 1fr);
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ min-width: 0;
+}
+
+.admin-dashboard-filters .admin-chip-filter-label {
+ color: var(--admin-muted);
+ font-size: 11px;
+ font-weight: 600;
+ line-height: 1.2;
+}
+
+.admin-dashboard-filters .admin-chip-filter {
+ flex: none;
+ min-width: 0;
+ width: 100%;
+}
+
+.admin-dashboard-filters .admin-chip-filter-list.is-segment {
+ width: 100%;
+ flex-wrap: nowrap;
+ overflow-x: auto;
+ scrollbar-width: none;
+}
+
+.admin-dashboard-filters .admin-chip-filter-list.is-segment::-webkit-scrollbar {
+ display: none;
+}
+
+.admin-dashboard-filters .admin-segment-btn {
+ min-height: 28px;
+ padding: 0 10px;
+ font-size: 11px;
+}
+
+.admin-dashboard-charts {
+ display: grid;
+ grid-template-columns: minmax(0, 1.6fr) minmax(240px, 1fr);
+ gap: 12px;
+ margin-top: 12px;
+ align-items: stretch;
+}
+
+.admin-dashboard-chart-main,
+.admin-dashboard-chart-side {
+ min-height: 0;
+}
+
+.admin-dashboard-chart-main .admin-section-body,
+.admin-dashboard-chart-side .admin-section-body {
+ min-height: 300px;
+}
+
+.admin-chart-wrap {
+ width: 100%;
+ height: 300px;
+ min-height: 300px;
+}
+
+.admin-chart-wrap--compact {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ height: auto;
+ min-height: 280px;
+}
+
+.admin-chart-empty {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 200px;
+ border: 1px dashed var(--admin-border);
+ border-radius: 12px;
+ color: var(--admin-muted);
+ font-size: 13px;
+ background: color-mix(in srgb, var(--admin-bg-subtle) 40%, transparent);
+}
+
+.admin-chart-legend {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 0 4px 4px;
+}
+
+.admin-chart-legend-item {
+ display: grid;
+ grid-template-columns: 10px 1fr auto;
+ gap: 8px;
+ align-items: center;
+ font-size: 12px;
+}
+
+.admin-chart-legend-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 999px;
+}
+
+.admin-chart-legend-label {
+ color: var(--admin-text);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
-.admin-dashboard-body {
- display: grid;
- grid-template-columns: minmax(0, 1fr) minmax(260px, 320px);
- gap: 12px;
- align-items: stretch;
+.admin-chart-legend-value {
+ color: var(--admin-muted);
+ font-variant-numeric: tabular-nums;
}
-.admin-list-page {
- display: flex;
- flex-direction: column;
- gap: 12px;
- width: 100%;
+@media (max-width: 1400px) {
+ .admin-dashboard-top,
+ .admin-dashboard-kpi-grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+
+ .admin-dashboard-section-tabs {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+
+ .admin-dashboard-tools {
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ }
}
@media (max-width: 1280px) {
@@ -1170,15 +2334,51 @@
grid-template-columns: repeat(2, minmax(0, 1fr));
}
- .admin-dashboard-body {
+ .admin-dashboard-body,
+ .admin-dashboard-charts,
+ .admin-dashboard-mini-row,
+ .admin-dashboard-project-row {
+ grid-template-columns: 1fr;
+ }
+
+ .admin-dashboard-filters .admin-filter-bar-main {
grid-template-columns: 1fr;
}
+
+ .admin-dashboard-filters .admin-chip-filter-list.is-segment {
+ flex-wrap: wrap;
+ }
}
@media (max-width: 640px) {
- .admin-dashboard-top {
+ .admin-dashboard-top,
+ .admin-dashboard-kpi-grid,
+ .admin-dashboard-section-tabs {
+ grid-template-columns: 1fr;
+ }
+
+ .admin-dashboard-status-card {
+ grid-column: span 1;
+ }
+
+ .admin-list-stats {
grid-template-columns: 1fr;
}
+
+ .admin-dashboard-tools,
+ .admin-dashboard-stat-grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+
+ .admin-chip-filter-list.is-segment {
+ flex-wrap: wrap;
+ border-radius: 12px;
+ }
+
+ .admin-segment-btn {
+ flex: 1 1 auto;
+ min-width: fit-content;
+ }
}
.admin-notice-title {
@@ -1214,12 +2414,13 @@
align-items: center;
justify-content: space-between;
gap: 12px;
- border-radius: 12px;
- background: #f5f8f6;
+ border-radius: var(--admin-radius);
+ background: var(--admin-card);
border: 1px solid var(--admin-border);
- padding: 10px 12px;
- font-size: 13px;
+ padding: 12px 16px;
+ font-size: 12px;
color: var(--admin-muted);
+ box-shadow: var(--admin-shadow);
}
.admin-domain-card {
@@ -1235,24 +2436,107 @@
box-shadow: 0 4px 16px rgba(31, 92, 72, 0.06);
}
-/* ---- Model settings (VOZEB-inspired panels) ---- */
+/* ---- Model settings (compact SaaS panels) ---- */
.settings-page {
display: flex;
flex-direction: column;
- gap: 20px;
+ gap: 10px;
+ min-height: 0;
+}
+
+.settings-head {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px 12px;
+ padding: 10px 14px;
+ border-radius: var(--admin-radius);
+ background: var(--admin-card);
+ box-shadow: var(--admin-shadow);
+}
+
+.settings-head-desc {
+ margin: 0;
+ flex: 1 1 220px;
+ font-size: 12px;
+ line-height: 1.45;
+ color: var(--admin-muted);
+}
+
+.settings-tabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.settings-tab {
+ min-height: 32px;
+ padding: 0 12px;
+ font-size: 12px;
+}
+
+.settings-main {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ min-width: 0;
+}
+
+.settings-tab-shell {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ min-width: 0;
+}
+
+.settings-tab-toolbar {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+}
+
+.settings-save-btn {
+ display: inline-flex !important;
+ width: auto !important;
+ align-items: center;
+ gap: 6px;
+ min-height: 32px;
+ padding: 0 12px !important;
+ font-size: 12px;
+}
+
+.settings-tab-body {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ min-width: 0;
+}
+
+.settings-loading {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 28px 16px;
+ border-radius: var(--admin-radius);
+ background: var(--admin-card);
+ box-shadow: var(--admin-shadow);
+ font-size: 13px;
+ color: var(--admin-muted);
}
.settings-readiness {
display: grid;
- gap: 12px;
- grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+ gap: 8px;
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
}
.settings-readiness-card {
border: 1px solid var(--admin-border);
- border-radius: 10px;
+ border-radius: 8px;
background: #fafbfc;
- padding: 12px 14px;
+ padding: 8px 10px;
}
.settings-readiness-card.is-ready {
@@ -1262,9 +2546,64 @@
.settings-panel {
overflow: hidden;
- border-radius: 12px;
- border: 1px solid var(--admin-border);
+ border-radius: var(--admin-radius);
background: #fff;
+ box-shadow: var(--admin-shadow);
+}
+
+.settings-panel--compact .settings-panel-header {
+ padding: 8px 12px;
+}
+
+.settings-panel--compact .settings-panel-body {
+ padding: 8px 12px 10px;
+}
+
+.settings-panel--compact .settings-panel-desc {
+ margin-top: 2px;
+}
+
+.settings-ark-compact {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.settings-ark-key-row {
+ max-width: 420px;
+}
+
+.settings-ark-hint {
+ margin: 4px 0 0;
+ font-size: 11px;
+ line-height: 1.4;
+ color: #909399;
+}
+
+.settings-field-grid--3 {
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+}
+
+.settings-field-grid--4 {
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+}
+
+@media (max-width: 900px) {
+ .settings-field-grid--3,
+ .settings-field-grid--4 {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+}
+
+@media (max-width: 560px) {
+ .settings-field-grid--3,
+ .settings-field-grid--4 {
+ grid-template-columns: 1fr;
+ }
+}
+
+.settings-routing .settings-surface {
+ padding: 10px;
}
.settings-panel-header {
@@ -1272,47 +2611,60 @@
flex-wrap: wrap;
align-items: flex-start;
justify-content: space-between;
- gap: 12px;
+ gap: 8px;
+ padding: 10px 14px;
border-bottom: 1px solid var(--admin-border);
- padding: 16px 20px;
+ background: #fafbfc;
}
.settings-panel-title {
margin: 0;
- font-size: 15px;
+ font-size: 13px;
font-weight: 600;
color: #303133;
}
.settings-panel-desc {
- margin: 6px 0 0;
- font-size: 12px;
- line-height: 1.5;
+ margin: 2px 0 0;
+ font-size: 11px;
+ line-height: 1.4;
color: #909399;
}
.settings-panel-actions {
display: flex;
flex-wrap: wrap;
- gap: 8px;
+ gap: 6px;
}
.settings-panel-body {
- padding: 16px 20px 20px;
+ padding: 10px 14px 12px;
+}
+
+.settings-panel-body > .settings-surface {
+ background: transparent;
+ padding: 0;
+ border-radius: 0;
}
.settings-surface {
- border-radius: 10px;
- border: 1px solid #ebeef5;
+ border-radius: 8px;
background: #fafbfc;
- padding: 16px;
+ padding: 10px 12px;
+}
+
+.settings-surface + .settings-surface,
+.settings-section-title + .settings-field-grid,
+.settings-section-title + .settings-toggle-row,
+.settings-section-title + .settings-readiness {
+ margin-top: 8px;
}
.settings-section-title {
display: flex;
align-items: center;
- gap: 8px;
- font-size: 14px;
+ gap: 6px;
+ font-size: 12px;
font-weight: 600;
color: #303133;
}
@@ -1321,87 +2673,73 @@
display: inline-flex;
align-items: center;
justify-content: center;
- width: 28px;
- height: 28px;
- border-radius: 8px;
+ width: 22px;
+ height: 22px;
+ border-radius: 6px;
background: #fff;
- color: #606266;
- border: 1px solid #ebeef5;
+ color: #64748b;
+ box-shadow: 0 1px 2px rgba(15, 23, 42, 0.06);
+}
+
+.settings-section-icon svg {
+ width: 13px;
+ height: 13px;
}
.settings-field-grid {
- margin-top: 16px;
+ margin-top: 0;
display: grid;
- gap: 14px;
- grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
+ gap: 8px;
+ grid-template-columns: repeat(auto-fit, minmax(168px, 1fr));
}
-.settings-field {
- display: block;
- min-width: 0;
+.settings-field-span-full {
+ grid-column: 1 / -1;
}
-.settings-field-label {
- display: block;
- margin-bottom: 6px;
+.settings-page .settings-input,
+.settings-page .settings-select {
+ height: 32px;
+ padding: 0 10px;
font-size: 12px;
- font-weight: 500;
- color: #606266;
-}
-
-.settings-field-hint {
- display: block;
- margin-top: 4px;
- font-size: 11px;
- line-height: 1.4;
- color: #c0c4cc;
-}
-
-.settings-input,
-.settings-select {
- width: 100%;
- height: 36px;
border-radius: 8px;
- border: 1px solid #dcdfe6;
- background: #fff;
- padding: 0 10px;
- font-size: 13px;
- color: #303133;
- outline: none;
}
-.settings-input:focus,
-.settings-select:focus {
- border-color: var(--admin-accent);
- box-shadow: 0 0 0 2px var(--admin-accent-ring);
+.settings-page textarea.settings-input {
+ min-height: 72px;
+ padding: 8px 10px;
}
.settings-input.is-secret::placeholder {
- color: #909399;
+ color: #94a3b8;
}
-.settings-toggle-row {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 12px;
+.settings-page .settings-toggle-row {
+ padding: 8px 10px;
border-radius: 8px;
- border: 1px solid #ebeef5;
- background: #fff;
- padding: 10px 12px;
+ gap: 10px;
}
-.settings-toggle-row strong {
- display: block;
- font-size: 13px;
- color: #303133;
+.settings-page .settings-toggle-row strong {
+ font-size: 12px;
}
-.settings-toggle-row span {
- display: block;
+.settings-page .settings-toggle-row span {
margin-top: 2px;
font-size: 11px;
- color: #909399;
+}
+
+.settings-page .settings-field-label {
+ font-size: 12px;
+}
+
+.settings-page .settings-field-hint {
+ font-size: 11px;
+}
+
+.settings-page .admin-secret-status {
+ font-size: 10px;
+ padding: 1px 6px;
}
/* ---- Template management (card grid + editor) ---- */
diff --git a/admin/src/lib/admin-account.ts b/admin/src/lib/admin-account.ts
new file mode 100644
index 0000000..b961185
--- /dev/null
+++ b/admin/src/lib/admin-account.ts
@@ -0,0 +1,15 @@
+/** 公开账号 ID 展示:不足四位补零 */
+export function formatAccountId(userId: number): string {
+ const n = Math.max(0, Math.floor(userId));
+ if (n < 10000) return String(n).padStart(4, "0");
+ return String(n);
+}
+
+/** 从搜索词解析账号 ID(支持 0001 或纯数字) */
+export function parseAccountIdQuery(raw: string): number | null {
+ const trimmed = raw.trim();
+ if (!trimmed) return null;
+ const digits = trimmed.replace(/^0+/, "") || "0";
+ const n = Number(digits);
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
+}
diff --git a/admin/src/lib/dramaLabels.ts b/admin/src/lib/dramaLabels.ts
new file mode 100644
index 0000000..0257aa0
--- /dev/null
+++ b/admin/src/lib/dramaLabels.ts
@@ -0,0 +1,45 @@
+/** 漫剧资产生成状态(与 params.generation.status 一致) */
+export const DRAMA_GENERATION_STATUSES = [
+ "queued",
+ "running",
+ "generating",
+ "done",
+ "failed",
+ "cancelled",
+] as const;
+
+/** 漫剧生成状态中文标签(idle 仅用于分镜等无 params.generation 时的展示回退) */
+export function dramaGenerationStatusLabel(status: string): string {
+ const map: Record<string, string> = {
+ queued: "排队中",
+ running: "生成中",
+ generating: "生成中",
+ done: "已完成",
+ failed: "失败",
+ cancelled: "已取消",
+ idle: "未开始",
+ };
+ return map[status] ?? status;
+}
+
+/** 列表/详情展示:空值显示 — */
+export function formatDramaGenerationStatus(status: string | null | undefined): string {
+ if (!status) return "—";
+ return dramaGenerationStatusLabel(status);
+}
+
+/** 漫剧资产类型中文标签 */
+export function dramaAssetTypeLabel(type: string): string {
+ const map: Record<string, string> = {
+ character: "角色",
+ scene: "场景",
+ prop: "道具",
+ material: "素材",
+ narration: "旁白",
+ video: "视频",
+ audio: "音频",
+ text: "文本",
+ none: "未分类",
+ };
+ return map[type] ?? type;
+}
diff --git a/admin/src/lib/statusLabels.ts b/admin/src/lib/statusLabels.ts
index 1010c0f..0338e97 100644
--- a/admin/src/lib/statusLabels.ts
+++ b/admin/src/lib/statusLabels.ts
@@ -69,7 +69,7 @@ export const TASK_STATUS_LABELS: Record<string, string> = {
/** Task domain → Chinese */
export const TASK_DOMAIN_LABELS: Record<string, string> = {
drama: "漫剧",
- kepu: "科普",
+ kepu: "AI短视频",
tools: "工具",
studio: "工作室",
api: "开放 API",
diff --git a/admin/src/pages/DashboardPage.tsx b/admin/src/pages/DashboardPage.tsx
index 20f320a..801d82a 100644
--- a/admin/src/pages/DashboardPage.tsx
+++ b/admin/src/pages/DashboardPage.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
Activity,
@@ -14,12 +14,24 @@ import {
Zap,
} from "lucide-react";
import { toast } from "sonner";
-import { StatCard } from "@/components/admin/StatCard";
import { PageSection } from "@/components/admin/PageSection";
import { PageHeader } from "@/components/ui/page";
-import { api, type AdminOrder, type AdminStats, type PageMeta } from "@/api/client";
+import { api, type AdminOrder, type AdminStats, type AdminUpstreamUsage, type PageMeta } from "@/api/client";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
import { fenToYuan } from "@/lib/utils";
-import { orderStatusLabel, payTypeLabel, projectStatusLabel, taskDomainLabel } from "@/lib/statusLabels";
+import { projectStatusLabel, taskDomainLabel } from "@/lib/statusLabels";
+import { Button } from "@/components/ui/button";
+import {
+ buildStatsQuery,
+ dashboardRangeLabel,
+ DashboardFilters,
+ DEFAULT_DASHBOARD_FILTERS,
+ type DashboardFilterState,
+} from "@/pages/dashboard/DashboardFilters";
+import { DashboardKpiCard } from "@/pages/dashboard/DashboardKpiCard";
+import { DashboardSectionTabs, type DashboardSection } from "@/pages/dashboard/DashboardSectionTabs";
+import { UsageDistributionChart } from "@/pages/dashboard/UsageDistributionChart";
+import { UsageTrendChart } from "@/pages/dashboard/UsageTrendChart";
type OrderRes = { items: AdminOrder[]; meta: PageMeta };
@@ -31,7 +43,6 @@ const CAPABILITY_LABELS: Record<string, string> = {
unknown: "其他",
};
-// Map project status to pill style
function statusClass(status: string): string {
if (status === "DONE") return "is-done";
if (status === "FAILED" || status === "REJECTED" || status === "CANCELLED") return "is-fail";
@@ -45,320 +56,484 @@ function capabilityLabel(key: string): string {
return CAPABILITY_LABELS[key] ?? key;
}
-// Dashboard overview with usage / cost / rankings
+function domainChartLabel(key: string): string {
+ if (key === "kepu") return "AI短视频";
+ return taskDomainLabel(key);
+}
+
+/** 管理端仪表盘:板块切换 + 渐变 KPI + 可筛选用量图表 */
export function DashboardPage() {
+ const [section, setSection] = useState<DashboardSection>("overview");
+ const [filters, setFilters] = useState<DashboardFilterState>(DEFAULT_DASHBOARD_FILTERS);
const [stats, setStats] = useState<AdminStats | null>(null);
const [orders, setOrders] = useState<AdminOrder[]>([]);
+ const [upstreamUsage, setUpstreamUsage] = useState<AdminUpstreamUsage | null>(null);
+ const [upstreamSyncing, setUpstreamSyncing] = useState(false);
+ const [loading, setLoading] = useState(true);
- useEffect(() => {
- Promise.all([
- api<AdminStats>("/api/admin/stats"),
- api<OrderRes>("/api/admin/orders?page=1&page_size=8"),
- ])
- .then(([s, o]) => {
- setStats(s);
- setOrders(o.items);
- })
- .catch((err) => toast.error(err instanceof Error ? err.message : "加载失败"));
+ const loadUpstreamUsage = useCallback(async () => {
+ try {
+ const data = await api<AdminUpstreamUsage>("/api/admin/stats/upstream-usage?days=30");
+ setUpstreamUsage(data);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "官方用量加载失败");
+ }
}, []);
- const statusEntries = Object.entries(stats?.project_status_counts ?? {}).sort(
- (a, b) => b[1] - a[1],
- );
+ const syncUpstreamUsage = useCallback(async () => {
+ setUpstreamSyncing(true);
+ try {
+ await api("/api/admin/stats/upstream-usage/sync?days=30", { method: "POST" });
+ toast.success("官方用量已刷新");
+ await loadUpstreamUsage();
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "刷新失败");
+ } finally {
+ setUpstreamSyncing(false);
+ }
+ }, [loadUpstreamUsage]);
+
+ const loadData = useCallback(async (nextFilters: DashboardFilterState) => {
+ setLoading(true);
+ try {
+ const [s, o] = await Promise.all([
+ api<AdminStats>(buildStatsQuery(nextFilters)),
+ api<OrderRes>("/api/admin/orders?page=1&page_size=8&status=paid"),
+ ]);
+ setStats(s);
+ setOrders(o.items);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "加载失败");
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ const kpiReady = Boolean(stats);
+ const kpiPlaceholder = loading ? "…" : "—";
+
+ useEffect(() => {
+ void loadData(filters);
+ }, [filters, loadData]);
+
+ useEffect(() => {
+ void loadUpstreamUsage();
+ }, [loadUpstreamUsage]);
+
+ const statusEntries = Object.entries(stats?.project_status_counts ?? {}).sort((a, b) => b[1] - a[1]);
const daily = stats?.daily_usage ?? [];
const byCapability = stats?.usage_by_capability ?? [];
const byDomain = stats?.usage_by_domain ?? [];
const topUsers = stats?.top_users_by_charge ?? [];
+ const rangeLabel = dashboardRangeLabel(filters.days);
+ const showUsageFilters = section === "overview" || section === "usage";
return (
- <div className="admin-page">
+ <div className="admin-page admin-dashboard-page">
<PageHeader description="用户、充值、AI 调用与费用概览" />
- <div className="admin-dashboard-top">
- <StatCard label="用户总数" value={stats?.user_count ?? "—"} hint="总注册用户" icon={Users} />
- <StatCard
+ <div className="admin-dashboard-kpi-grid">
+ <DashboardKpiCard
+ label="用户总数"
+ value={kpiReady ? stats!.user_count : kpiPlaceholder}
+ hint="总注册用户"
+ icon={Users}
+ tone="teal"
+ />
+ <DashboardKpiCard
label="累计已付"
- value={stats ? `¥${fenToYuan(stats.order_paid_total_fen)}` : "—"}
+ value={kpiReady ? `¥${fenToYuan(stats!.order_paid_total_fen)}` : kpiPlaceholder}
hint="历史充值"
icon={Banknote}
- tone="success"
- />
- <StatCard
- label="今日已付"
- value={stats ? `¥${fenToYuan(stats.order_paid_today_fen)}` : "—"}
- hint="今日充值"
- icon={Wallet}
- tone="info"
+ tone="blue"
/>
- <StatCard
+ <DashboardKpiCard
label="本月 AI 扣费"
- value={stats ? `¥${fenToYuan(stats.usage_charge_month_fen ?? 0)}` : "—"}
- hint={`今日 ¥${fenToYuan(stats?.usage_charge_today_fen ?? 0)}`}
+ value={kpiReady ? `¥${fenToYuan(stats!.usage_charge_month_fen ?? 0)}` : kpiPlaceholder}
+ hint={kpiReady ? `今日 ¥${fenToYuan(stats!.usage_charge_today_fen ?? 0)}` : "今日扣费"}
icon={Zap}
- tone="warn"
+ tone="purple"
/>
- <StatCard
+ <DashboardKpiCard
label="本月上游成本"
- value={stats ? `¥${fenToYuan(stats.usage_cost_month_fen ?? 0)}` : "—"}
- hint={`今日 ¥${fenToYuan(stats?.usage_cost_today_fen ?? 0)} · 累计 ¥${fenToYuan(stats?.usage_cost_total_fen ?? 0)}`}
- icon={Banknote}
- tone="info"
- />
- <StatCard
- label="今日调用"
- value={stats?.usage_calls_today ?? "—"}
- hint={`本月 ${stats?.usage_calls_month ?? 0} · 累计 ${stats?.usage_calls_total ?? 0}`}
- icon={Activity}
- tone="info"
+ value={kpiReady ? `¥${fenToYuan(stats!.usage_cost_month_fen ?? 0)}` : kpiPlaceholder}
+ hint={kpiReady ? `今日 ¥${fenToYuan(stats!.usage_cost_today_fen ?? 0)}` : "成本汇总"}
+ icon={Wallet}
+ tone="sand"
/>
- <div className="admin-panel admin-stat-card tone-success">
- <div className="admin-stat-label">科普项目状态</div>
- <div className="mt-1 text-xs text-[var(--admin-muted)]">
- 漫剧项目 {stats?.drama_project_count ?? 0} 部
- </div>
- <div className="mt-2 flex flex-wrap gap-1.5">
- {statusEntries.length === 0 ? (
- <span className="text-xs text-[var(--admin-muted)]">暂无数据</span>
- ) : (
- statusEntries.map(([status, count]) => (
- <span key={status} className={`admin-status-pill !px-2 !py-1 !text-[11px] ${statusClass(status)}`}>
- {projectStatusLabel(status)} {count}
- </span>
- ))
- )}
- </div>
- </div>
</div>
- <div className="admin-dashboard-body">
- <PageSection title="近 7 日调用与扣费" bodyClassName="!pt-0" className="min-h-0">
- <div className="admin-table-wrap">
- <table>
- <thead>
- <tr>
- <th>日期</th>
- <th>调用次数</th>
- <th>扣费</th>
- </tr>
- </thead>
- <tbody>
- {daily.length === 0 ? (
- <tr>
- <td colSpan={3} className="!text-center text-[var(--admin-muted)]">
- 暂无用量
- </td>
- </tr>
- ) : (
- daily.map((d) => (
- <tr key={d.date}>
- <td className="font-mono text-xs">{d.date}</td>
- <td>{d.calls}</td>
- <td>¥{fenToYuan(d.charge_fen)}</td>
- </tr>
- ))
- )}
- </tbody>
- </table>
+ <DashboardSectionTabs value={section} onChange={setSection} />
+
+ {showUsageFilters ? <DashboardFilters value={filters} onChange={setFilters} /> : null}
+
+ {section === "overview" ? (
+ <>
+ <div className="admin-dashboard-charts">
+ <PageSection
+ title={`${rangeLabel}用量趋势`}
+ description={loading ? "加载中…" : "按筛选条件聚合的日趋势"}
+ bodyClassName="!pt-2"
+ className="admin-dashboard-chart-main admin-dashboard-glass min-h-0"
+ >
+ <UsageTrendChart data={daily} metric={filters.metric} />
+ </PageSection>
+
+ <PageSection
+ title="能力分布"
+ description={rangeLabel}
+ bodyClassName="!pt-2"
+ className="admin-dashboard-chart-side admin-dashboard-glass min-h-0"
+ >
+ <UsageDistributionChart
+ data={byCapability}
+ metric={filters.metric}
+ labelForKey={capabilityLabel}
+ variant="donut"
+ />
+ </PageSection>
</div>
- </PageSection>
- <PageSection title="能力 / 领域分布(本月)" bodyClassName="!pt-0">
- <div className="mb-3 text-xs font-medium text-[var(--admin-muted)]">按能力</div>
- <div className="admin-table-wrap mb-4">
- <table>
- <thead>
- <tr>
- <th>能力</th>
- <th>调用</th>
- <th>扣费</th>
- </tr>
- </thead>
- <tbody>
- {byCapability.length === 0 ? (
- <tr>
- <td colSpan={3} className="!text-center text-[var(--admin-muted)]">
- 暂无
- </td>
- </tr>
+ <div className="admin-dashboard-mini-row">
+ <PageSection
+ title="今日已付"
+ bodyClassName="!pt-0"
+ className="admin-dashboard-glass min-h-0"
+ >
+ <div className="admin-dashboard-mini-metric">
+ {kpiReady ? `¥${fenToYuan(stats!.order_paid_today_fen)}` : kpiPlaceholder}
+ </div>
+ <p className="admin-dashboard-mini-desc">今日充值到账</p>
+ </PageSection>
+ <PageSection
+ title="今日调用"
+ bodyClassName="!pt-0"
+ className="admin-dashboard-glass min-h-0"
+ >
+ <div className="admin-dashboard-mini-metric">
+ {kpiReady ? stats!.usage_calls_today ?? 0 : kpiPlaceholder}
+ </div>
+ <p className="admin-dashboard-mini-desc">
+ {kpiReady ? `本月 ${stats!.usage_calls_month ?? 0} 次` : "调用次数"}
+ </p>
+ </PageSection>
+ <PageSection
+ title={`用户消费 TOP3(${rangeLabel})`}
+ actions={
+ <Link to="/orders?tab=usage" className="admin-link">
+ 更多 →
+ </Link>
+ }
+ bodyClassName="!pt-0"
+ className="admin-dashboard-glass min-h-0 admin-dashboard-mini-wide"
+ >
+ <div className="admin-dashboard-rank-list">
+ {topUsers.length === 0 ? (
+ <div className="admin-chart-empty !min-h-[120px]">暂无排行</div>
) : (
- byCapability.map((b) => (
- <tr key={b.key}>
- <td>{capabilityLabel(b.key)}</td>
- <td>{b.calls}</td>
- <td>¥{fenToYuan(b.charge_fen)}</td>
- </tr>
+ topUsers.slice(0, 3).map((u, idx) => (
+ <div key={u.user_id} className="admin-dashboard-rank-item">
+ <span className="admin-dashboard-rank-no">{idx + 1}</span>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-sm">{u.email ?? `用户 ${u.user_id}`}</div>
+ <div className="text-[11px] text-[var(--admin-muted)]">{u.calls} 次调用</div>
+ </div>
+ <span className="admin-dashboard-rank-amount">¥{fenToYuan(u.charge_fen)}</span>
+ </div>
))
)}
- </tbody>
- </table>
+ </div>
+ </PageSection>
</div>
- <div className="mb-2 text-xs font-medium text-[var(--admin-muted)]">按领域</div>
- <div className="admin-table-wrap">
- <table>
- <thead>
- <tr>
- <th>领域</th>
- <th>调用</th>
- <th>扣费</th>
- </tr>
- </thead>
- <tbody>
- {byDomain.length === 0 ? (
- <tr>
- <td colSpan={3} className="!text-center text-[var(--admin-muted)]">
- 暂无
- </td>
- </tr>
- ) : (
- byDomain.map((b) => (
- <tr key={b.key}>
- <td>{taskDomainLabel(b.key)}</td>
- <td>{b.calls}</td>
- <td>¥{fenToYuan(b.charge_fen)}</td>
+ </>
+ ) : null}
+
+ {section === "usage" ? (
+ <>
+ <div className="admin-dashboard-charts">
+ <PageSection
+ title={`${rangeLabel}用量趋势`}
+ description={loading ? "加载中…" : "扣费 / 成本 / 调用按日聚合"}
+ bodyClassName="!pt-2"
+ className="admin-dashboard-chart-main admin-dashboard-glass min-h-0"
+ >
+ <UsageTrendChart data={daily} metric={filters.metric} />
+ </PageSection>
+
+ <PageSection
+ title="能力分布"
+ description={rangeLabel}
+ bodyClassName="!pt-2"
+ className="admin-dashboard-chart-side admin-dashboard-glass min-h-0"
+ >
+ <UsageDistributionChart
+ data={byCapability}
+ metric={filters.metric}
+ labelForKey={capabilityLabel}
+ variant="donut"
+ />
+ </PageSection>
+ </div>
+
+ <div className="admin-dashboard-body">
+ <PageSection title="领域分布" description={rangeLabel} bodyClassName="!pt-2" className="admin-dashboard-glass min-h-0">
+ <UsageDistributionChart
+ data={byDomain}
+ metric={filters.metric}
+ labelForKey={domainChartLabel}
+ variant="bar"
+ />
+ </PageSection>
+
+ <PageSection
+ title={`用户消费排行(${rangeLabel})`}
+ actions={
+ <Link to="/orders?tab=usage" className="admin-link">
+ 用量明细 →
+ </Link>
+ }
+ bodyClassName="!pt-0"
+ className="admin-dashboard-glass min-h-0"
+ >
+ <div className="admin-table-wrap">
+ <table>
+ <thead>
+ <tr>
+ <th>#</th>
+ <th>用户</th>
+ <th>调用</th>
+ <th>扣费</th>
</tr>
- ))
- )}
- </tbody>
- </table>
+ </thead>
+ <tbody>
+ {topUsers.length === 0 ? (
+ <tr>
+ <td colSpan={4} className="!text-center text-[var(--admin-muted)]">
+ 暂无排行
+ </td>
+ </tr>
+ ) : (
+ topUsers.map((u, idx) => (
+ <tr key={u.user_id}>
+ <td>{idx + 1}</td>
+ <td>
+ <AdminEntityLink kind="user" id={u.user_id} label={u.email ?? undefined} />
+ <div className="font-mono text-[11px] text-[var(--admin-muted)]">
+ ID {u.user_id}
+ </div>
+ </td>
+ <td>{u.calls}</td>
+ <td>¥{fenToYuan(u.charge_fen)}</td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </div>
+ </PageSection>
</div>
- </PageSection>
- </div>
+ </>
+ ) : null}
- <div className="admin-dashboard-body mt-4">
- <PageSection
- title="用户消费排行(近 30 日)"
- actions={
- <Link to="/orders?tab=usage" className="admin-link">
- 用量明细 →
- </Link>
- }
- bodyClassName="!pt-0"
- className="min-h-0"
- >
- <div className="admin-table-wrap">
- <table>
- <thead>
- <tr>
- <th>#</th>
- <th>用户</th>
- <th>调用</th>
- <th>扣费</th>
- </tr>
- </thead>
- <tbody>
- {topUsers.length === 0 ? (
+ {section === "finance" ? (
+ <div className="admin-dashboard-body admin-dashboard-body--finance">
+ <PageSection
+ title="Seedance 官方用量对照"
+ description={
+ upstreamUsage?.configured
+ ? `近 30 日本地 seedance 成本 vs 方舟 GetInferenceUsage${upstreamUsage.last_sync_at ? ` · 最近同步 ${new Date(upstreamUsage.last_sync_at).toLocaleString()}` : ""}`
+ : "未配置火山 Access Key,请在「支付计费 → 上游成本监控」配置后刷新官方数据"
+ }
+ actions={
+ upstreamUsage?.configured ? (
+ <Button type="button" size="sm" variant="outline" disabled={upstreamSyncing} onClick={() => void syncUpstreamUsage()}>
+ {upstreamSyncing ? "刷新中…" : "刷新官方数据"}
+ </Button>
+ ) : null
+ }
+ bodyClassName="!pt-0"
+ className="admin-dashboard-glass min-h-0"
+ >
+ <div className="admin-table-wrap">
+ <table>
+ <thead>
<tr>
- <td colSpan={4} className="!text-center text-[var(--admin-muted)]">
- 暂无排行
- </td>
+ <th>日期</th>
+ <th>本地成本</th>
+ <th>本地 token</th>
+ <th>官方 token</th>
+ <th>官方成本</th>
+ <th>差额</th>
</tr>
- ) : (
- topUsers.map((u, idx) => (
- <tr key={u.user_id}>
- <td>{idx + 1}</td>
- <td>
- <div className="text-sm">{u.email ?? u.user_id}</div>
- <div className="font-mono text-[11px] text-[var(--admin-muted)]">ID {u.user_id}</div>
+ </thead>
+ <tbody>
+ {(upstreamUsage?.series ?? []).length === 0 ? (
+ <tr>
+ <td colSpan={6} className="!text-center text-[var(--admin-muted)]">
+ 暂无对照数据
</td>
- <td>{u.calls}</td>
- <td>¥{fenToYuan(u.charge_fen)}</td>
</tr>
- ))
- )}
- </tbody>
- </table>
- </div>
- </PageSection>
+ ) : (
+ [...(upstreamUsage?.series ?? [])].reverse().slice(0, 14).map((row) => (
+ <tr key={row.date}>
+ <td className="font-mono text-xs">{row.date}</td>
+ <td>¥{fenToYuan(row.local_cost_fen)}</td>
+ <td>{row.local_tokens.toLocaleString()}</td>
+ <td>{row.official_tokens > 0 ? row.official_tokens.toLocaleString() : "—"}</td>
+ <td>{row.official_cost_fen > 0 ? `¥${fenToYuan(row.official_cost_fen)}` : "—"}</td>
+ <td>
+ {row.official_cost_fen > 0
+ ? `¥${fenToYuan(row.delta_fen)}${row.delta_pct != null ? ` (${row.delta_pct}%)` : ""}`
+ : "—"}
+ </td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </div>
+ </PageSection>
- <PageSection
- title="最近订单"
- actions={
- <Link to="/orders" className="admin-link">
- 全部 →
- </Link>
- }
- bodyClassName="!pt-0"
- className="min-h-0"
- >
- <div className="admin-table-wrap">
- <table>
- <thead>
- <tr>
- <th>单号</th>
- <th>用户</th>
- <th>金额</th>
- <th>支付</th>
- <th>状态</th>
- <th>时间</th>
- </tr>
- </thead>
- <tbody>
- {orders.length === 0 ? (
+ <PageSection
+ title="最近订单"
+ description="仅展示支付成功"
+ actions={
+ <Link to="/orders" className="admin-link">
+ 全部 →
+ </Link>
+ }
+ bodyClassName="!pt-0"
+ className="admin-dashboard-glass min-h-0"
+ >
+ <div className="admin-table-wrap">
+ <table>
+ <thead>
<tr>
- <td colSpan={6} className="!text-center text-[var(--admin-muted)]">
- 暂无订单
- </td>
+ <th>用户名</th>
+ <th>金额</th>
+ <th>支付时间</th>
</tr>
- ) : (
- orders.map((o) => (
- <tr key={o.id}>
- <td className="font-mono text-xs">{o.out_trade_no}</td>
- <td>{o.user_email ?? o.user_id}</td>
- <td>¥{fenToYuan(o.amount_fen)}</td>
- <td>{payTypeLabel(o.pay_type)}</td>
- <td>
- <span
- className={`admin-status-pill ${o.status === "paid" ? "is-done" : o.status === "pending" ? "is-warn" : "is-fail"}`}
- >
- {orderStatusLabel(o.status)}
- </span>
- </td>
- <td className="text-xs text-[var(--admin-muted)]">
- {new Date(o.created_at).toLocaleString()}
+ </thead>
+ <tbody>
+ {orders.length === 0 ? (
+ <tr>
+ <td colSpan={3} className="!text-center text-[var(--admin-muted)]">
+ 暂无已支付订单
</td>
</tr>
+ ) : (
+ orders.map((o) => (
+ <tr key={o.id}>
+ <td>
+ <AdminEntityLink kind="user" id={o.user_id} label={o.user_email ?? undefined} />
+ </td>
+ <td className="font-semibold text-[var(--admin-forest)]">¥{fenToYuan(o.amount_fen)}</td>
+ <td className="text-xs text-[var(--admin-muted)]">
+ {o.paid_at ? new Date(o.paid_at).toLocaleString() : "—"}
+ </td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </div>
+ </PageSection>
+ </div>
+ ) : null}
+
+ {section === "projects" ? (
+ <>
+ <div className="admin-dashboard-project-row">
+ <PageSection
+ title="AI短视频项目状态"
+ description={`漫剧项目 ${stats?.drama_project_count ?? 0} 部`}
+ bodyClassName="!pt-2"
+ className="admin-dashboard-glass min-h-0"
+ >
+ <div className="flex flex-wrap gap-1.5">
+ {statusEntries.length === 0 ? (
+ <span className="text-xs text-[var(--admin-muted)]">暂无数据</span>
+ ) : (
+ statusEntries.map(([status, count]) => (
+ <span key={status} className={`admin-status-pill !px-2.5 !py-1 !text-[11px] ${statusClass(status)}`}>
+ {projectStatusLabel(status)} {count}
+ </span>
))
)}
- </tbody>
- </table>
- </div>
- </PageSection>
- </div>
+ </div>
+ </PageSection>
- <div className="mt-4">
- <PageSection title="快捷入口" bodyClassName="!pt-0">
- <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-6">
- <Link to="/templates" className="admin-quick-btn !flex-row !items-center !py-2.5">
- <Shapes className="h-4 w-4" />
- 模板
- </Link>
- <Link to="/orders?tab=usage" className="admin-quick-btn !flex-row !items-center !py-2.5">
- <Receipt className="h-4 w-4" />
- 订单/用量
- </Link>
- <Link to="/users" className="admin-quick-btn !flex-row !items-center !py-2.5">
- <Users className="h-4 w-4" />
- 用户
- </Link>
- <Link to="/projects" className="admin-quick-btn !flex-row !items-center !py-2.5">
- <Clapperboard className="h-4 w-4" />
- 科普
- </Link>
- <Link to="/drama-projects" className="admin-quick-btn !flex-row !items-center !py-2.5">
- <Film className="h-4 w-4" />
- 漫剧
- </Link>
- <Link to="/queues" className="admin-quick-btn !flex-row !items-center !py-2.5">
- <Layers className="h-4 w-4" />
- 任务
- </Link>
- <Link to="/settings" className="admin-quick-btn !flex-row !items-center !py-2.5">
- <Settings className="h-4 w-4" />
- 配置
- </Link>
+ <PageSection title="调用统计" bodyClassName="!pt-2" className="admin-dashboard-glass min-h-0">
+ <div className="admin-dashboard-stat-grid">
+ <div>
+ <div className="admin-dashboard-stat-grid-label">今日调用</div>
+ <div className="admin-dashboard-stat-grid-value">
+ {kpiReady ? stats!.usage_calls_today ?? 0 : kpiPlaceholder}
+ </div>
+ </div>
+ <div>
+ <div className="admin-dashboard-stat-grid-label">本月调用</div>
+ <div className="admin-dashboard-stat-grid-value">
+ {kpiReady ? stats!.usage_calls_month ?? 0 : kpiPlaceholder}
+ </div>
+ </div>
+ <div>
+ <div className="admin-dashboard-stat-grid-label">累计调用</div>
+ <div className="admin-dashboard-stat-grid-value">
+ {kpiReady ? stats!.usage_calls_total ?? 0 : kpiPlaceholder}
+ </div>
+ </div>
+ </div>
+ </PageSection>
</div>
- </PageSection>
- </div>
+
+ <PageSection title={`领域分布(${rangeLabel})`} bodyClassName="!pt-2" className="admin-dashboard-glass min-h-0">
+ <UsageDistributionChart
+ data={byDomain}
+ metric="charge"
+ labelForKey={domainChartLabel}
+ variant="bar"
+ />
+ </PageSection>
+
+ <PageSection title="快捷入口" bodyClassName="!pt-2" className="admin-dashboard-glass">
+ <div className="admin-dashboard-tools">
+ <Link to="/templates" className="admin-dashboard-tool-btn">
+ <Shapes className="h-5 w-5" />
+ <span>模板管理</span>
+ </Link>
+ <Link to="/orders?tab=usage" className="admin-dashboard-tool-btn">
+ <Receipt className="h-5 w-5" />
+ <span>订单用量</span>
+ </Link>
+ <Link to="/users" className="admin-dashboard-tool-btn">
+ <Users className="h-5 w-5" />
+ <span>用户管理</span>
+ </Link>
+ <Link to="/projects" className="admin-dashboard-tool-btn">
+ <Clapperboard className="h-5 w-5" />
+ <span>AI短视频</span>
+ </Link>
+ <Link to="/drama-projects" className="admin-dashboard-tool-btn">
+ <Film className="h-5 w-5" />
+ <span>漫剧项目</span>
+ </Link>
+ <Link to="/queues" className="admin-dashboard-tool-btn">
+ <Layers className="h-5 w-5" />
+ <span>任务队列</span>
+ </Link>
+ <Link to="/settings" className="admin-dashboard-tool-btn">
+ <Settings className="h-5 w-5" />
+ <span>系统配置</span>
+ </Link>
+ <Link to="/orders" className="admin-dashboard-tool-btn">
+ <Activity className="h-5 w-5" />
+ <span>财务流水</span>
+ </Link>
+ </div>
+ </PageSection>
+ </>
+ ) : null}
</div>
);
}
diff --git a/admin/src/pages/DramaProjectsPage.tsx b/admin/src/pages/DramaProjectsPage.tsx
index 7d20e4a..dca173b 100644
--- a/admin/src/pages/DramaProjectsPage.tsx
+++ b/admin/src/pages/DramaProjectsPage.tsx
@@ -2,30 +2,34 @@ import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { toast } from "sonner";
import { api, type AdminDramaProject, type PageMeta } from "@/api/client";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
+import { AdminUserSearchSelect } from "@/components/admin/AdminUserSearchSelect";
import { PaginationBar } from "@/components/PaginationBar";
import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { PageHeader } from "@/components/ui/page";
-import { taskStatusLabel, taskTypeLabel } from "@/lib/statusLabels";
import { fenToYuan } from "@/lib/utils";
type ListRes = { items: AdminDramaProject[]; meta: PageMeta };
-/** Admin drama projects with filters and detail dialog */
+/** 漫剧项目列表:点击进入二级详情页 */
export function DramaProjectsPage() {
const [page, setPage] = useState(1);
const [q, setQ] = useState("");
- const [userId, setUserId] = useState("");
+ const [userId, setUserId] = useState<number | null>(null);
+ const [summaryStatus, setSummaryStatus] = useState("");
+ const [assetsSeedStatus, setAssetsSeedStatus] = useState("");
const [data, setData] = useState<ListRes | null>(null);
- const [detail, setDetail] = useState<AdminDramaProject | null>(null);
async function load(nextPage = page) {
try {
const params = new URLSearchParams({ page: String(nextPage), page_size: String(DEFAULT_PAGE_SIZE) });
if (q.trim()) params.set("q", q.trim());
- if (userId.trim()) params.set("user_id", userId.trim());
+ if (userId) params.set("user_id", String(userId));
+ if (summaryStatus.trim()) params.set("summary_status", summaryStatus.trim());
+ if (assetsSeedStatus.trim()) params.set("assets_seed_status", assetsSeedStatus.trim());
setData(await api<ListRes>(`/api/admin/drama-projects?${params}`));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载失败");
@@ -37,34 +41,22 @@ export function DramaProjectsPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page]);
- async function openDetail(id: number) {
- try {
- setDetail(await api<AdminDramaProject>(`/api/admin/drama-projects/${id}`));
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "加载详情失败");
- }
- }
-
- const usage = detail?.usage;
-
return (
<div className="admin-list-page">
- <PageHeader description="漫剧项目:集数、资产、生产状态、费用与关联任务" />
- <div className="admin-filter-bar">
- <Input
- className="max-w-xs"
- placeholder="标题 / 描述"
- value={q}
- onChange={(e) => setQ(e.target.value)}
- />
+ <PageHeader description="漫剧项目:集数、资产、生产状态与费用;点击详情进入二级页" />
+ <AdminFilterBar>
+ <Input placeholder="标题 / 描述" value={q} onChange={(e) => setQ(e.target.value)} />
+ <AdminUserSearchSelect value={userId} onChange={(id) => setUserId(id)} />
+ <Input placeholder="摘要状态" value={summaryStatus} onChange={(e) => setSummaryStatus(e.target.value)} />
<Input
- className="w-32"
- placeholder="用户 ID"
- value={userId}
- onChange={(e) => setUserId(e.target.value)}
+ placeholder="资产抽取状态"
+ value={assetsSeedStatus}
+ onChange={(e) => setAssetsSeedStatus(e.target.value)}
/>
<Button
+ size="sm"
variant="secondary"
+ className="admin-filter-action"
onClick={() => {
setPage(1);
void load(1);
@@ -72,7 +64,7 @@ export function DramaProjectsPage() {
>
筛选
</Button>
- </div>
+ </AdminFilterBar>
<div className="admin-table-wrap">
<table>
<thead>
@@ -84,7 +76,8 @@ export function DramaProjectsPage() {
<th>资产</th>
<th>费用</th>
<th>摘要</th>
- <th>创建时间</th>
+ <th>资产抽取</th>
+ <th>更新时间</th>
<th></th>
</tr>
</thead>
@@ -92,25 +85,32 @@ export function DramaProjectsPage() {
{(data?.items ?? []).map((row) => (
<tr key={row.id}>
<td>{row.id}</td>
- <td className="max-w-[200px] truncate">{row.title}</td>
- <td>{row.user_email ?? row.user_id}</td>
+ <td className="max-w-[200px] truncate">
+ <Link to={`/drama-projects/${row.id}`} className="admin-link font-medium">
+ {row.title}
+ </Link>
+ </td>
+ <td>
+ <AdminEntityLink kind="user" id={row.user_id} label={row.user_email ?? undefined} />
+ </td>
<td>{row.episode_count ?? 0}</td>
<td>{row.asset_count ?? 0}</td>
<td>¥{fenToYuan(row.charge_fen ?? 0)}</td>
<td className="text-xs text-[var(--admin-muted)]">{row.summary_status || "—"}</td>
+ <td className="text-xs text-[var(--admin-muted)]">{row.assets_seed_status || "—"}</td>
<td className="text-xs text-[var(--admin-muted)]">
- {row.created_at ? new Date(row.created_at).toLocaleString() : "—"}
+ {row.updated_at ? new Date(row.updated_at).toLocaleString() : "—"}
</td>
<td>
- <Button size="sm" variant="outline" onClick={() => void openDetail(row.id)}>
- 详情
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-projects/${row.id}`}>详情</Link>
</Button>
</td>
</tr>
))}
{(data?.items.length ?? 0) === 0 ? (
<tr>
- <td colSpan={9} className="!text-center text-[var(--admin-muted)]">
+ <td colSpan={10} className="!text-center text-[var(--admin-muted)]">
暂无项目
</td>
</tr>
@@ -126,179 +126,6 @@ export function DramaProjectsPage() {
onPageChange={setPage}
/>
) : null}
-
- <Dialog open={!!detail} onOpenChange={(open) => !open && setDetail(null)}>
- <DialogContent className="max-h-[90vh] max-w-3xl overflow-y-auto">
- <DialogHeader>
- <DialogTitle>
- 漫剧 #{detail?.id} · {detail?.title}
- </DialogTitle>
- </DialogHeader>
- {detail && (
- <div className="space-y-4 text-sm">
- <section className="space-y-1">
- <div className="text-xs font-medium text-muted-foreground">基本信息</div>
- <div>用户:{detail.user_email ?? detail.user_id}</div>
- <div>{detail.description || "无描述"}</div>
- <div className="flex flex-wrap gap-2 text-xs">
- <span className="rounded border px-2 py-0.5">摘要 {detail.summary_status || "—"}</span>
- <span className="rounded border px-2 py-0.5">
- 分集 {detail.episode_content_status || "—"}
- </span>
- <span className="rounded border px-2 py-0.5">
- 资产抽取 {detail.assets_seed_status || "—"}
- </span>
- <span className="rounded border px-2 py-0.5">集 {detail.episode_count ?? 0}</span>
- <span className="rounded border px-2 py-0.5">资产 {detail.asset_count ?? 0}</span>
- <span className="rounded border px-2 py-0.5">分镜 {detail.fragment_count ?? 0}</span>
- </div>
- </section>
-
- <section className="space-y-1">
- <div className="text-xs font-medium text-muted-foreground">费用汇总</div>
- <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
- <div className="rounded border p-2">
- <div className="text-[11px] text-muted-foreground">扣费</div>
- <div>¥{fenToYuan(usage?.charge_fen ?? detail.charge_fen ?? 0)}</div>
- </div>
- <div className="rounded border p-2">
- <div className="text-[11px] text-muted-foreground">成本</div>
- <div>¥{fenToYuan(usage?.cost_fen ?? 0)}</div>
- </div>
- <div className="rounded border p-2">
- <div className="text-[11px] text-muted-foreground">调用</div>
- <div>{usage?.calls ?? 0}</div>
- </div>
- <div className="rounded border p-2">
- <div className="text-[11px] text-muted-foreground">图/视/LLM/TTS</div>
- <div>
- {usage?.image_gens ?? 0}/{usage?.video_gens ?? 0}/{usage?.llm_calls ?? 0}/
- {usage?.tts_gens ?? 0}
- </div>
- </div>
- </div>
- </section>
-
- <section className="space-y-1">
- <div className="text-xs font-medium text-muted-foreground">
- 集列表({(detail.episodes ?? []).length})
- </div>
- <div className="max-h-36 overflow-auto rounded border">
- <table className="w-full text-xs">
- <thead>
- <tr className="border-b bg-muted/40 text-left">
- <th className="p-2">ID</th>
- <th className="p-2">名称</th>
- <th className="p-2">分镜数</th>
- <th className="p-2">分镜状态</th>
- </tr>
- </thead>
- <tbody>
- {(detail.episodes ?? []).length === 0 ? (
- <tr>
- <td colSpan={4} className="p-2 text-center text-muted-foreground">
- 暂无集
- </td>
- </tr>
- ) : (
- (detail.episodes ?? []).map((ep) => (
- <tr key={ep.id} className="border-b">
- <td className="p-2">{ep.id}</td>
- <td className="p-2">{ep.name}</td>
- <td className="p-2">{ep.fragment_count}</td>
- <td className="p-2">{ep.fragment_plan_status || "—"}</td>
- </tr>
- ))
- )}
- </tbody>
- </table>
- </div>
- </section>
-
- <section className="space-y-1">
- <div className="text-xs font-medium text-muted-foreground">
- 资产摘要({(detail.assets ?? []).length})
- </div>
- <div className="max-h-36 overflow-auto rounded border">
- <table className="w-full text-xs">
- <thead>
- <tr className="border-b bg-muted/40 text-left">
- <th className="p-2">ID</th>
- <th className="p-2">类型</th>
- <th className="p-2">名称</th>
- <th className="p-2">封面</th>
- <th className="p-2">生成</th>
- </tr>
- </thead>
- <tbody>
- {(detail.assets ?? []).length === 0 ? (
- <tr>
- <td colSpan={5} className="p-2 text-center text-muted-foreground">
- 暂无资产
- </td>
- </tr>
- ) : (
- (detail.assets ?? []).map((a) => (
- <tr key={a.id} className="border-b">
- <td className="p-2">{a.id}</td>
- <td className="p-2">{a.type}</td>
- <td className="max-w-[120px] truncate p-2">{a.name || "—"}</td>
- <td className="p-2">{a.has_cover ? "有" : "—"}</td>
- <td className="p-2">{a.generation_status || "—"}</td>
- </tr>
- ))
- )}
- </tbody>
- </table>
- </div>
- </section>
-
- <section className="space-y-1">
- <div className="flex items-center justify-between">
- <div className="text-xs font-medium text-muted-foreground">
- 关联任务(最近 {(detail.recent_tasks ?? []).length})
- </div>
- <Link to="/queues" className="text-xs text-primary">
- 任务中心 →
- </Link>
- </div>
- <div className="max-h-48 overflow-auto rounded border">
- <table className="w-full text-xs">
- <thead>
- <tr className="border-b bg-muted/40 text-left">
- <th className="p-2">ID</th>
- <th className="p-2">类型</th>
- <th className="p-2">状态</th>
- <th className="p-2">已扣 / 预估</th>
- </tr>
- </thead>
- <tbody>
- {(detail.recent_tasks ?? []).length === 0 ? (
- <tr>
- <td colSpan={4} className="p-2 text-center text-muted-foreground">
- 暂无任务
- </td>
- </tr>
- ) : (
- (detail.recent_tasks ?? []).map((t) => (
- <tr key={t.id} className="border-b">
- <td className="p-2 font-mono">{t.id}</td>
- <td className="p-2">{taskTypeLabel(t.task_type)}</td>
- <td className="p-2">{taskStatusLabel(t.status)}</td>
- <td className="p-2">
- ¥{fenToYuan(t.billing_charged_fen)} / ¥{fenToYuan(t.billing_estimate_fen)}
- </td>
- </tr>
- ))
- )}
- </tbody>
- </table>
- </div>
- </section>
- </div>
- )}
- </DialogContent>
- </Dialog>
</div>
);
}
diff --git a/admin/src/pages/OrdersPage.tsx b/admin/src/pages/OrdersPage.tsx
index c76566e..0e63a33 100644
--- a/admin/src/pages/OrdersPage.tsx
+++ b/admin/src/pages/OrdersPage.tsx
@@ -1,7 +1,13 @@
import { useEffect, useState } from "react";
-import { useSearchParams } from "react-router-dom";
+import { Link, useSearchParams } from "react-router-dom";
import { toast } from "sonner";
import { api, type AdminLedger, type AdminOrder, type AdminUsageEventListRes, type PageMeta } from "@/api/client";
+import { AdminDateRangeFilter } from "@/components/admin/AdminDateRangeFilter";
+import { AdminDetailMeta, AdminDetailSection } from "@/components/admin/AdminDetailLayout";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
+import { AdminModal } from "@/components/admin/AdminModal";
+import { AdminUserSearchSelect } from "@/components/admin/AdminUserSearchSelect";
import { PaginationBar } from "@/components/PaginationBar";
import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { Badge } from "@/components/ui/badge";
@@ -11,6 +17,7 @@ import { Select } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { PageHeader } from "@/components/ui/page";
+import { useAdminDetailQuery } from "@/hooks/useAdminDetailQuery";
import { fenToYuan } from "@/lib/utils";
import { ledgerKindLabel, orderStatusLabel, payTypeLabel, taskDomainLabel } from "@/lib/statusLabels";
@@ -23,75 +30,93 @@ function tabFromSearch(raw: string | null): string {
return raw && ORDER_TABS.has(raw) ? raw : "orders";
}
-// Orders and wallet ledger tabs
+function ledgerRefLink(row: AdminLedger) {
+ if (row.ref_type === "order" && row.ref_id) {
+ const id = Number(row.ref_id);
+ if (Number.isFinite(id) && id > 0) {
+ return <AdminEntityLink kind="order" id={id} label={`订单#${id}`} />;
+ }
+ return (
+ <Link
+ to={`/orders?tab=orders&trade=${encodeURIComponent(row.ref_id)}`}
+ className="admin-link font-mono text-xs"
+ >
+ {row.ref_id}
+ </Link>
+ );
+ }
+ if (!row.ref_type && !row.ref_id) return "—";
+ return (
+ <span className="font-mono text-xs">
+ {row.ref_type}/{row.ref_id}
+ </span>
+ );
+}
+
+// 充值订单、钱包流水与用量明细
export function OrdersPage() {
- /*
- * tab active tab
- * orderStatus order filter
- * orderUserId user id filter for orders
- * ledgerKind ledger kind filter
- * ledgerUserId user id filter for ledger
- * orderPage orders page
- * ledgerPage ledger page
- * orders order list
- * ledger ledger list
- */
const [searchParams, setSearchParams] = useSearchParams();
const [tab, setTab] = useState(() => tabFromSearch(searchParams.get("tab")));
const [orderStatus, setOrderStatus] = useState("");
- const [orderUserId, setOrderUserId] = useState("");
+ const [orderUserId, setOrderUserId] = useState<number | null>(null);
const [ledgerKind, setLedgerKind] = useState("");
- const [ledgerUserId, setLedgerUserId] = useState("");
+ const [ledgerUserId, setLedgerUserId] = useState<number | null>(null);
const [orderPage, setOrderPage] = useState(1);
const [ledgerPage, setLedgerPage] = useState(1);
const [usagePage, setUsagePage] = useState(1);
- const [usageUserId, setUsageUserId] = useState("");
+ const [usageUserId, setUsageUserId] = useState<number | null>(null);
const [usageTaskId, setUsageTaskId] = useState("");
const [usageDomain, setUsageDomain] = useState("");
const [usageBillingKey, setUsageBillingKey] = useState("");
const [usageCapability, setUsageCapability] = useState("");
+ const [usageBasis, setUsageBasis] = useState("");
+ const [usageDateFrom, setUsageDateFrom] = useState("");
+ const [usageDateTo, setUsageDateTo] = useState("");
const [orders, setOrders] = useState<OrderRes | null>(null);
const [ledger, setLedger] = useState<LedgerRes | null>(null);
const [usage, setUsage] = useState<AdminUsageEventListRes | null>(null);
+ const [orderDetail, setOrderDetail] = useState<AdminOrder | null>(null);
+ const [ledgerDetail, setLedgerDetail] = useState<AdminLedger | null>(null);
+ const orderQuery = useAdminDetailQuery("order");
- // Load recharge orders
async function loadOrders(page = orderPage) {
try {
const params = new URLSearchParams({ page: String(page), page_size: String(DEFAULT_PAGE_SIZE) });
if (orderStatus) params.set("status", orderStatus);
- if (orderUserId.trim()) params.set("user_id", orderUserId.trim());
+ if (orderUserId) params.set("user_id", String(orderUserId));
setOrders(await api<OrderRes>(`/api/admin/orders?${params}`));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载订单失败");
}
}
- // Load wallet ledger
async function loadLedger(page = ledgerPage) {
try {
const params = new URLSearchParams({ page: String(page), page_size: String(DEFAULT_PAGE_SIZE) });
if (ledgerKind) params.set("kind", ledgerKind);
- if (ledgerUserId.trim()) params.set("user_id", ledgerUserId.trim());
+ if (ledgerUserId) params.set("user_id", String(ledgerUserId));
setLedger(await api<LedgerRes>(`/api/admin/ledger?${params}`));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载流水失败");
}
}
- // Load usage events
async function loadUsage(
page = usagePage,
overrides?: { billing_key?: string; capability?: string },
) {
try {
const params = new URLSearchParams({ page: String(page), page_size: String(DEFAULT_PAGE_SIZE) });
- if (usageUserId.trim()) params.set("user_id", usageUserId.trim());
+ if (usageUserId) params.set("user_id", String(usageUserId));
if (usageTaskId.trim()) params.set("task_run_id", usageTaskId.trim());
if (usageDomain) params.set("domain", usageDomain);
const billingKey = overrides?.billing_key ?? usageBillingKey.trim();
const capability = overrides?.capability ?? usageCapability.trim();
if (billingKey) params.set("billing_key", billingKey);
if (capability) params.set("capability", capability);
+ if (usageBasis) params.set("billing_basis", usageBasis);
+ if (usageDateFrom) params.set("created_from", `${usageDateFrom}T00:00:00`);
+ if (usageDateTo) params.set("created_to", `${usageDateTo}T23:59:59`);
setUsage(await api<AdminUsageEventListRes>(`/api/admin/usage-events?${params}`));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载用量失败");
@@ -118,6 +143,32 @@ export function OrdersPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [usagePage]);
+ useEffect(() => {
+ if (!orderQuery.id || !orders?.items) return;
+ const hit = orders.items.find((o) => o.id === orderQuery.id);
+ if (hit) setOrderDetail(hit);
+ }, [orderQuery.id, orders?.items]);
+
+ useEffect(() => {
+ const tradeNo = searchParams.get("trade");
+ if (!tradeNo) return;
+ void (async () => {
+ try {
+ const res = await api<OrderRes>(
+ `/api/admin/orders?page=1&page_size=1&out_trade_no=${encodeURIComponent(tradeNo)}`,
+ );
+ const hit = res.items[0];
+ if (hit) {
+ setOrderDetail(hit);
+ orderQuery.open(hit.id);
+ }
+ } catch {
+ /* 深链失败时静默,用户仍可手动筛选 */
+ }
+ })();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [searchParams]);
+
function onTabChange(next: string) {
setTab(next);
const params = new URLSearchParams(searchParams);
@@ -126,6 +177,15 @@ export function OrdersPage() {
setSearchParams(params, { replace: true });
}
+ async function copyText(text: string) {
+ try {
+ await navigator.clipboard.writeText(text);
+ toast.success("已复制");
+ } catch {
+ toast.error("复制失败");
+ }
+ }
+
return (
<div className="admin-list-page">
<PageHeader description="查看充值单、钱包流水与 AI 用量明细" />
@@ -136,25 +196,18 @@ export function OrdersPage() {
<TabsTrigger value="usage">用量明细</TabsTrigger>
</TabsList>
<TabsContent value="orders" className="space-y-4">
- <div className="flex flex-wrap gap-2">
- <Select
- className="w-40"
- value={orderStatus}
- onChange={(e) => setOrderStatus(e.target.value)}
- >
+ <AdminFilterBar>
+ <Select value={orderStatus} onChange={(e) => setOrderStatus(e.target.value)}>
<option value="">全部状态</option>
<option value="pending">待支付</option>
<option value="paid">已支付</option>
<option value="closed">已关闭</option>
</Select>
- <Input
- className="w-40"
- placeholder="用户 ID"
- value={orderUserId}
- onChange={(e) => setOrderUserId(e.target.value)}
- />
+ <AdminUserSearchSelect value={orderUserId} onChange={(id) => setOrderUserId(id)} />
<Button
+ size="sm"
variant="secondary"
+ className="admin-filter-action"
onClick={() => {
setOrderPage(1);
void loadOrders(1);
@@ -162,27 +215,38 @@ export function OrdersPage() {
>
筛选
</Button>
- </div>
+ </AdminFilterBar>
<div className="rounded-lg border bg-background">
<Table>
<TableHeader>
<TableRow>
- <TableHead>单号</TableHead>
+ <TableHead>ID</TableHead>
+ <TableHead>商户单号</TableHead>
<TableHead>用户</TableHead>
<TableHead>SKU</TableHead>
<TableHead>金额</TableHead>
<TableHead>入账</TableHead>
<TableHead>支付</TableHead>
<TableHead>状态</TableHead>
+ <TableHead>渠道单号</TableHead>
+ <TableHead>支付时间</TableHead>
<TableHead>创建时间</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{(orders?.items ?? []).map((o) => (
- <TableRow key={o.id}>
+ <TableRow
+ key={o.id}
+ className="cursor-pointer"
+ onClick={() => {
+ setOrderDetail(o);
+ orderQuery.open(o.id);
+ }}
+ >
+ <TableCell>{o.id}</TableCell>
<TableCell className="font-mono text-xs">{o.out_trade_no}</TableCell>
<TableCell>
- <div className="text-sm">{o.user_email ?? o.user_id}</div>
+ <AdminEntityLink kind="user" id={o.user_id} label={o.user_email ?? undefined} />
</TableCell>
<TableCell>{o.sku_id}</TableCell>
<TableCell>¥{fenToYuan(o.amount_fen)}</TableCell>
@@ -193,6 +257,10 @@ export function OrdersPage() {
{orderStatusLabel(o.status)}
</Badge>
</TableCell>
+ <TableCell className="font-mono text-xs">{o.trade_no || "—"}</TableCell>
+ <TableCell className="text-xs text-muted-foreground">
+ {o.paid_at ? new Date(o.paid_at).toLocaleString() : "—"}
+ </TableCell>
<TableCell className="text-xs text-muted-foreground">
{new Date(o.created_at).toLocaleString()}
</TableCell>
@@ -211,8 +279,8 @@ export function OrdersPage() {
)}
</TabsContent>
<TabsContent value="ledger" className="space-y-4">
- <div className="flex flex-wrap gap-2">
- <Select className="w-40" value={ledgerKind} onChange={(e) => setLedgerKind(e.target.value)}>
+ <AdminFilterBar>
+ <Select value={ledgerKind} onChange={(e) => setLedgerKind(e.target.value)}>
<option value="">全部类型</option>
<option value="topup">充值</option>
<option value="grant">赠送</option>
@@ -222,14 +290,11 @@ export function OrdersPage() {
<option value="settle">结算</option>
<option value="refund">退款</option>
</Select>
- <Input
- className="w-40"
- placeholder="用户 ID"
- value={ledgerUserId}
- onChange={(e) => setLedgerUserId(e.target.value)}
- />
+ <AdminUserSearchSelect value={ledgerUserId} onChange={(id) => setLedgerUserId(id)} />
<Button
+ size="sm"
variant="secondary"
+ className="admin-filter-action"
onClick={() => {
setLedgerPage(1);
void loadLedger(1);
@@ -237,7 +302,7 @@ export function OrdersPage() {
>
筛选
</Button>
- </div>
+ </AdminFilterBar>
<div className="rounded-lg border bg-background">
<Table>
<TableHeader>
@@ -247,15 +312,18 @@ export function OrdersPage() {
<TableHead>变动</TableHead>
<TableHead>余额后</TableHead>
<TableHead>类型</TableHead>
+ <TableHead>关联</TableHead>
<TableHead>备注</TableHead>
<TableHead>时间</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{(ledger?.items ?? []).map((e) => (
- <TableRow key={e.id}>
+ <TableRow key={e.id} className="cursor-pointer" onClick={() => setLedgerDetail(e)}>
<TableCell>{e.id}</TableCell>
- <TableCell>{e.user_email ?? e.user_id}</TableCell>
+ <TableCell>
+ <AdminEntityLink kind="user" id={e.user_id} label={e.user_email ?? undefined} />
+ </TableCell>
<TableCell className={e.delta_fen >= 0 ? "text-emerald-700" : "text-red-600"}>
{e.delta_fen >= 0 ? "+" : ""}
¥{fenToYuan(e.delta_fen)}
@@ -264,6 +332,7 @@ export function OrdersPage() {
<TableCell>
<Badge variant="secondary">{ledgerKindLabel(e.kind)}</Badge>
</TableCell>
+ <TableCell>{ledgerRefLink(e)}</TableCell>
<TableCell className="max-w-[200px] truncate">{e.note}</TableCell>
<TableCell className="text-xs text-muted-foreground">
{new Date(e.created_at).toLocaleString()}
@@ -283,20 +352,10 @@ export function OrdersPage() {
)}
</TabsContent>
<TabsContent value="usage" className="space-y-4">
- <div className="flex flex-wrap gap-2">
- <Input
- className="w-32"
- placeholder="用户 ID"
- value={usageUserId}
- onChange={(e) => setUsageUserId(e.target.value)}
- />
- <Input
- className="w-32"
- placeholder="任务 ID"
- value={usageTaskId}
- onChange={(e) => setUsageTaskId(e.target.value)}
- />
- <Select className="w-36" value={usageDomain} onChange={(e) => setUsageDomain(e.target.value)}>
+ <AdminFilterBar>
+ <AdminUserSearchSelect value={usageUserId} onChange={(id) => setUsageUserId(id)} />
+ <Input placeholder="任务 ID" value={usageTaskId} onChange={(e) => setUsageTaskId(e.target.value)} />
+ <Select value={usageDomain} onChange={(e) => setUsageDomain(e.target.value)}>
<option value="">全部领域</option>
<option value="kepu">科普</option>
<option value="drama">漫剧</option>
@@ -304,24 +363,36 @@ export function OrdersPage() {
<option value="api">开放 API</option>
</Select>
<Input
- className="w-40"
placeholder="billing_key"
value={usageBillingKey}
onChange={(e) => setUsageBillingKey(e.target.value)}
/>
- <Select
- className="w-32"
- value={usageCapability}
- onChange={(e) => setUsageCapability(e.target.value)}
- >
+ <Select value={usageCapability} onChange={(e) => setUsageCapability(e.target.value)}>
<option value="">全部能力</option>
<option value="llm">LLM 文本</option>
<option value="image">生图</option>
<option value="video">视频</option>
<option value="tts">配音</option>
</Select>
+ <Select value={usageBasis} onChange={(e) => setUsageBasis(e.target.value)}>
+ <option value="">全部计费依据</option>
+ <option value="estimate">估算</option>
+ <option value="upstream">实测(火山)</option>
+ <option value="upstream_usage">实测(token)</option>
+ <option value="upstream_cost">实测(费用)</option>
+ </Select>
+ <AdminDateRangeFilter
+ from={usageDateFrom}
+ to={usageDateTo}
+ onChange={({ from, to }) => {
+ setUsageDateFrom(from);
+ setUsageDateTo(to);
+ }}
+ />
<Button
+ size="sm"
variant="outline"
+ className="admin-filter-action"
onClick={() => {
setUsageBillingKey("llm_chat");
setUsageCapability("llm");
@@ -332,7 +403,9 @@ export function OrdersPage() {
LLM 用量
</Button>
<Button
+ size="sm"
variant="secondary"
+ className="admin-filter-action"
onClick={() => {
setUsagePage(1);
void loadUsage(1);
@@ -340,7 +413,7 @@ export function OrdersPage() {
>
筛选
</Button>
- </div>
+ </AdminFilterBar>
<div className="rounded-lg border bg-background">
<Table>
<TableHeader>
@@ -348,12 +421,14 @@ export function OrdersPage() {
<TableHead>时间</TableHead>
<TableHead>用户</TableHead>
<TableHead>任务</TableHead>
+ <TableHead>项目</TableHead>
<TableHead>领域</TableHead>
<TableHead>能力</TableHead>
<TableHead>模型</TableHead>
<TableHead>Tokens</TableHead>
- <TableHead>费用</TableHead>
- <TableHead>估算</TableHead>
+ <TableHead>扣费</TableHead>
+ <TableHead>上游成本</TableHead>
+ <TableHead>计费依据</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -362,18 +437,47 @@ export function OrdersPage() {
<TableCell className="text-xs text-muted-foreground">
{row.created_at ? new Date(row.created_at).toLocaleString() : "—"}
</TableCell>
- <TableCell>{row.user_email ?? row.user_id}</TableCell>
- <TableCell className="font-mono text-xs">
- {row.task_run_id ? `#${row.task_run_id}` : "历史/未关联"}
+ <TableCell>
+ <AdminEntityLink kind="user" id={row.user_id} label={row.user_email ?? undefined} />
+ </TableCell>
+ <TableCell>
+ {row.task_run_id ? (
+ <AdminEntityLink kind="task" id={row.task_run_id} />
+ ) : (
+ "历史/未关联"
+ )}
+ </TableCell>
+ <TableCell className="text-xs">
+ {row.project_id ? (
+ <AdminEntityLink kind="project" id={row.project_id} />
+ ) : row.drama_project_id ? (
+ <AdminEntityLink kind="drama" id={row.drama_project_id} />
+ ) : (
+ "—"
+ )}
</TableCell>
<TableCell>{row.domain ? taskDomainLabel(row.domain) : "—"}</TableCell>
<TableCell>{row.capability ?? row.billing_key}</TableCell>
<TableCell className="max-w-[120px] truncate text-xs">{row.model || "—"}</TableCell>
<TableCell>{row.total_tokens ?? 0}</TableCell>
<TableCell>¥{fenToYuan(row.charge_fen ?? 0)}</TableCell>
+ <TableCell>¥{fenToYuan(row.cost_fen ?? 0)}</TableCell>
<TableCell>
- <Badge variant={row.estimated ? "secondary" : "success"}>
- {row.estimated ? "估算" : "实测"}
+ <Badge
+ variant={
+ row.billing_basis === "estimate" || row.estimated
+ ? "secondary"
+ : "success"
+ }
+ title={
+ row.billing_basis === "upstream_cost"
+ ? "按火山返回的实际费用 × markup"
+ : row.billing_basis === "upstream_usage"
+ ? "按火山返回的 usage token × 配置单价 × markup"
+ : "上游未返回 usage,按配置估算 token 扣费"
+ }
+ >
+ {row.billing_basis_label ?? (row.estimated ? "估算" : "实测")}
</Badge>
</TableCell>
</TableRow>
@@ -391,6 +495,96 @@ export function OrdersPage() {
)}
</TabsContent>
</Tabs>
+
+ <AdminModal
+ open={orderQuery.isOpen && !!orderDetail}
+ onOpenChange={(open) => {
+ if (!open) {
+ setOrderDetail(null);
+ orderQuery.close();
+ }
+ }}
+ size="md"
+ title={orderDetail ? `订单明细 #${orderDetail.id}` : "订单明细"}
+ subtitle={orderDetail?.out_trade_no}
+ footer={
+ orderDetail ? (
+ <Button size="sm" variant="outline" onClick={() => void copyText(orderDetail.out_trade_no)}>
+ 复制商户单号
+ </Button>
+ ) : undefined
+ }
+ >
+ {orderDetail ? (
+ <AdminDetailSection>
+ <AdminDetailMeta
+ items={[
+ {
+ label: "用户",
+ value: (
+ <AdminEntityLink
+ kind="user"
+ id={orderDetail.user_id}
+ label={orderDetail.user_email ?? undefined}
+ />
+ ),
+ },
+ { label: "SKU", value: orderDetail.sku_id },
+ { label: "金额", value: `¥${fenToYuan(orderDetail.amount_fen)}` },
+ { label: "入账", value: `¥${fenToYuan(orderDetail.credit_fen)}` },
+ { label: "支付方式", value: payTypeLabel(orderDetail.pay_type) },
+ { label: "状态", value: orderStatusLabel(orderDetail.status) },
+ { label: "渠道单号", value: orderDetail.trade_no || "—" },
+ {
+ label: "支付时间",
+ value: orderDetail.paid_at ? new Date(orderDetail.paid_at).toLocaleString() : "—",
+ },
+ {
+ label: "创建时间",
+ value: new Date(orderDetail.created_at).toLocaleString(),
+ full: true,
+ },
+ ]}
+ />
+ </AdminDetailSection>
+ ) : null}
+ </AdminModal>
+
+ <AdminModal
+ open={!!ledgerDetail}
+ onOpenChange={(open) => !open && setLedgerDetail(null)}
+ size="md"
+ title={ledgerDetail ? `流水明细 #${ledgerDetail.id}` : "流水明细"}
+ >
+ {ledgerDetail ? (
+ <AdminDetailSection>
+ <AdminDetailMeta
+ items={[
+ {
+ label: "用户",
+ value: (
+ <AdminEntityLink
+ kind="user"
+ id={ledgerDetail.user_id}
+ label={ledgerDetail.user_email ?? undefined}
+ />
+ ),
+ },
+ { label: "类型", value: ledgerKindLabel(ledgerDetail.kind) },
+ { label: "变动", value: `¥${fenToYuan(ledgerDetail.delta_fen)}` },
+ { label: "余额后", value: `¥${fenToYuan(ledgerDetail.balance_after)}` },
+ { label: "关联", value: ledgerRefLink(ledgerDetail) },
+ { label: "备注", value: ledgerDetail.note || "—" },
+ {
+ label: "时间",
+ value: new Date(ledgerDetail.created_at).toLocaleString(),
+ full: true,
+ },
+ ]}
+ />
+ </AdminDetailSection>
+ ) : null}
+ </AdminModal>
</div>
);
}
diff --git a/admin/src/pages/ProjectsPage.tsx b/admin/src/pages/ProjectsPage.tsx
index 6fa8d67..3d01ab4 100644
--- a/admin/src/pages/ProjectsPage.tsx
+++ b/admin/src/pages/ProjectsPage.tsx
@@ -1,22 +1,31 @@
import { useEffect, useState } from "react";
-import { Link } from "react-router-dom";
import { toast } from "sonner";
import { api, type AdminProject, type PageMeta } from "@/api/client";
+import {
+ AdminDetailMeta,
+ AdminDetailNote,
+ AdminDetailSection,
+ AdminDetailStatGrid,
+ AdminDetailTableWrap,
+} from "@/components/admin/AdminDetailLayout";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
+import { AdminModal } from "@/components/admin/AdminModal";
+import { AdminUserSearchSelect } from "@/components/admin/AdminUserSearchSelect";
import { PaginationBar } from "@/components/PaginationBar";
import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { PageHeader } from "@/components/ui/page";
+import { useAdminDetailQuery } from "@/hooks/useAdminDetailQuery";
import { PROJECT_STATUS_OPTIONS, projectStatusLabel, taskStatusLabel, taskTypeLabel } from "@/lib/statusLabels";
import { fenToYuan } from "@/lib/utils";
type ListRes = { items: AdminProject[]; meta: PageMeta };
-// Badge color by project status
function statusBadgeVariant(status: string): "destructive" | "success" | "warning" | "info" | "secondary" {
if (status === "FAILED" || status === "REJECTED") return "destructive";
if (status === "DONE") return "success";
@@ -25,19 +34,30 @@ function statusBadgeVariant(status: string): "destructive" | "success" | "warnin
return "info";
}
-// 科普项目列表与详情(镜头 / 任务 / 费用)
+function mediaSrc(url: string | null | undefined): string {
+ const trimmed = (url || "").trim();
+ if (!trimmed) return "";
+ if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) return trimmed;
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
+}
+
+// 科普项目列表与详情(镜头 / 任务 / 费用 / 媒体预览)
export function ProjectsPage() {
const [q, setQ] = useState("");
const [status, setStatus] = useState("");
+ const [userId, setUserId] = useState<number | null>(null);
const [page, setPage] = useState(1);
const [data, setData] = useState<ListRes | null>(null);
const [detail, setDetail] = useState<AdminProject | null>(null);
+ const [detailLoading, setDetailLoading] = useState(false);
+ const projectDetail = useAdminDetailQuery("open");
async function load(nextPage = page) {
try {
const params = new URLSearchParams({ page: String(nextPage), page_size: String(DEFAULT_PAGE_SIZE) });
if (status) params.set("status", status);
if (q.trim()) params.set("q", q.trim());
+ if (userId) params.set("user_id", String(userId));
setData(await api<ListRes>(`/api/admin/projects?${params}`));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载失败");
@@ -50,34 +70,47 @@ export function ProjectsPage() {
}, [page]);
async function openDetail(id: number) {
+ setDetailLoading(true);
+ projectDetail.open(id);
try {
setDetail(await api<AdminProject>(`/api/admin/projects/${id}`));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载详情失败");
+ projectDetail.close();
+ } finally {
+ setDetailLoading(false);
}
}
+ useEffect(() => {
+ if (!projectDetail.id) {
+ setDetail(null);
+ return;
+ }
+ if (detail?.id === projectDetail.id) return;
+ void openDetail(projectDetail.id);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [projectDetail.id]);
+
const usage = detail?.usage;
return (
<div className="admin-list-page">
<PageHeader description="科普管线项目:状态、镜头、关联任务与费用" />
- <div className="admin-filter-bar">
- <Select className="w-44" value={status} onChange={(e) => setStatus(e.target.value)}>
+ <AdminFilterBar>
+ <Select value={status} onChange={(e) => setStatus(e.target.value)}>
{PROJECT_STATUS_OPTIONS.map((opt) => (
<option key={opt.value || "all"} value={opt.value}>
{opt.label}
</option>
))}
</Select>
- <Input
- className="max-w-xs"
- placeholder="标题 / 错误信息"
- value={q}
- onChange={(e) => setQ(e.target.value)}
- />
+ <Input placeholder="标题 / 错误信息" value={q} onChange={(e) => setQ(e.target.value)} />
+ <AdminUserSearchSelect value={userId} onChange={(id) => setUserId(id)} />
<Button
+ size="sm"
variant="secondary"
+ className="admin-filter-action"
onClick={() => {
setPage(1);
void load(1);
@@ -85,7 +118,7 @@ export function ProjectsPage() {
>
筛选
</Button>
- </div>
+ </AdminFilterBar>
<div className="rounded-lg border bg-background">
<Table>
<TableHeader>
@@ -93,11 +126,14 @@ export function ProjectsPage() {
<TableHead>ID</TableHead>
<TableHead>标题</TableHead>
<TableHead>用户</TableHead>
+ <TableHead>模板</TableHead>
+ <TableHead>管线</TableHead>
<TableHead>状态</TableHead>
<TableHead>进度</TableHead>
<TableHead>镜头</TableHead>
<TableHead>费用</TableHead>
- <TableHead>错误</TableHead>
+ <TableHead>创建</TableHead>
+ <TableHead>更新</TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
@@ -106,15 +142,22 @@ export function ProjectsPage() {
<TableRow key={p.id}>
<TableCell>{p.id}</TableCell>
<TableCell className="max-w-[180px] truncate">{p.title}</TableCell>
- <TableCell className="text-sm">{p.user_email ?? p.user_id}</TableCell>
+ <TableCell className="text-sm">
+ <AdminEntityLink kind="user" id={p.user_id} label={p.user_email ?? undefined} />
+ </TableCell>
+ <TableCell className="font-mono text-xs">{p.template_id}</TableCell>
+ <TableCell className="text-xs">{p.pipeline_mode}</TableCell>
<TableCell>
<Badge variant={statusBadgeVariant(p.status)}>{projectStatusLabel(p.status)}</Badge>
</TableCell>
<TableCell>{p.progress}%</TableCell>
<TableCell>{p.shot_count}</TableCell>
<TableCell>¥{fenToYuan(p.charge_fen ?? 0)}</TableCell>
- <TableCell className="max-w-[220px] truncate text-xs text-red-600">
- {p.error_msg || "—"}
+ <TableCell className="text-xs text-muted-foreground">
+ {new Date(p.created_at).toLocaleString()}
+ </TableCell>
+ <TableCell className="text-xs text-muted-foreground">
+ {new Date(p.updated_at).toLocaleString()}
</TableCell>
<TableCell>
<Button size="sm" variant="outline" onClick={() => void openDetail(p.id)}>
@@ -135,148 +178,165 @@ export function ProjectsPage() {
/>
)}
- <Dialog open={!!detail} onOpenChange={(open) => !open && setDetail(null)}>
- <DialogContent className="max-h-[90vh] max-w-3xl overflow-y-auto">
- <DialogHeader>
- <DialogTitle>
- 科普项目 #{detail?.id} · {detail?.title}
- </DialogTitle>
- </DialogHeader>
- {detail && (
- <div className="space-y-4 text-sm">
- <section className="space-y-1">
- <div className="text-xs font-medium text-muted-foreground">基本信息</div>
- <div>用户:{detail.user_email ?? detail.user_id}</div>
- <div>
- 状态:{projectStatusLabel(detail.status)} · 进度 {detail.progress}% · 镜头{" "}
- {detail.shot_count}
- </div>
- <div>模板:{detail.template_id}</div>
- <div>管线:{detail.pipeline_mode}</div>
- <div>成片:{detail.final_video_url || "—"}</div>
- <div className="rounded-md bg-muted p-3 text-xs whitespace-pre-wrap">
- {detail.error_msg || "无错误信息"}
- </div>
- </section>
+ <AdminModal
+ open={projectDetail.isOpen}
+ onOpenChange={(open) => {
+ if (!open) {
+ setDetail(null);
+ projectDetail.close();
+ }
+ }}
+ size="full"
+ title={detail ? `科普项目 #${detail.id} · ${detail.title}` : "科普项目详情"}
+ subtitle={detail ? projectStatusLabel(detail.status) : detailLoading ? "加载中…" : undefined}
+ bodyClassName="space-y-3"
+ >
+ {detailLoading && !detail ? (
+ <div className="py-10 text-center text-sm text-[var(--admin-muted)]">加载中…</div>
+ ) : null}
+ {detail ? (
+ <>
+ <AdminDetailSection title="基本信息">
+ <AdminDetailMeta
+ items={[
+ {
+ label: "用户",
+ value: (
+ <AdminEntityLink
+ kind="user"
+ id={detail.user_id}
+ label={detail.user_email ?? undefined}
+ />
+ ),
+ },
+ {
+ label: "状态 / 进度",
+ value: `${projectStatusLabel(detail.status)} · ${detail.progress}% · 镜头 ${detail.shot_count}`,
+ },
+ { label: "模板", value: detail.template_id },
+ { label: "管线", value: detail.pipeline_mode },
+ { label: "来源", value: detail.source_type || "—" },
+ {
+ label: "分辨率 / 比例",
+ value: `${detail.resolution_mode || "—"} · ${detail.output_ratio || "—"}`,
+ },
+ { label: "配音", value: detail.voice_id || "—", full: true },
+ ]}
+ />
+ <AdminDetailNote empty={!detail.error_msg} className="mt-3">
+ {detail.error_msg || "无错误信息"}
+ </AdminDetailNote>
+ </AdminDetailSection>
- <section className="space-y-1">
- <div className="text-xs font-medium text-muted-foreground">费用汇总</div>
- <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
- <div className="rounded border p-2">
- <div className="text-[11px] text-muted-foreground">扣费</div>
- <div>¥{fenToYuan(usage?.charge_fen ?? detail.charge_fen ?? 0)}</div>
- </div>
- <div className="rounded border p-2">
- <div className="text-[11px] text-muted-foreground">成本</div>
- <div>¥{fenToYuan(usage?.cost_fen ?? 0)}</div>
- </div>
- <div className="rounded border p-2">
- <div className="text-[11px] text-muted-foreground">调用</div>
- <div>{usage?.calls ?? 0}</div>
- </div>
- <div className="rounded border p-2">
- <div className="text-[11px] text-muted-foreground">图/视/LLM/TTS</div>
- <div>
- {usage?.image_gens ?? 0}/{usage?.video_gens ?? 0}/{usage?.llm_calls ?? 0}/
- {usage?.tts_gens ?? 0}
- </div>
- </div>
+ {(detail.cover_url || detail.final_video_url) ? (
+ <AdminDetailSection title="媒体预览">
+ <div className="admin-detail-media">
+ {detail.cover_url ? (
+ <img src={mediaSrc(detail.cover_url)} alt="封面" />
+ ) : null}
+ {detail.final_video_url ? (
+ <video src={mediaSrc(detail.final_video_url)} controls className="max-w-full" />
+ ) : null}
</div>
- </section>
+ </AdminDetailSection>
+ ) : null}
- <section className="space-y-1">
- <div className="text-xs font-medium text-muted-foreground">
- 镜头({(detail.shots ?? []).length})
- </div>
- <div className="max-h-40 overflow-auto rounded border">
- <table className="w-full text-xs">
- <thead>
- <tr className="border-b bg-muted/40 text-left">
- <th className="p-2">#</th>
- <th className="p-2">状态</th>
- <th className="p-2">图</th>
- <th className="p-2">视频</th>
- <th className="p-2">音频</th>
+ <AdminDetailSection title="费用汇总">
+ <AdminDetailStatGrid
+ items={[
+ { label: "扣费", value: `¥${fenToYuan(usage?.charge_fen ?? detail.charge_fen ?? 0)}` },
+ { label: "成本", value: `¥${fenToYuan(usage?.cost_fen ?? 0)}` },
+ { label: "Tokens", value: usage?.tokens ?? 0 },
+ {
+ label: "图/视/LLM/TTS",
+ value: `${usage?.image_gens ?? 0}/${usage?.video_gens ?? 0}/${usage?.llm_calls ?? 0}/${usage?.tts_gens ?? 0}`,
+ },
+ ]}
+ />
+ </AdminDetailSection>
+
+ <AdminDetailSection title={`镜头(${(detail.shots ?? []).length})`}>
+ <AdminDetailTableWrap>
+ <table>
+ <thead>
+ <tr>
+ <th>#</th>
+ <th>状态</th>
+ <th>时长</th>
+ <th>图</th>
+ <th>视频</th>
+ <th>音频</th>
+ </tr>
+ </thead>
+ <tbody>
+ {(detail.shots ?? []).length === 0 ? (
+ <tr>
+ <td colSpan={6} className="!text-center text-[var(--admin-muted)]">
+ 暂无镜头
+ </td>
</tr>
- </thead>
- <tbody>
- {(detail.shots ?? []).length === 0 ? (
- <tr>
- <td colSpan={5} className="p-2 text-center text-muted-foreground">
- 暂无镜头
- </td>
+ ) : (
+ (detail.shots ?? []).map((s) => (
+ <tr key={s.id}>
+ <td>{s.shot_no}</td>
+ <td>{s.status}</td>
+ <td>{s.duration}s</td>
+ <td>{s.has_image ? "有" : "—"}</td>
+ <td>{s.has_video ? "有" : "—"}</td>
+ <td>{s.has_audio ? "有" : "—"}</td>
</tr>
- ) : (
- (detail.shots ?? []).map((s) => (
- <tr key={s.id} className="border-b">
- <td className="p-2">{s.shot_no}</td>
- <td className="p-2">{s.status}</td>
- <td className="p-2">{s.has_image ? "有" : "—"}</td>
- <td className="p-2">{s.has_video ? "有" : "—"}</td>
- <td className="p-2">{s.has_audio ? "有" : "—"}</td>
- </tr>
- ))
- )}
- </tbody>
- </table>
- </div>
- </section>
+ ))
+ )}
+ </tbody>
+ </table>
+ </AdminDetailTableWrap>
+ </AdminDetailSection>
- <section className="space-y-1">
- <div className="flex items-center justify-between">
- <div className="text-xs font-medium text-muted-foreground">
- 关联任务(最近 {(detail.recent_tasks ?? []).length})
- </div>
- <Link to="/queues" className="text-xs text-primary">
- 任务中心 →
- </Link>
- </div>
- <div className="max-h-48 overflow-auto rounded border">
- <table className="w-full text-xs">
- <thead>
- <tr className="border-b bg-muted/40 text-left">
- <th className="p-2">ID</th>
- <th className="p-2">类型</th>
- <th className="p-2">状态</th>
- <th className="p-2">已扣 / 预估</th>
+ <AdminDetailSection title={`关联任务(最近 ${(detail.recent_tasks ?? []).length})`}>
+ <AdminDetailTableWrap className="max-h-[200px]">
+ <table>
+ <thead>
+ <tr>
+ <th>ID</th>
+ <th>类型</th>
+ <th>状态</th>
+ <th>已扣 / 预估</th>
+ </tr>
+ </thead>
+ <tbody>
+ {(detail.recent_tasks ?? []).length === 0 ? (
+ <tr>
+ <td colSpan={4} className="!text-center text-[var(--admin-muted)]">
+ 暂无任务
+ </td>
</tr>
- </thead>
- <tbody>
- {(detail.recent_tasks ?? []).length === 0 ? (
- <tr>
- <td colSpan={4} className="p-2 text-center text-muted-foreground">
- 暂无任务
+ ) : (
+ (detail.recent_tasks ?? []).map((t) => (
+ <tr key={t.id}>
+ <td>
+ <AdminEntityLink kind="task" id={t.id} />
+ </td>
+ <td>{taskTypeLabel(t.task_type)}</td>
+ <td>{taskStatusLabel(t.status)}</td>
+ <td>
+ ¥{fenToYuan(t.billing_charged_fen)} / ¥{fenToYuan(t.billing_estimate_fen)}
</td>
</tr>
- ) : (
- (detail.recent_tasks ?? []).map((t) => (
- <tr key={t.id} className="border-b">
- <td className="p-2 font-mono">{t.id}</td>
- <td className="p-2">{taskTypeLabel(t.task_type)}</td>
- <td className="p-2">{taskStatusLabel(t.status)}</td>
- <td className="p-2">
- ¥{fenToYuan(t.billing_charged_fen)} / ¥{fenToYuan(t.billing_estimate_fen)}
- </td>
- </tr>
- ))
- )}
- </tbody>
- </table>
- </div>
- </section>
+ ))
+ )}
+ </tbody>
+ </table>
+ </AdminDetailTableWrap>
+ </AdminDetailSection>
- {detail.source_text ? (
- <section>
- <div className="mb-1 text-xs font-medium text-muted-foreground">源文本</div>
- <div className="max-h-32 overflow-auto rounded-md border p-3 text-xs whitespace-pre-wrap">
- {detail.source_text}
- </div>
- </section>
- ) : null}
- </div>
- )}
- </DialogContent>
- </Dialog>
+ {detail.source_text ? (
+ <AdminDetailSection title="源文本">
+ <AdminDetailNote>{detail.source_text}</AdminDetailNote>
+ </AdminDetailSection>
+ ) : null}
+ </>
+ ) : null}
+ </AdminModal>
</div>
);
}
diff --git a/admin/src/pages/QueuesPage.tsx b/admin/src/pages/QueuesPage.tsx
index fedc078..6ebed65 100644
--- a/admin/src/pages/QueuesPage.tsx
+++ b/admin/src/pages/QueuesPage.tsx
@@ -1,12 +1,16 @@
-import { useCallback, useEffect, useMemo, useState } from "react";
-import { Activity, Ban, Eye, Layers, Loader2, RefreshCw, Search } from "lucide-react";
+import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
+import { Activity, Ban, Eye, Layers, Loader2, RefreshCw } from "lucide-react";
import { toast } from "sonner";
import { api, type AdminTaskListRes, type AdminTaskRow, type AdminTaskStats } from "@/api/client";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { AdminSearchInput } from "@/components/admin/AdminSearchInput";
+import { AdminUserSearchSelect } from "@/components/admin/AdminUserSearchSelect";
import { StatCard } from "@/components/admin/StatCard";
import { PageSection } from "@/components/admin/PageSection";
import { TaskDetailDialog } from "@/components/tasks/TaskDetailDialog";
import { PageHeader, Toolbar } from "@/components/ui/page";
import { PaginationBar } from "@/components/PaginationBar";
+import { useAdminDetailQuery } from "@/hooks/useAdminDetailQuery";
import { cn, fenToYuan } from "@/lib/utils";
import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { taskDomainLabel, taskStatusLabel, taskTypeLabel } from "@/lib/statusLabels";
@@ -28,13 +32,14 @@ function formatTime(value: string | null | undefined): string {
return new Date(value).toLocaleString();
}
-function scopeLabel(task: AdminTaskRow): string {
- const parts: string[] = [];
- if (task.drama_project_id) parts.push(`漫剧#${task.drama_project_id}`);
- if (task.project_id) parts.push(`科普#${task.project_id}`);
- if (task.episode_id) parts.push(`分集#${task.episode_id}`);
- if (task.fragment_id) parts.push(`分镜#${task.fragment_id}`);
- return parts.length ? parts.join(" · ") : "—";
+function scopeLinks(task: AdminTaskRow): ReactNode {
+ const parts: ReactNode[] = [];
+ if (task.drama_project_id) parts.push(<AdminEntityLink key="drama" kind="drama" id={task.drama_project_id} />);
+ if (task.project_id) parts.push(<AdminEntityLink key="project" kind="project" id={task.project_id} />);
+ if (task.episode_id) parts.push(<span key="ep">分集#{task.episode_id}</span>);
+ if (task.fragment_id) parts.push(<span key="frag">分镜#{task.fragment_id}</span>);
+ if (parts.length === 0) return <span className="text-[#909399]">—</span>;
+ return <div className="flex flex-wrap gap-1">{parts}</div>;
}
function canCancel(task: AdminTaskRow): boolean {
@@ -64,10 +69,11 @@ export function QueuesPage() {
const [searchInput, setSearchInput] = useState("");
const [domain, setDomain] = useState("");
const [status, setStatus] = useState("");
+ const [filterUserId, setFilterUserId] = useState<number | null>(null);
+ const [taskType, setTaskType] = useState("");
const [viewTab, setViewTab] = useState<"all" | "active">("all");
const [cancelLoading, setCancelLoading] = useState<number | null>(null);
- const [detailTaskId, setDetailTaskId] = useState<number | null>(null);
- const [detailOpen, setDetailOpen] = useState(false);
+ const taskDetail = useAdminDetailQuery("task");
const loadStats = useCallback(async () => {
const res = await api<AdminTaskStats>("/api/admin/tasks/stats");
@@ -84,6 +90,8 @@ export function QueuesPage() {
});
if (domain) params.set("domain", domain);
if (status) params.set("status", status);
+ if (filterUserId) params.set("user_id", String(filterUserId));
+ if (taskType.trim()) params.set("task_type", taskType.trim());
if (q.trim()) params.set("q", q.trim());
if (viewTab === "active" && !status) params.set("active_only", "true");
const res = await api<AdminTaskListRes>(`/api/admin/tasks?${params}`);
@@ -97,7 +105,7 @@ export function QueuesPage() {
setRefreshing(false);
}
},
- [domain, page, pageSize, q, status, viewTab],
+ [domain, filterUserId, page, pageSize, q, status, taskType, viewTab],
);
const refreshAll = useCallback(
@@ -117,13 +125,17 @@ export function QueuesPage() {
useEffect(() => {
void refreshAll();
- }, [page, pageSize, domain, status, q, viewTab, refreshAll]);
+ }, [page, pageSize, domain, status, q, viewTab, filterUserId, taskType, refreshAll]);
useEffect(() => {
const timer = window.setInterval(() => void refreshAll(true), REFRESH_MS);
return () => window.clearInterval(timer);
}, [refreshAll]);
+ function openDetail(taskId: number) {
+ taskDetail.open(taskId);
+ }
+
const handleCancel = useCallback(
async (task: AdminTaskRow) => {
if (!canCancel(task)) return;
@@ -147,11 +159,6 @@ export function QueuesPage() {
return Array.from(new Set(fromStats));
}, [stats]);
- function openDetail(taskId: number) {
- setDetailTaskId(taskId);
- setDetailOpen(true);
- }
-
return (
<div className="admin-page">
<PageHeader
@@ -273,76 +280,84 @@ export function QueuesPage() {
bodyClassName="space-y-4 !pt-0"
>
<Toolbar>
- <label className="admin-field">
- <span className="admin-field-label">领域</span>
- <select
- className="admin-select"
- value={domain}
- onChange={(e) => {
- setDomain(e.target.value);
- setPage(1);
- }}
- >
- <option value="">全部</option>
- {domainOptions.map((d) => (
- <option key={d} value={d}>
- {taskDomainLabel(d)}
- </option>
- ))}
- </select>
- </label>
- <label className="admin-field">
- <span className="admin-field-label">状态</span>
- <select
- className="admin-select"
- value={status}
- onChange={(e) => {
- setStatus(e.target.value);
+ <select
+ className="admin-select"
+ value={domain}
+ onChange={(e) => {
+ setDomain(e.target.value);
+ setPage(1);
+ }}
+ >
+ <option value="">全部领域</option>
+ {domainOptions.map((d) => (
+ <option key={d} value={d}>
+ {taskDomainLabel(d)}
+ </option>
+ ))}
+ </select>
+ <select
+ className="admin-select"
+ value={status}
+ onChange={(e) => {
+ setStatus(e.target.value);
+ setPage(1);
+ if (e.target.value) setViewTab("all");
+ }}
+ >
+ <option value="">全部状态</option>
+ {Object.entries({
+ pending: "排队中",
+ leased: "已租约",
+ running: "执行中",
+ awaiting_poll: "等待轮询",
+ cancel_requested: "取消中",
+ succeeded: "已成功",
+ failed: "失败",
+ cancelled: "已取消",
+ }).map(([value, label]) => (
+ <option key={value} value={value}>
+ {label}
+ </option>
+ ))}
+ </select>
+ <AdminUserSearchSelect
+ value={filterUserId}
+ onChange={(id) => {
+ setFilterUserId(id);
+ setPage(1);
+ }}
+ />
+ <input
+ className="admin-input"
+ placeholder="任务类型"
+ value={taskType}
+ onChange={(e) => {
+ setTaskType(e.target.value);
+ setPage(1);
+ }}
+ />
+ <AdminSearchInput
+ value={searchInput}
+ onChange={setSearchInput}
+ placeholder="任务类型 / 用户邮箱 / dedupe_key"
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ setQ(searchInput);
setPage(1);
- if (e.target.value) setViewTab("all");
- }}
- >
- <option value="">全部</option>
- {Object.entries({
- pending: "排队中",
- leased: "已租约",
- running: "执行中",
- awaiting_poll: "等待轮询",
- cancel_requested: "取消中",
- succeeded: "已成功",
- failed: "失败",
- cancelled: "已取消",
- }).map(([value, label]) => (
- <option key={value} value={value}>
- {label}
- </option>
- ))}
- </select>
- </label>
- <form
- className="flex min-w-[240px] flex-1 flex-wrap items-end gap-2"
- onSubmit={(e) => {
- e.preventDefault();
+ }
+ }}
+ />
+ <button
+ type="button"
+ className="admin-btn admin-btn-primary admin-filter-action"
+ onClick={() => {
setQ(searchInput);
setPage(1);
}}
>
- <label className="admin-field flex-1">
- <span className="admin-field-label">搜索</span>
- <div className="admin-input-search-wrap">
- <Search className="h-4 w-4" />
- <input
- className="admin-input"
- placeholder="任务类型 / 用户邮箱 / dedupe_key"
- value={searchInput}
- onChange={(e) => setSearchInput(e.target.value)}
- />
- </div>
- </label>
- <button type="submit" className="admin-btn admin-btn-primary">
- 查询
- </button>
- </form>
+ 查询
+ </button>
</Toolbar>
<div className="admin-table-wrap">
@@ -385,11 +400,14 @@ export function QueuesPage() {
</div>
</td>
<td>
- <div className="text-xs">{task.user_email ?? `#${task.requested_by}`}</div>
- </td>
- <td className="max-w-[180px] truncate text-xs text-[#909399]" title={scopeLabel(task)}>
- {scopeLabel(task)}
+ <AdminEntityLink
+ kind="user"
+ id={task.requested_by}
+ label={task.user_email ?? undefined}
+ className="text-xs"
+ />
</td>
+ <td className="max-w-[200px] text-xs">{scopeLinks(task)}</td>
<td>
<span className={`admin-status-pill ${statusClass(task.status)}`}>
{taskStatusLabel(task.status)}
@@ -458,9 +476,11 @@ export function QueuesPage() {
)}
<TaskDetailDialog
- taskId={detailTaskId}
- open={detailOpen}
- onOpenChange={setDetailOpen}
+ taskId={taskDetail.id}
+ open={taskDetail.isOpen}
+ onOpenChange={(open) => {
+ if (!open) taskDetail.close();
+ }}
onCancelled={() => void refreshAll(true)}
/>
</div>
diff --git a/admin/src/pages/SettingsPage.tsx b/admin/src/pages/SettingsPage.tsx
index a4b6e97..836e382 100644
--- a/admin/src/pages/SettingsPage.tsx
+++ b/admin/src/pages/SettingsPage.tsx
@@ -1,98 +1,55 @@
-import { useState } from "react";
-import { Download } from "lucide-react";
-import { toast } from "sonner";
-import { api } from "@/api/client";
-import { AdminConfirmDialog } from "@/components/admin/AdminConfirmDialog";
-import { OssSettingsPanel } from "@/components/settings/OssSettingsPanel";
-import { PaymentSettingsPanel } from "@/components/settings/PaymentSettingsPanel";
-import { RoutingSettingsPanel } from "@/components/settings/RoutingSettingsPanel";
-import { RuntimeSettingsPanel } from "@/components/settings/RuntimeSettingsPanel";
-import { SiteSettingsPanel } from "@/components/settings/SiteSettingsPanel";
-import { PageHeader } from "@/components/ui/page";
-import { cn } from "@/lib/utils";
-
-type SettingsTab = "routing" | "runtime" | "oss" | "payment" | "site";
-
-type ImportEnvRes = {
- imported_fields: string[];
- skipped_secret_fields: string[];
-};
-
-const TABS: { id: SettingsTab; label: string }[] = [
- { id: "routing", label: "模型路由" },
- { id: "runtime", label: "运行参数" },
- { id: "oss", label: "存储 OSS" },
- { id: "payment", label: "支付计费" },
- { id: "site", label: "站点工具" },
-];
-
-// 系统设置:模型、运行参数、OSS、支付、站点
-export function SettingsPage() {
- const [tab, setTab] = useState<SettingsTab>("routing");
- const [reloadKey, setReloadKey] = useState(0);
- const [importOpen, setImportOpen] = useState(false);
- const [importing, setImporting] = useState(false);
-
- // 从服务器 .env 一键导入 flat 配置到 DB
- async function handleImportEnv() {
- setImporting(true);
- try {
- const res = await api<ImportEnvRes>("/api/admin/settings/models/import-env", { method: "POST" });
- setReloadKey((k) => k + 1);
- setImportOpen(false);
- const skipped = res.skipped_secret_fields?.length ?? 0;
- toast.success(
- `已导入 ${res.imported_fields?.length ?? 0} 项${skipped ? `,${skipped} 个空密钥已跳过` : ""}`,
- );
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "导入失败");
- } finally {
- setImporting(false);
- }
- }
-
- return (
- <div className="admin-page">
- <PageHeader
- description="渠道路由、运行参数、OSS / 易支付 / 计费与站点配置;密钥加密存库,留空保存不修改。"
- actions={
- <button
- type="button"
- className="admin-quick-btn !inline-flex !w-auto items-center gap-2 px-4 py-2.5"
- onClick={() => setImportOpen(true)}
- >
- <Download className="h-4 w-4" />
- 从 .env 导入
- </button>
- }
- />
- <div className="flex flex-wrap gap-2">
- {TABS.map(({ id, label }) => (
- <button
- key={id}
- type="button"
- className={cn("admin-tab", tab === id && "is-active")}
- onClick={() => setTab(id)}
- >
- {label}
- </button>
- ))}
- </div>
- {tab === "routing" ? <RoutingSettingsPanel key={reloadKey} /> : null}
- {tab === "runtime" ? <RuntimeSettingsPanel key={reloadKey} /> : null}
- {tab === "oss" ? <OssSettingsPanel key={reloadKey} /> : null}
- {tab === "payment" ? <PaymentSettingsPanel key={reloadKey} /> : null}
- {tab === "site" ? <SiteSettingsPanel key={reloadKey} /> : null}
-
- <AdminConfirmDialog
- open={importOpen}
- title="从 .env 导入配置"
- description="将服务器当前环境变量 / backend/.env 中的 OSS、支付、模型密钥、运行参数等写入数据库并立即生效。已有 DB 配置会被覆盖;.env 中为空的密钥字段会跳过(保留库内原值)。"
- confirmLabel="开始导入"
- loading={importing}
- onOpenChange={setImportOpen}
- onConfirm={() => void handleImportEnv()}
- />
- </div>
- );
-}
+import { useState } from "react";
+import { OssSettingsPanel } from "@/components/settings/OssSettingsPanel";
+import { PaymentSettingsPanel } from "@/components/settings/PaymentSettingsPanel";
+import { RoutingSettingsPanel } from "@/components/settings/RoutingSettingsPanel";
+import { RuntimeSettingsPanel } from "@/components/settings/RuntimeSettingsPanel";
+import { SiteSettingsPanel } from "@/components/settings/SiteSettingsPanel";
+import { cn } from "@/lib/utils";
+
+type SettingsTab = "routing" | "runtime" | "oss" | "payment" | "site";
+
+const TABS: { id: SettingsTab; label: string }[] = [
+ { id: "routing", label: "模型路由" },
+ { id: "runtime", label: "运行参数" },
+ { id: "oss", label: "存储 OSS" },
+ { id: "payment", label: "支付计费" },
+ { id: "site", label: "站点工具" },
+];
+
+// 系统设置:模型、运行参数、OSS、支付、站点
+export function SettingsPage() {
+ const [tab, setTab] = useState<SettingsTab>("routing");
+
+ return (
+ <div className="settings-page admin-page">
+ <div className="settings-head">
+ <p className="settings-head-desc">
+ 渠道路由、运行参数、OSS / 易支付 / 计费与站点配置;密钥加密存库,留空保存不修改。
+ </p>
+ <div className="settings-tabs" role="tablist" aria-label="系统设置分区">
+ {TABS.map(({ id, label }) => (
+ <button
+ key={id}
+ type="button"
+ role="tab"
+ aria-selected={tab === id}
+ className={cn("admin-tab settings-tab", tab === id && "is-active")}
+ onClick={() => setTab(id)}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="settings-main">
+ {tab === "routing" ? <RoutingSettingsPanel /> : null}
+ {tab === "runtime" ? <RuntimeSettingsPanel /> : null}
+ {tab === "oss" ? <OssSettingsPanel /> : null}
+ {tab === "payment" ? <PaymentSettingsPanel /> : null}
+ {tab === "site" ? <SiteSettingsPanel /> : null}
+ </div>
+ </div>
+ );
+}
+
\ No newline at end of file
diff --git a/admin/src/pages/TemplatesPage.tsx b/admin/src/pages/TemplatesPage.tsx
index b35bacf..a6dce38 100644
--- a/admin/src/pages/TemplatesPage.tsx
+++ b/admin/src/pages/TemplatesPage.tsx
@@ -68,7 +68,7 @@ export function TemplatesPage() {
const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
- // 加载模板分页列表
+ // 加载模板分页列表(服务端筛选)
async function load(nextPage = page) {
setLoading(true);
try {
@@ -76,6 +76,10 @@ export function TemplatesPage() {
page: String(nextPage),
page_size: String(TEMPLATE_PAGE_SIZE),
});
+ if (q.trim()) params.set("q", q.trim());
+ if (categoryFilter) params.set("category", categoryFilter);
+ if (statusFilter === "active") params.set("is_active", "true");
+ if (statusFilter === "inactive") params.set("is_active", "false");
setData(await api<ListRes>(`/api/admin/templates?${params}`));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载失败");
@@ -119,21 +123,9 @@ export function TemplatesPage() {
const filteredItems = useMemo(() => {
const items = data?.items ?? [];
- const keyword = q.trim().toLowerCase();
- return items.filter((t) => {
- if (statusFilter === "active" && !t.is_active) return false;
- if (statusFilter === "inactive" && t.is_active) return false;
- if (statusFilter === "premium" && !t.is_premium) return false;
- if (categoryFilter && !(t.category || []).includes(categoryFilter)) return false;
- if (!keyword) return true;
- return (
- t.id.toLowerCase().includes(keyword) ||
- t.name.toLowerCase().includes(keyword) ||
- (t.description || "").toLowerCase().includes(keyword) ||
- (t.category || []).some((c) => c.toLowerCase().includes(keyword))
- );
- });
- }, [data?.items, q, statusFilter, categoryFilter]);
+ if (statusFilter !== "premium") return items;
+ return items.filter((t) => t.is_premium);
+ }, [data?.items, statusFilter]);
// 打开新建弹窗
function openCreate() {
@@ -142,28 +134,33 @@ export function TemplatesPage() {
setOpen(true);
}
- // 打开编辑弹窗
- function openEdit(tpl: AdminTemplate) {
- setEditing(tpl);
- setForm({
- id: tpl.id,
- name: tpl.name,
- description: tpl.description,
- category: (tpl.category || []).join(","),
- preview_cover: tpl.preview_cover,
- style_prefix: tpl.style_prefix,
- character_prompt: seedreamText(tpl.seedream_config, "character_prompt"),
- extra_prompt: seedreamText(tpl.seedream_config, "extra_prompt"),
- negative_prompt: tpl.negative_prompt,
- default_ratio: tpl.default_ratio,
- shot_duration_min: tpl.shot_duration_min,
- shot_duration_max: tpl.shot_duration_max,
- llm_system_addon: tpl.llm_system_addon,
- sort_order: tpl.sort_order,
- is_active: tpl.is_active,
- is_premium: tpl.is_premium,
- });
- setOpen(true);
+ // 打开编辑弹窗(拉取最新配置)
+ async function openEdit(tpl: AdminTemplate) {
+ try {
+ const fresh = await api<AdminTemplate>(`/api/admin/templates/${tpl.id}`);
+ setEditing(fresh);
+ setForm({
+ id: fresh.id,
+ name: fresh.name,
+ description: fresh.description,
+ category: (fresh.category || []).join(","),
+ preview_cover: fresh.preview_cover,
+ style_prefix: fresh.style_prefix,
+ character_prompt: seedreamText(fresh.seedream_config, "character_prompt"),
+ extra_prompt: seedreamText(fresh.seedream_config, "extra_prompt"),
+ negative_prompt: fresh.negative_prompt,
+ default_ratio: fresh.default_ratio,
+ shot_duration_min: fresh.shot_duration_min,
+ shot_duration_max: fresh.shot_duration_max,
+ llm_system_addon: fresh.llm_system_addon,
+ sort_order: fresh.sort_order,
+ is_active: fresh.is_active,
+ is_premium: fresh.is_premium,
+ });
+ setOpen(true);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "加载模板详情失败");
+ }
}
// 创建或更新模板
@@ -288,19 +285,41 @@ export function TemplatesPage() {
placeholder="搜索名称 / ID / 描述 / 分类"
value={q}
onChange={setQ}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ setPage(1);
+ void load(1);
+ }
+ }}
/>
<AdminSelect
className="w-36"
value={statusFilter}
options={STATUS_OPTIONS}
- onChange={setStatusFilter}
+ onChange={(v) => {
+ setStatusFilter(v);
+ setPage(1);
+ }}
/>
<AdminChipFilter
label="分类"
value={categoryFilter}
options={categoryOptions}
- onChange={setCategoryFilter}
+ onChange={(v) => {
+ setCategoryFilter(v);
+ setPage(1);
+ }}
/>
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => {
+ setPage(1);
+ void load(1);
+ }}
+ >
+ 筛选
+ </Button>
</AdminFilterBar>
{loading ? (
@@ -321,7 +340,7 @@ export function TemplatesPage() {
<TemplateCard
key={t.id}
template={t}
- onEdit={openEdit}
+ onEdit={(tpl) => void openEdit(tpl)}
onDelete={(id) => setDeleteTarget(id)}
onToggleActive={(id, v) => void quickPatch(id, { is_active: v })}
onTogglePremium={(id, v) => void quickPatch(id, { is_premium: v })}
diff --git a/admin/src/pages/UsersPage.tsx b/admin/src/pages/UsersPage.tsx
index 391f316..ef23c8a 100644
--- a/admin/src/pages/UsersPage.tsx
+++ b/admin/src/pages/UsersPage.tsx
@@ -1,39 +1,40 @@
import { useEffect, useState } from "react";
import { toast } from "sonner";
-import { api, type AdminUserRow, type PageMeta } from "@/api/client";
+import { api, type AdminStats, type AdminUserRow, type PageMeta } from "@/api/client";
+import { AdminField } from "@/components/admin/AdminField";
+import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
+import { AdminListStats } from "@/components/admin/AdminListStats";
+import { AdminModal } from "@/components/admin/AdminModal";
+import { AdminSearchInput } from "@/components/admin/AdminSearchInput";
+import { UserDetailDrawer } from "@/components/admin/UserDetailDrawer";
import { PaginationBar } from "@/components/PaginationBar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { EmptyState, PageHeader, Toolbar } from "@/components/ui/page";
+import { EmptyState, PageHeader } from "@/components/ui/page";
import { Select } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { useAdminDetailQuery } from "@/hooks/useAdminDetailQuery";
+import { formatAccountId } from "@/lib/admin-account";
import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { fenToYuan } from "@/lib/utils";
type ListRes = { items: AdminUserRow[]; meta: PageMeta };
-// User management: search, plan, balance, unlimited
+// 用户管理:搜索、筛选、只读明细与编辑
export function UsersPage() {
- /*
- * q search query
- * page current page
- * pageSize rows per page
- * data list response
- * loading fetch state
- * editing user being edited
- * form edit form state
- * saving patch in flight
- */
const [q, setQ] = useState("");
+ const [planFilter, setPlanFilter] = useState("");
+ const [roleFilter, setRoleFilter] = useState("");
+ const [unlimitedFilter, setUnlimitedFilter] = useState("");
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
const [data, setData] = useState<ListRes | null>(null);
+ const [stats, setStats] = useState<AdminStats | null>(null);
const [loading, setLoading] = useState(false);
const [editing, setEditing] = useState<AdminUserRow | null>(null);
+ const [detailUser, setDetailUser] = useState<AdminUserRow | null>(null);
const [form, setForm] = useState({
plan: "free",
billing_unlimited: false,
@@ -42,8 +43,8 @@ export function UsersPage() {
balance_note: "",
});
const [saving, setSaving] = useState(false);
+ const userDetail = useAdminDetailQuery("user");
- // Load paginated users
async function load(nextPage = page, nextQ = q, nextSize = pageSize) {
setLoading(true);
try {
@@ -52,6 +53,10 @@ export function UsersPage() {
page_size: String(nextSize),
});
if (nextQ.trim()) params.set("q", nextQ.trim());
+ if (planFilter) params.set("plan", planFilter);
+ if (roleFilter) params.set("role", roleFilter);
+ if (unlimitedFilter === "yes") params.set("billing_unlimited", "true");
+ if (unlimitedFilter === "no") params.set("billing_unlimited", "false");
const res = await api<ListRes>(`/api/admin/users?${params}`);
setData(res);
} catch (err) {
@@ -63,10 +68,18 @@ export function UsersPage() {
useEffect(() => {
void load();
+ void api<AdminStats>("/api/admin/stats?days=7")
+ .then(setStats)
+ .catch(() => undefined);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page, pageSize]);
- // Open edit dialog for a user
+ useEffect(() => {
+ if (!userDetail.id || !data?.items) return;
+ const hit = data.items.find((u) => u.id === userDetail.id);
+ if (hit) setDetailUser(hit);
+ }, [userDetail.id, data?.items]);
+
function openEdit(user: AdminUserRow) {
setEditing(user);
setForm({
@@ -78,7 +91,6 @@ export function UsersPage() {
});
}
- // Save user patch
async function saveEdit() {
if (!editing) return;
setSaving(true);
@@ -105,58 +117,91 @@ export function UsersPage() {
}
}
+ function applyFilters() {
+ setPage(1);
+ void load(1, q, pageSize);
+ }
+
return (
<div className="admin-list-page">
<PageHeader description="搜索用户,调整套餐、余额与无限额度" />
- <Toolbar>
- <Input
- className="max-w-xs"
- placeholder="搜索邮箱 / 昵称"
+ <AdminFilterBar>
+ <AdminSearchInput
value={q}
- onChange={(e) => setQ(e.target.value)}
+ onChange={setQ}
+ placeholder="搜索邮箱 / 昵称 / 账号 ID"
onKeyDown={(e) => {
- if (e.key === "Enter") {
- setPage(1);
- void load(1, q);
- }
+ if (e.key === "Enter") applyFilters();
}}
/>
- <Button
- variant="soft"
- onClick={() => {
- setPage(1);
- void load(1, q);
- }}
- >
+ <Select value={planFilter} onChange={(e) => setPlanFilter(e.target.value)}>
+ <option value="">全部套餐</option>
+ <option value="free">free</option>
+ <option value="pro">pro</option>
+ <option value="team">team</option>
+ </Select>
+ <Select value={roleFilter} onChange={(e) => setRoleFilter(e.target.value)}>
+ <option value="">全部角色</option>
+ <option value="user">user</option>
+ <option value="admin">admin</option>
+ </Select>
+ <Select value={unlimitedFilter} onChange={(e) => setUnlimitedFilter(e.target.value)}>
+ <option value="">无限额度</option>
+ <option value="yes">是</option>
+ <option value="no">否</option>
+ </Select>
+ <Button size="sm" className="admin-filter-action" onClick={applyFilters}>
搜索
</Button>
- </Toolbar>
+ </AdminFilterBar>
+
+ <AdminListStats
+ items={[
+ { label: "总用户数", value: stats?.user_count ?? data?.meta.total ?? (loading ? "…" : "—") },
+ {
+ label: "本月调用",
+ value: stats?.usage_calls_month ?? (loading ? "…" : "—"),
+ hint: stats ? `今日 ${stats.usage_calls_today ?? 0} 次` : undefined,
+ },
+ {
+ label: "累计调用",
+ value: stats?.usage_calls_total ?? (loading ? "…" : "—"),
+ },
+ ]}
+ />
<div className="space-y-3">
<Table>
<TableHeader>
<TableRow>
- <TableHead>ID</TableHead>
+ <TableHead>账号 ID</TableHead>
<TableHead>邮箱</TableHead>
<TableHead>昵称</TableHead>
+ <TableHead>手机</TableHead>
<TableHead>套餐</TableHead>
<TableHead>余额</TableHead>
+ <TableHead>冻结</TableHead>
+ <TableHead>剩余额度</TableHead>
<TableHead>角色</TableHead>
<TableHead>无限</TableHead>
- <TableHead className="w-[100px]">操作</TableHead>
+ <TableHead>注册时间</TableHead>
+ <TableHead className="w-[140px]">操作</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{(data?.items ?? []).map((u) => (
<TableRow key={u.id}>
- <TableCell className="text-[#909399]">{u.id}</TableCell>
+ <TableCell className="font-mono text-xs text-[#909399]">{formatAccountId(u.id)}</TableCell>
<TableCell className="font-medium">{u.email}</TableCell>
- <TableCell>{u.nickname}</TableCell>
+ <TableCell>{u.nickname || "—"}</TableCell>
+ <TableCell className="text-xs">{u.phone || "—"}</TableCell>
<TableCell>
<Badge variant="info">{u.plan}</Badge>
</TableCell>
<TableCell className="tabular-nums">¥{fenToYuan(u.balance_fen)}</TableCell>
+ <TableCell className="tabular-nums">¥{fenToYuan(u.frozen_fen)}</TableCell>
+ <TableCell>{u.quota_left}</TableCell>
<TableCell>
<Badge variant={u.role === "admin" ? "success" : "secondary"}>{u.role}</Badge>
</TableCell>
@@ -165,16 +210,31 @@ export function UsersPage() {
{u.billing_unlimited ? "是" : "否"}
</Badge>
</TableCell>
+ <TableCell className="text-xs text-muted-foreground">
+ {u.created_at ? new Date(u.created_at).toLocaleString() : "—"}
+ </TableCell>
<TableCell>
- <Button size="sm" variant="outline" onClick={() => openEdit(u)}>
- 编辑
- </Button>
+ <div className="flex gap-1">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ setDetailUser(u);
+ userDetail.open(u.id);
+ }}
+ >
+ 查看
+ </Button>
+ <Button size="sm" variant="ghost" onClick={() => openEdit(u)}>
+ 编辑
+ </Button>
+ </div>
</TableCell>
</TableRow>
))}
{!loading && (data?.items.length ?? 0) === 0 && (
<TableRow>
- <TableCell colSpan={8} className="p-0">
+ <TableCell colSpan={12} className="p-0">
<EmptyState title="暂无用户" description="试试换个关键词搜索" />
</TableCell>
</TableRow>
@@ -196,59 +256,66 @@ export function UsersPage() {
)}
</div>
- <Dialog open={!!editing} onOpenChange={(open) => !open && setEditing(null)}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>编辑用户</DialogTitle>
- <DialogDescription>{editing?.email}</DialogDescription>
- </DialogHeader>
- <div className="space-y-4">
- <div className="space-y-2">
- <Label>套餐</Label>
- <Select value={form.plan} onChange={(e) => setForm((f) => ({ ...f, plan: e.target.value }))}>
- <option value="free">free</option>
- <option value="pro">pro</option>
- <option value="team">team</option>
- </Select>
- </div>
- <div className="space-y-2">
- <Label>角色</Label>
- <Select value={form.role} onChange={(e) => setForm((f) => ({ ...f, role: e.target.value }))}>
- <option value="user">user</option>
- <option value="admin">admin</option>
- </Select>
- </div>
- <div className="space-y-2">
- <Label>余额(元)</Label>
- <Input
- value={form.balance_yuan}
- onChange={(e) => setForm((f) => ({ ...f, balance_yuan: e.target.value }))}
- />
- </div>
- <div className="space-y-2">
- <Label>调账备注</Label>
- <Input
- value={form.balance_note}
- onChange={(e) => setForm((f) => ({ ...f, balance_note: e.target.value }))}
- placeholder="可选"
- />
- </div>
- <div className="flex items-center justify-between rounded-xl bg-[#fafbfc] px-3 py-3">
- <div>
- <Label>无限额度</Label>
- <p className="mt-1 text-xs text-[#909399]">billing_unlimited</p>
- </div>
- <Switch
- checked={form.billing_unlimited}
- onCheckedChange={(v) => setForm((f) => ({ ...f, billing_unlimited: v }))}
- />
+ <UserDetailDrawer
+ userId={userDetail.id}
+ open={userDetail.isOpen}
+ onOpenChange={(open) => {
+ if (!open) userDetail.close();
+ }}
+ initialUser={detailUser}
+ />
+
+ <AdminModal
+ open={!!editing}
+ onOpenChange={(open) => !open && setEditing(null)}
+ size="md"
+ title="编辑用户"
+ subtitle={editing?.email}
+ footer={
+ <Button className="w-full sm:w-auto" disabled={saving} onClick={() => void saveEdit()}>
+ {saving ? "保存中…" : "保存修改"}
+ </Button>
+ }
+ >
+ <div className="admin-form-grid admin-form-grid--2">
+ <AdminField label="套餐">
+ <Select value={form.plan} onChange={(e) => setForm((f) => ({ ...f, plan: e.target.value }))}>
+ <option value="free">free</option>
+ <option value="pro">pro</option>
+ <option value="team">team</option>
+ </Select>
+ </AdminField>
+ <AdminField label="角色">
+ <Select value={form.role} onChange={(e) => setForm((f) => ({ ...f, role: e.target.value }))}>
+ <option value="user">user</option>
+ <option value="admin">admin</option>
+ </Select>
+ </AdminField>
+ <AdminField label="余额(元)">
+ <Input
+ value={form.balance_yuan}
+ onChange={(e) => setForm((f) => ({ ...f, balance_yuan: e.target.value }))}
+ />
+ </AdminField>
+ <AdminField label="调账备注" hint="可选">
+ <Input
+ value={form.balance_note}
+ onChange={(e) => setForm((f) => ({ ...f, balance_note: e.target.value }))}
+ placeholder="管理员备注"
+ />
+ </AdminField>
+ <div className="admin-form-switch-row admin-form-grid--full">
+ <div>
+ <strong>无限额度</strong>
+ <p>开启后该用户调用不计费上限</p>
</div>
- <Button className="w-full" disabled={saving} onClick={() => void saveEdit()}>
- {saving ? "保存中…" : "保存修改"}
- </Button>
+ <Switch
+ checked={form.billing_unlimited}
+ onCheckedChange={(v) => setForm((f) => ({ ...f, billing_unlimited: v }))}
+ />
</div>
- </DialogContent>
- </Dialog>
+ </div>
+ </AdminModal>
</div>
);
}
diff --git a/admin/src/pages/WorksPage.tsx b/admin/src/pages/WorksPage.tsx
index df4b63e..578fd8e 100644
--- a/admin/src/pages/WorksPage.tsx
+++ b/admin/src/pages/WorksPage.tsx
@@ -1,6 +1,12 @@
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { api, type AdminWork, type PageMeta } from "@/api/client";
+import { AdminDetailMeta, AdminDetailSection } from "@/components/admin/AdminDetailLayout";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
+import { AdminModal } from "@/components/admin/AdminModal";
+import { AdminSearchInput } from "@/components/admin/AdminSearchInput";
+import { AdminUserSearchSelect } from "@/components/admin/AdminUserSearchSelect";
import { PaginationBar } from "@/components/PaginationBar";
import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { Badge } from "@/components/ui/badge";
@@ -8,29 +14,36 @@ import { Button } from "@/components/ui/button";
import { Select } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { PageHeader } from "@/components/ui/page";
+import { useAdminDetailQuery } from "@/hooks/useAdminDetailQuery";
import { auditStatusLabel, visibilityLabel } from "@/lib/statusLabels";
type ListRes = { items: AdminWork[]; meta: PageMeta };
-// Work audit: visibility + audit_status
+function coverSrc(url: string | null | undefined): string {
+ const trimmed = (url || "").trim();
+ if (!trimmed) return "";
+ if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) return trimmed;
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
+}
+
+// 作品审核:搜索、预览与只读详情
export function WorksPage() {
- /*
- * auditStatus filter
- * visibility filter
- * page current page
- * data list response
- */
const [auditStatus, setAuditStatus] = useState("");
const [visibility, setVisibility] = useState("");
+ const [q, setQ] = useState("");
+ const [userId, setUserId] = useState<number | null>(null);
const [page, setPage] = useState(1);
const [data, setData] = useState<ListRes | null>(null);
+ const [detail, setDetail] = useState<AdminWork | null>(null);
+ const workDetail = useAdminDetailQuery("work");
- // Load works
async function load(nextPage = page) {
try {
const params = new URLSearchParams({ page: String(nextPage), page_size: String(DEFAULT_PAGE_SIZE) });
if (auditStatus) params.set("audit_status", auditStatus);
if (visibility) params.set("visibility", visibility);
+ if (q.trim()) params.set("q", q.trim());
+ if (userId) params.set("user_id", String(userId));
setData(await api<ListRes>(`/api/admin/works?${params}`));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载失败");
@@ -42,7 +55,12 @@ export function WorksPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page]);
- // Patch a work field
+ useEffect(() => {
+ if (!workDetail.id || !data?.items) return;
+ const hit = data.items.find((w) => w.id === workDetail.id);
+ if (hit) setDetail(hit);
+ }, [workDetail.id, data?.items]);
+
async function patchWork(id: number, body: { visibility?: string; audit_status?: string }) {
try {
await api(`/api/admin/works/${id}`, { method: "PATCH", body: JSON.stringify(body) });
@@ -53,24 +71,43 @@ export function WorksPage() {
}
}
+ function openWork(work: AdminWork) {
+ setDetail(work);
+ workDetail.open(work.id);
+ }
+
return (
<div className="admin-list-page">
<PageHeader description="调整可见性与审核状态" />
- <div className="admin-filter-bar">
- <Select className="w-40" value={auditStatus} onChange={(e) => setAuditStatus(e.target.value)}>
+ <AdminFilterBar>
+ <AdminSearchInput
+ value={q}
+ onChange={setQ}
+ placeholder="搜索标题"
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ setPage(1);
+ void load(1);
+ }
+ }}
+ />
+ <AdminUserSearchSelect value={userId} onChange={(id) => setUserId(id)} />
+ <Select value={auditStatus} onChange={(e) => setAuditStatus(e.target.value)}>
<option value="">全部审核</option>
<option value="pending">待审核</option>
<option value="passed">已通过</option>
<option value="rejected">已拒绝</option>
</Select>
- <Select className="w-40" value={visibility} onChange={(e) => setVisibility(e.target.value)}>
+ <Select value={visibility} onChange={(e) => setVisibility(e.target.value)}>
<option value="">全部可见性</option>
<option value="public">公开</option>
<option value="private">私密</option>
<option value="unlisted">不公开列出</option>
</Select>
<Button
+ size="sm"
variant="secondary"
+ className="admin-filter-action"
onClick={() => {
setPage(1);
void load(1);
@@ -78,11 +115,12 @@ export function WorksPage() {
>
筛选
</Button>
- </div>
+ </AdminFilterBar>
<div className="rounded-lg border bg-background">
<Table>
<TableHeader>
<TableRow>
+ <TableHead>封面</TableHead>
<TableHead>ID</TableHead>
<TableHead>标题</TableHead>
<TableHead>用户</TableHead>
@@ -95,14 +133,37 @@ export function WorksPage() {
<TableBody>
{(data?.items ?? []).map((w) => (
<TableRow key={w.id}>
+ <TableCell>
+ {w.cover_url ? (
+ <button type="button" onClick={() => openWork(w)} className="block">
+ <img src={coverSrc(w.cover_url)} alt={w.title} className="admin-thumb" loading="lazy" />
+ </button>
+ ) : (
+ "—"
+ )}
+ </TableCell>
<TableCell>{w.id}</TableCell>
- <TableCell className="max-w-[200px] truncate">{w.title}</TableCell>
- <TableCell>{w.user_email ?? w.user_id}</TableCell>
+ <TableCell className="max-w-[200px] truncate">
+ <button type="button" className="admin-link text-left" onClick={() => openWork(w)}>
+ {w.title}
+ </button>
+ </TableCell>
+ <TableCell>
+ <AdminEntityLink kind="user" id={w.user_id} label={w.user_email ?? undefined} />
+ </TableCell>
<TableCell>
<Badge variant="secondary">{visibilityLabel(w.visibility)}</Badge>
</TableCell>
<TableCell>
- <Badge variant={w.audit_status === "rejected" ? "destructive" : w.audit_status === "passed" ? "success" : "warning"}>
+ <Badge
+ variant={
+ w.audit_status === "rejected"
+ ? "destructive"
+ : w.audit_status === "passed"
+ ? "success"
+ : "warning"
+ }
+ >
{auditStatusLabel(w.audit_status)}
</Badge>
</TableCell>
@@ -111,6 +172,9 @@ export function WorksPage() {
</TableCell>
<TableCell>
<div className="flex flex-wrap gap-1">
+ <Button size="sm" variant="outline" onClick={() => openWork(w)}>
+ 详情
+ </Button>
<Button size="sm" variant="outline" onClick={() => void patchWork(w.id, { audit_status: "passed" })}>
通过
</Button>
@@ -147,6 +211,74 @@ export function WorksPage() {
onPageChange={setPage}
/>
)}
+
+ <AdminModal
+ open={workDetail.isOpen && !!detail}
+ onOpenChange={(open) => {
+ if (!open) {
+ setDetail(null);
+ workDetail.close();
+ }
+ }}
+ size="lg"
+ title={detail?.title ?? "作品详情"}
+ subtitle={detail ? `作品 #${detail.id}` : undefined}
+ >
+ {detail ? (
+ <>
+ {(detail.cover_url || detail.video_url) ? (
+ <AdminDetailSection title="媒体预览">
+ <div className="admin-detail-media">
+ {detail.cover_url ? (
+ <img src={coverSrc(detail.cover_url)} alt={detail.title} />
+ ) : null}
+ {detail.video_url ? (
+ <video src={detail.video_url} controls className="max-w-full" />
+ ) : null}
+ </div>
+ </AdminDetailSection>
+ ) : null}
+ <AdminDetailSection title="基本信息">
+ <AdminDetailMeta
+ items={[
+ {
+ label: "用户",
+ value: (
+ <AdminEntityLink
+ kind="user"
+ id={detail.user_id}
+ label={detail.user_email ?? undefined}
+ />
+ ),
+ },
+ {
+ label: "关联项目",
+ value: detail.project_id ? (
+ <AdminEntityLink kind="project" id={detail.project_id} />
+ ) : (
+ "—"
+ ),
+ },
+ { label: "可见性", value: visibilityLabel(detail.visibility) },
+ { label: "审核", value: auditStatusLabel(detail.audit_status) },
+ {
+ label: "发布时间",
+ value: new Date(detail.published_at).toLocaleString(),
+ full: true,
+ },
+ ]}
+ />
+ </AdminDetailSection>
+ {detail.video_url ? (
+ <Button size="sm" variant="outline" asChild>
+ <a href={detail.video_url} target="_blank" rel="noreferrer">
+ 新窗口打开视频
+ </a>
+ </Button>
+ ) : null}
+ </>
+ ) : null}
+ </AdminModal>
</div>
);
}
diff --git a/admin/src/pages/dashboard/DashboardFilters.tsx b/admin/src/pages/dashboard/DashboardFilters.tsx
new file mode 100644
index 0000000..0e3adc6
--- /dev/null
+++ b/admin/src/pages/dashboard/DashboardFilters.tsx
@@ -0,0 +1,111 @@
+import { AdminChipFilter } from "@/components/admin/AdminChipFilter";
+import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
+
+/** 仪表盘筛选维度 */
+export type DashboardDays = "1" | "7" | "14" | "30";
+export type DashboardDomain = "all" | "drama" | "kepu" | "api" | "tools" | "studio";
+export type DashboardCapability = "all" | "llm" | "image" | "video" | "tts";
+export type DashboardMetric = "charge" | "cost" | "calls";
+
+export type DashboardFilterState = {
+ days: DashboardDays;
+ domain: DashboardDomain;
+ capability: DashboardCapability;
+ metric: DashboardMetric;
+};
+
+export const DEFAULT_DASHBOARD_FILTERS: DashboardFilterState = {
+ days: "7",
+ domain: "all",
+ capability: "all",
+ metric: "charge",
+};
+
+const DAY_OPTIONS = [
+ { value: "1", label: "今日" },
+ { value: "7", label: "近 7 日" },
+ { value: "14", label: "近 14 日" },
+ { value: "30", label: "近 30 日" },
+];
+
+/** 图表 / 区块标题用的时间范围文案 */
+export function dashboardRangeLabel(days: DashboardDays): string {
+ if (days === "1") return "今日";
+ return `近 ${days} 日`;
+}
+
+const DOMAIN_OPTIONS = [
+ { value: "all", label: "全部领域" },
+ { value: "drama", label: "漫剧" },
+ { value: "kepu", label: "AI短视频" },
+ { value: "api", label: "开放 API" },
+ { value: "tools", label: "工具" },
+ { value: "studio", label: "工作室" },
+];
+
+const CAPABILITY_OPTIONS = [
+ { value: "all", label: "全部能力" },
+ { value: "llm", label: "LLM" },
+ { value: "image", label: "生图" },
+ { value: "video", label: "视频" },
+ { value: "tts", label: "配音" },
+];
+
+const METRIC_OPTIONS = [
+ { value: "charge", label: "扣费" },
+ { value: "cost", label: "成本" },
+ { value: "calls", label: "调用" },
+];
+
+type DashboardFiltersProps = {
+ value: DashboardFilterState;
+ onChange: (next: DashboardFilterState) => void;
+};
+
+/** 仪表盘用量筛选条(两行紧凑布局) */
+export function DashboardFilters({ value, onChange }: DashboardFiltersProps) {
+ const patch = (partial: Partial<DashboardFilterState>) => onChange({ ...value, ...partial });
+
+ return (
+ <AdminFilterBar className="admin-dashboard-filters">
+ <AdminChipFilter
+ label="时间维度"
+ value={value.days}
+ options={DAY_OPTIONS}
+ onChange={(days) => patch({ days: days as DashboardDays })}
+ className="admin-chip-filter--segment"
+ />
+ <AdminChipFilter
+ label="业务领域"
+ value={value.domain}
+ options={DOMAIN_OPTIONS}
+ onChange={(domain) => patch({ domain: domain as DashboardDomain })}
+ className="admin-chip-filter--segment"
+ />
+ <AdminChipFilter
+ label="能力类型"
+ value={value.capability}
+ options={CAPABILITY_OPTIONS}
+ onChange={(capability) => patch({ capability: capability as DashboardCapability })}
+ className="admin-chip-filter--segment"
+ />
+ <AdminChipFilter
+ label="统计指标"
+ value={value.metric}
+ options={METRIC_OPTIONS}
+ onChange={(metric) => patch({ metric: metric as DashboardMetric })}
+ className="admin-chip-filter--segment"
+ />
+ </AdminFilterBar>
+ );
+}
+
+/** 拼接 stats API 查询串(指标仅前端使用) */
+export function buildStatsQuery(filters: DashboardFilterState): string {
+ const params = new URLSearchParams({
+ days: filters.days,
+ domain: filters.domain,
+ capability: filters.capability,
+ });
+ return `/api/admin/stats?${params.toString()}`;
+}
diff --git a/admin/src/pages/dashboard/DashboardKpiCard.tsx b/admin/src/pages/dashboard/DashboardKpiCard.tsx
new file mode 100644
index 0000000..16b0cae
--- /dev/null
+++ b/admin/src/pages/dashboard/DashboardKpiCard.tsx
@@ -0,0 +1,42 @@
+import type { LucideIcon } from "lucide-react";
+import type { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+
+type DashboardKpiTone = "teal" | "blue" | "purple" | "sand";
+
+type DashboardKpiCardProps = {
+ label: string;
+ value: ReactNode;
+ hint?: string;
+ icon: LucideIcon;
+ tone?: DashboardKpiTone;
+ trend?: string;
+ className?: string;
+};
+
+/** 仪表盘渐变 KPI 卡片 */
+export function DashboardKpiCard({
+ label,
+ value,
+ hint,
+ icon: Icon,
+ tone = "teal",
+ trend,
+ className,
+}: DashboardKpiCardProps) {
+ return (
+ <div className={cn("admin-dashboard-kpi", `tone-${tone}`, className)}>
+ <div className="admin-dashboard-kpi-icon">
+ <Icon className="h-5 w-5" />
+ </div>
+ <div className="admin-dashboard-kpi-label">{label}</div>
+ <div className="admin-dashboard-kpi-value">{value}</div>
+ {hint || trend ? (
+ <div className="admin-dashboard-kpi-foot">
+ {hint ? <span>{hint}</span> : null}
+ {trend ? <span className="admin-dashboard-kpi-trend">{trend}</span> : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/admin/src/pages/dashboard/DashboardSectionTabs.tsx b/admin/src/pages/dashboard/DashboardSectionTabs.tsx
new file mode 100644
index 0000000..e7f1790
--- /dev/null
+++ b/admin/src/pages/dashboard/DashboardSectionTabs.tsx
@@ -0,0 +1,52 @@
+import { BarChart3, Clapperboard, LayoutDashboard, Wallet } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+/** 仪表盘主板块 */
+export type DashboardSection = "overview" | "usage" | "finance" | "projects";
+
+const SECTIONS: {
+ id: DashboardSection;
+ label: string;
+ desc: string;
+ icon: typeof LayoutDashboard;
+}[] = [
+ { id: "overview", label: "经营概览", desc: "核心指标与趋势", icon: LayoutDashboard },
+ { id: "usage", label: "用量分析", desc: "调用与分布", icon: BarChart3 },
+ { id: "finance", label: "财务账单", desc: "充值与成本", icon: Wallet },
+ { id: "projects", label: "项目运维", desc: "生产与快捷入口", icon: Clapperboard },
+];
+
+type DashboardSectionTabsProps = {
+ value: DashboardSection;
+ onChange: (next: DashboardSection) => void;
+};
+
+/** 仪表盘板块切换 */
+export function DashboardSectionTabs({ value, onChange }: DashboardSectionTabsProps) {
+ return (
+ <div className="admin-dashboard-section-tabs" role="tablist" aria-label="仪表盘板块">
+ {SECTIONS.map((item) => {
+ const active = value === item.id;
+ const Icon = item.icon;
+ return (
+ <button
+ key={item.id}
+ type="button"
+ role="tab"
+ aria-selected={active}
+ className={cn("admin-dashboard-section-tab", active && "is-active")}
+ onClick={() => onChange(item.id)}
+ >
+ <span className="admin-dashboard-section-tab-icon">
+ <Icon className="h-4 w-4" />
+ </span>
+ <span className="admin-dashboard-section-tab-text">
+ <span className="admin-dashboard-section-tab-label">{item.label}</span>
+ <span className="admin-dashboard-section-tab-desc">{item.desc}</span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/admin/src/pages/dashboard/UsageDistributionChart.tsx b/admin/src/pages/dashboard/UsageDistributionChart.tsx
new file mode 100644
index 0000000..91c6440
--- /dev/null
+++ b/admin/src/pages/dashboard/UsageDistributionChart.tsx
@@ -0,0 +1,142 @@
+import {
+ Bar,
+ BarChart,
+ Cell,
+ Pie,
+ PieChart,
+ ResponsiveContainer,
+ Tooltip,
+ XAxis,
+ YAxis,
+} from "recharts";
+import type { AdminUsageBucket } from "@/api/client";
+import { fenToYuan } from "@/lib/utils";
+import type { DashboardMetric } from "./DashboardFilters";
+
+const CHART_COLORS = [
+ "var(--admin-forest)",
+ "var(--admin-accent)",
+ "#5a9e86",
+ "#7ab89f",
+ "#9fd0b8",
+ "#c2e2d4",
+];
+
+type UsageDistributionChartProps = {
+ data: AdminUsageBucket[];
+ metric: DashboardMetric;
+ labelForKey: (key: string) => string;
+ variant?: "bar" | "donut";
+};
+
+function readMetric(row: AdminUsageBucket, metric: DashboardMetric): number {
+ if (metric === "cost") return row.cost_fen ?? 0;
+ if (metric === "calls") return row.calls;
+ return row.charge_fen;
+}
+
+function formatMetric(value: number, metric: DashboardMetric): string {
+ if (metric === "calls") return String(value);
+ return `¥${fenToYuan(value)}`;
+}
+
+/** 能力 / 领域分布图 */
+export function UsageDistributionChart({
+ data,
+ metric,
+ labelForKey,
+ variant = "bar",
+}: UsageDistributionChartProps) {
+ const chartData = data
+ .map((row) => ({
+ key: row.key,
+ name: labelForKey(row.key),
+ value: readMetric(row, metric),
+ }))
+ .filter((row) => row.value > 0);
+
+ if (chartData.length === 0) {
+ return <div className="admin-chart-empty">暂无分布数据</div>;
+ }
+
+ if (variant === "donut") {
+ return (
+ <div className="admin-chart-wrap admin-chart-wrap--compact">
+ <ResponsiveContainer width="100%" height={220}>
+ <PieChart>
+ <Pie
+ data={chartData}
+ dataKey="value"
+ nameKey="name"
+ innerRadius={52}
+ outerRadius={78}
+ paddingAngle={2}
+ stroke="none"
+ >
+ {chartData.map((row, idx) => (
+ <Cell key={row.key} fill={CHART_COLORS[idx % CHART_COLORS.length]} />
+ ))}
+ </Pie>
+ <Tooltip
+ contentStyle={{
+ background: "var(--admin-card)",
+ border: "1px solid var(--admin-border)",
+ borderRadius: "10px",
+ fontSize: "12px",
+ }}
+ formatter={(value, _name, item) => {
+ const row = item?.payload as { name?: string } | undefined;
+ return [formatMetric(Number(value ?? 0), metric), row?.name ?? ""];
+ }}
+ />
+ </PieChart>
+ </ResponsiveContainer>
+ <div className="admin-chart-legend">
+ {chartData.map((row, idx) => (
+ <div key={row.key} className="admin-chart-legend-item">
+ <span
+ className="admin-chart-legend-dot"
+ style={{ background: CHART_COLORS[idx % CHART_COLORS.length] }}
+ />
+ <span className="admin-chart-legend-label">{row.name}</span>
+ <span className="admin-chart-legend-value">{formatMetric(row.value, metric)}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="admin-chart-wrap admin-chart-wrap--compact">
+ <ResponsiveContainer width="100%" height={220}>
+ <BarChart data={chartData} layout="vertical" margin={{ top: 0, right: 8, left: 0, bottom: 0 }}>
+ <XAxis type="number" hide />
+ <YAxis
+ type="category"
+ dataKey="name"
+ width={72}
+ tick={{ fill: "var(--admin-muted)", fontSize: 11 }}
+ axisLine={false}
+ tickLine={false}
+ />
+ <Tooltip
+ cursor={{ fill: "var(--admin-accent-soft)" }}
+ contentStyle={{
+ background: "var(--admin-card)",
+ border: "1px solid var(--admin-border)",
+ borderRadius: "10px",
+ fontSize: "12px",
+ }}
+ formatter={(value) => [formatMetric(Number(value ?? 0), metric), "数值"]}
+ />
+ <Bar dataKey="value" radius={[0, 6, 6, 0]} maxBarSize={18}>
+ {chartData.map((row, idx) => (
+ <Cell key={row.key} fill={CHART_COLORS[idx % CHART_COLORS.length]} />
+ ))}
+ </Bar>
+ </BarChart>
+ </ResponsiveContainer>
+ </div>
+ );
+}
diff --git a/admin/src/pages/dashboard/UsageTrendChart.tsx b/admin/src/pages/dashboard/UsageTrendChart.tsx
new file mode 100644
index 0000000..d91402b
--- /dev/null
+++ b/admin/src/pages/dashboard/UsageTrendChart.tsx
@@ -0,0 +1,104 @@
+import {
+ Area,
+ AreaChart,
+ CartesianGrid,
+ ResponsiveContainer,
+ Tooltip,
+ XAxis,
+ YAxis,
+} from "recharts";
+import type { AdminDailyUsage } from "@/api/client";
+import { fenToYuan } from "@/lib/utils";
+import type { DashboardMetric } from "./DashboardFilters";
+
+type UsageTrendChartProps = {
+ data: AdminDailyUsage[];
+ metric: DashboardMetric;
+};
+
+function metricLabel(metric: DashboardMetric): string {
+ if (metric === "cost") return "上游成本";
+ if (metric === "calls") return "调用次数";
+ return "扣费金额";
+}
+
+function readMetric(row: AdminDailyUsage, metric: DashboardMetric): number {
+ if (metric === "cost") return row.cost_fen ?? 0;
+ if (metric === "calls") return row.calls;
+ return row.charge_fen;
+}
+
+function formatMetric(value: number, metric: DashboardMetric): string {
+ if (metric === "calls") return String(value);
+ return `¥${fenToYuan(value)}`;
+}
+
+function shortDate(iso: string): string {
+ const parts = iso.split("-");
+ return parts.length === 3 ? `${parts[1]}/${parts[2]}` : iso;
+}
+
+/** 用量趋势面积图 */
+export function UsageTrendChart({ data, metric }: UsageTrendChartProps) {
+ const chartData = data.map((row) => ({
+ date: row.date,
+ label: shortDate(row.date),
+ value: readMetric(row, metric),
+ }));
+
+ if (chartData.length === 0) {
+ return <div className="admin-chart-empty">暂无趋势数据</div>;
+ }
+
+ return (
+ <div className="admin-chart-wrap">
+ <ResponsiveContainer width="100%" height={280}>
+ <AreaChart data={chartData} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
+ <defs>
+ <linearGradient id="usageTrendFill" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stopColor="var(--admin-accent)" stopOpacity={0.35} />
+ <stop offset="100%" stopColor="var(--admin-accent)" stopOpacity={0.02} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid stroke="var(--admin-border)" strokeDasharray="3 3" vertical={false} />
+ <XAxis
+ dataKey="label"
+ tick={{ fill: "var(--admin-muted)", fontSize: 11 }}
+ axisLine={false}
+ tickLine={false}
+ minTickGap={16}
+ />
+ <YAxis
+ tick={{ fill: "var(--admin-muted)", fontSize: 11 }}
+ axisLine={false}
+ tickLine={false}
+ width={metric === "calls" ? 36 : 52}
+ tickFormatter={(v) => (metric === "calls" ? String(v) : `¥${fenToYuan(Number(v))}`)}
+ />
+ <Tooltip
+ contentStyle={{
+ background: "var(--admin-card)",
+ border: "1px solid var(--admin-border)",
+ borderRadius: "10px",
+ fontSize: "12px",
+ }}
+ labelFormatter={(_, payload) => {
+ const row = payload?.[0]?.payload as { date?: string } | undefined;
+ return row?.date ?? "";
+ }}
+ formatter={(value) => [formatMetric(Number(value ?? 0), metric), metricLabel(metric)]}
+ />
+ <Area
+ type="monotone"
+ dataKey="value"
+ stroke="var(--admin-forest)"
+ strokeWidth={2}
+ fill="url(#usageTrendFill)"
+ dot={false}
+ activeDot={{ r: 4, fill: "var(--admin-forest)" }}
+ />
+ </AreaChart>
+ </ResponsiveContainer>
+ </div>
+ );
+}
diff --git a/admin/src/pages/drama/DramaAssetDetailPage.tsx b/admin/src/pages/drama/DramaAssetDetailPage.tsx
new file mode 100644
index 0000000..408f88c
--- /dev/null
+++ b/admin/src/pages/drama/DramaAssetDetailPage.tsx
@@ -0,0 +1,116 @@
+import { useEffect, useState } from "react";
+import { ArrowLeft } from "lucide-react";
+import { Link, useNavigate, useParams } from "react-router-dom";
+import { toast } from "sonner";
+import { api, type AdminDramaAsset } from "@/api/client";
+import { AdminDetailMeta, AdminDetailSection } from "@/components/admin/AdminDetailLayout";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { Button } from "@/components/ui/button";
+import { dramaAssetTypeLabel, formatDramaGenerationStatus } from "@/lib/dramaLabels";
+
+/** 漫剧资产详情二级页 */
+export function DramaAssetDetailPage() {
+ const { assetId } = useParams<{ assetId: string }>();
+ const navigate = useNavigate();
+ const [detail, setDetail] = useState<AdminDramaAsset | null>(null);
+ const [loading, setLoading] = useState(true);
+ const id = Number(assetId);
+
+ useEffect(() => {
+ if (!id || Number.isNaN(id)) {
+ navigate("/drama-assets", { replace: true });
+ return;
+ }
+ setLoading(true);
+ void api<AdminDramaAsset>(`/api/admin/drama-assets/${id}`)
+ .then(setDetail)
+ .catch((err) => {
+ toast.error(err instanceof Error ? err.message : "加载失败");
+ navigate("/drama-assets", { replace: true });
+ })
+ .finally(() => setLoading(false));
+ }, [id, navigate]);
+
+ if (loading && !detail) {
+ return <div className="admin-detail-page-loading">加载中…</div>;
+ }
+ if (!detail) return null;
+
+ const mediaUrl = detail.cover || detail.url;
+
+ return (
+ <div className="admin-detail-page">
+ <div className="admin-detail-page-toolbar">
+ <Button variant="ghost" size="sm" className="admin-detail-back" asChild>
+ <Link to="/drama-assets">
+ <ArrowLeft className="h-4 w-4" />
+ 返回资产库
+ </Link>
+ </Button>
+ <div className="admin-detail-page-heading">
+ <h2 className="admin-detail-page-title">
+ 资产 #{detail.id} · {detail.name || "未命名"}
+ </h2>
+ <p className="admin-detail-page-sub">
+ {dramaAssetTypeLabel(detail.type)} ·{" "}
+ <AdminEntityLink kind="drama" id={detail.project_id} label={detail.project_title ?? undefined} />
+ </p>
+ </div>
+ <div className="admin-detail-page-actions">
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-projects/${detail.project_id}`}>打开项目</Link>
+ </Button>
+ </div>
+ </div>
+
+ {mediaUrl ? (
+ <AdminDetailSection title="媒体预览">
+ <div className="admin-detail-media">
+ {detail.asset_type === "video" ? (
+ <video src={mediaUrl} controls className="max-w-full" />
+ ) : (
+ <img src={mediaUrl} alt={detail.name ?? ""} />
+ )}
+ </div>
+ </AdminDetailSection>
+ ) : null}
+
+ <AdminDetailSection title="基本信息">
+ <AdminDetailMeta
+ items={[
+ { label: "类型", value: dramaAssetTypeLabel(detail.type) },
+ { label: "媒体类型", value: detail.asset_type },
+ { label: "derive_id", value: detail.derive_id || "—" },
+ {
+ label: "用户",
+ value: detail.user_id ? (
+ <AdminEntityLink kind="user" id={detail.user_id} label={detail.user_email ?? undefined} />
+ ) : (
+ "—"
+ ),
+ },
+ {
+ label: "所属项目",
+ value: <AdminEntityLink kind="drama" id={detail.project_id} label={detail.project_title ?? undefined} />,
+ },
+ { label: "生成状态", value: formatDramaGenerationStatus(detail.generation_status) },
+ {
+ label: "创建时间",
+ value: detail.created_at ? new Date(detail.created_at).toLocaleString() : "—",
+ },
+ {
+ label: "更新时间",
+ value: detail.updated_at ? new Date(detail.updated_at).toLocaleString() : "—",
+ },
+ ]}
+ />
+ </AdminDetailSection>
+
+ {detail.params ? (
+ <AdminDetailSection title="参数 JSON">
+ <pre className="admin-json-preview">{JSON.stringify(detail.params, null, 2)}</pre>
+ </AdminDetailSection>
+ ) : null}
+ </div>
+ );
+}
diff --git a/admin/src/pages/drama/DramaAssetsPage.tsx b/admin/src/pages/drama/DramaAssetsPage.tsx
new file mode 100644
index 0000000..f1ec0df
--- /dev/null
+++ b/admin/src/pages/drama/DramaAssetsPage.tsx
@@ -0,0 +1,171 @@
+import { useEffect, useState } from "react";
+import { Link, useSearchParams } from "react-router-dom";
+import { toast } from "sonner";
+import { api, type AdminDramaAsset, type PageMeta } from "@/api/client";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
+import { AdminUserSearchSelect } from "@/components/admin/AdminUserSearchSelect";
+import { PaginationBar } from "@/components/PaginationBar";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { PageHeader } from "@/components/ui/page";
+import {
+ DRAMA_GENERATION_STATUSES,
+ dramaAssetTypeLabel,
+ formatDramaGenerationStatus,
+} from "@/lib/dramaLabels";
+import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
+
+type ListRes = { items: AdminDramaAsset[]; meta: PageMeta };
+
+const ASSET_TYPES = ["character", "scene", "prop", "material", "none"] as const;
+
+/** 全站漫剧资产库列表 */
+export function DramaAssetsPage() {
+ const [searchParams] = useSearchParams();
+ const initialProjectId = searchParams.get("project_id");
+
+ const [page, setPage] = useState(1);
+ const [q, setQ] = useState("");
+ const [userId, setUserId] = useState<number | null>(null);
+ const [projectId, setProjectId] = useState(initialProjectId ?? "");
+ const [type, setType] = useState("");
+ const [generationStatus, setGenerationStatus] = useState("");
+ const [data, setData] = useState<ListRes | null>(null);
+
+ async function load(nextPage = page) {
+ try {
+ const params = new URLSearchParams({ page: String(nextPage), page_size: String(DEFAULT_PAGE_SIZE) });
+ if (q.trim()) params.set("q", q.trim());
+ if (userId) params.set("user_id", String(userId));
+ if (projectId.trim()) params.set("project_id", projectId.trim());
+ if (type.trim()) params.set("type", type.trim());
+ if (generationStatus.trim()) params.set("generation_status", generationStatus.trim());
+ setData(await api<ListRes>(`/api/admin/drama-assets?${params}`));
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "加载失败");
+ }
+ }
+
+ useEffect(() => {
+ void load();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [page]);
+
+ return (
+ <div className="admin-list-page">
+ <PageHeader description="全站漫剧资产:角色、场景、道具等,可按项目与用户筛选" />
+ <AdminFilterBar>
+ <Input placeholder="名称 / derive_id" value={q} onChange={(e) => setQ(e.target.value)} />
+ <AdminUserSearchSelect value={userId} onChange={setUserId} />
+ <Input placeholder="项目 ID" value={projectId} onChange={(e) => setProjectId(e.target.value)} />
+ <select className="admin-native-select" value={type} onChange={(e) => setType(e.target.value)}>
+ <option value="">全部类型</option>
+ {ASSET_TYPES.map((t) => (
+ <option key={t} value={t}>
+ {dramaAssetTypeLabel(t)}
+ </option>
+ ))}
+ </select>
+ <select
+ className="admin-native-select"
+ value={generationStatus}
+ onChange={(e) => setGenerationStatus(e.target.value)}
+ >
+ <option value="">全部生成状态</option>
+ {DRAMA_GENERATION_STATUSES.map((s) => (
+ <option key={s} value={s}>
+ {formatDramaGenerationStatus(s)}
+ </option>
+ ))}
+ </select>
+ <Button
+ size="sm"
+ variant="secondary"
+ className="admin-filter-action"
+ onClick={() => {
+ setPage(1);
+ void load(1);
+ }}
+ >
+ 筛选
+ </Button>
+ </AdminFilterBar>
+
+ <div className="admin-table-wrap">
+ <table>
+ <thead>
+ <tr>
+ <th>ID</th>
+ <th>预览</th>
+ <th>名称</th>
+ <th>类型</th>
+ <th>项目</th>
+ <th>用户</th>
+ <th>生成</th>
+ <th>更新时间</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ {(data?.items ?? []).map((row) => (
+ <tr key={row.id}>
+ <td>{row.id}</td>
+ <td>
+ {row.cover || row.url ? (
+ <img
+ src={row.cover || row.url || ""}
+ alt={row.name ?? ""}
+ className="admin-thumb"
+ />
+ ) : (
+ "—"
+ )}
+ </td>
+ <td className="max-w-[140px] truncate">{row.name || "—"}</td>
+ <td>{dramaAssetTypeLabel(row.type)}</td>
+ <td>
+ <AdminEntityLink kind="drama" id={row.project_id} label={row.project_title ?? undefined} />
+ </td>
+ <td>
+ {row.user_id ? (
+ <AdminEntityLink kind="user" id={row.user_id} label={row.user_email ?? undefined} />
+ ) : (
+ "—"
+ )}
+ </td>
+ <td className="text-xs text-[var(--admin-muted)]">
+ {formatDramaGenerationStatus(row.generation_status)}
+ </td>
+ <td className="text-xs text-[var(--admin-muted)]">
+ {row.updated_at ? new Date(row.updated_at).toLocaleString() : "—"}
+ </td>
+ <td>
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-assets/${row.id}`}>查看</Link>
+ </Button>
+ </td>
+ </tr>
+ ))}
+ {(data?.items.length ?? 0) === 0 ? (
+ <tr>
+ <td colSpan={9} className="!text-center text-[var(--admin-muted)]">
+ 暂无资产
+ </td>
+ </tr>
+ ) : null}
+ </tbody>
+ </table>
+ </div>
+
+ {data?.meta ? (
+ <PaginationBar
+ page={data.meta.page}
+ pageSize={data.meta.page_size}
+ total={data.meta.total}
+ onPageChange={setPage}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/admin/src/pages/drama/DramaEpisodeDetailPage.tsx b/admin/src/pages/drama/DramaEpisodeDetailPage.tsx
new file mode 100644
index 0000000..ae33be3
--- /dev/null
+++ b/admin/src/pages/drama/DramaEpisodeDetailPage.tsx
@@ -0,0 +1,141 @@
+import { useEffect, useState } from "react";
+import { ArrowLeft } from "lucide-react";
+import { Link, useNavigate, useParams } from "react-router-dom";
+import { toast } from "sonner";
+import { api, type AdminDramaEpisode } from "@/api/client";
+import {
+ AdminDetailMeta,
+ AdminDetailSection,
+ AdminDetailTableWrap,
+} from "@/components/admin/AdminDetailLayout";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { Button } from "@/components/ui/button";
+import { formatDramaGenerationStatus } from "@/lib/dramaLabels";
+
+/** 漫剧分集详情:含分镜列表 */
+export function DramaEpisodeDetailPage() {
+ const { episodeId } = useParams<{ episodeId: string }>();
+ const navigate = useNavigate();
+ const [detail, setDetail] = useState<AdminDramaEpisode | null>(null);
+ const [loading, setLoading] = useState(true);
+ const id = Number(episodeId);
+
+ useEffect(() => {
+ if (!id || Number.isNaN(id)) {
+ navigate("/drama-episodes", { replace: true });
+ return;
+ }
+ setLoading(true);
+ void api<AdminDramaEpisode>(`/api/admin/drama-episodes/${id}`)
+ .then(setDetail)
+ .catch((err) => {
+ toast.error(err instanceof Error ? err.message : "加载失败");
+ navigate("/drama-episodes", { replace: true });
+ })
+ .finally(() => setLoading(false));
+ }, [id, navigate]);
+
+ if (loading && !detail) {
+ return <div className="admin-detail-page-loading">加载中…</div>;
+ }
+ if (!detail) return null;
+
+ return (
+ <div className="admin-detail-page">
+ <div className="admin-detail-page-toolbar">
+ <Button variant="ghost" size="sm" className="admin-detail-back" asChild>
+ <Link to="/drama-episodes">
+ <ArrowLeft className="h-4 w-4" />
+ 返回分集列表
+ </Link>
+ </Button>
+ <div className="admin-detail-page-heading">
+ <h2 className="admin-detail-page-title">
+ 分集 #{detail.id} · {detail.name}
+ </h2>
+ <p className="admin-detail-page-sub">
+ <AdminEntityLink kind="drama" id={detail.project_id} label={detail.project_title ?? undefined} />
+ </p>
+ </div>
+ <div className="admin-detail-page-actions">
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-projects/${detail.project_id}?tab=episodes`}>打开项目</Link>
+ </Button>
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-fragments?episode_id=${detail.id}`}>全部分镜</Link>
+ </Button>
+ </div>
+ </div>
+
+ <AdminDetailSection title="基本信息">
+ <AdminDetailMeta
+ items={[
+ {
+ label: "用户",
+ value: detail.user_id ? (
+ <AdminEntityLink kind="user" id={detail.user_id} label={detail.user_email ?? undefined} />
+ ) : (
+ "—"
+ ),
+ },
+ {
+ label: "所属项目",
+ value: <AdminEntityLink kind="drama" id={detail.project_id} label={detail.project_title ?? undefined} />,
+ },
+ { label: "分镜数", value: detail.fragment_count },
+ { label: "分镜计划", value: detail.fragment_plan_status || "—" },
+ {
+ label: "更新时间",
+ value: detail.updated_at ? new Date(detail.updated_at).toLocaleString() : "—",
+ },
+ ]}
+ />
+ </AdminDetailSection>
+
+ <AdminDetailSection title={`分镜列表(${(detail.fragments ?? []).length})`}>
+ <AdminDetailTableWrap>
+ <table>
+ <thead>
+ <tr>
+ <th>序号</th>
+ <th>ID</th>
+ <th>内容</th>
+ <th>时长</th>
+ <th>生成</th>
+ <th>资产引用</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ {(detail.fragments ?? []).length === 0 ? (
+ <tr>
+ <td colSpan={7} className="!text-center text-[var(--admin-muted)]">
+ 暂无分镜
+ </td>
+ </tr>
+ ) : (
+ (detail.fragments ?? []).map((f) => (
+ <tr key={f.id}>
+ <td>{f.sort_order}</td>
+ <td>{f.id}</td>
+ <td className="max-w-[240px] truncate">{f.content || "—"}</td>
+ <td>{f.duration_sec != null ? `${f.duration_sec}s` : "—"}</td>
+ <td className="text-xs text-[var(--admin-muted)]">
+ {formatDramaGenerationStatus(f.generation_status)}
+ </td>
+ <td>{f.asset_ref_count}</td>
+ <td>
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-fragments/${f.id}`}>查看</Link>
+ </Button>
+ </td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </AdminDetailTableWrap>
+ </AdminDetailSection>
+ </div>
+ );
+}
diff --git a/admin/src/pages/drama/DramaEpisodesPage.tsx b/admin/src/pages/drama/DramaEpisodesPage.tsx
new file mode 100644
index 0000000..74aa892
--- /dev/null
+++ b/admin/src/pages/drama/DramaEpisodesPage.tsx
@@ -0,0 +1,126 @@
+import { useEffect, useState } from "react";
+import { Link, useSearchParams } from "react-router-dom";
+import { toast } from "sonner";
+import { api, type AdminDramaEpisode, type PageMeta } from "@/api/client";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
+import { AdminUserSearchSelect } from "@/components/admin/AdminUserSearchSelect";
+import { PaginationBar } from "@/components/PaginationBar";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { PageHeader } from "@/components/ui/page";
+import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
+
+type ListRes = { items: AdminDramaEpisode[]; meta: PageMeta };
+
+/** 全站漫剧分集列表 */
+export function DramaEpisodesPage() {
+ const [searchParams] = useSearchParams();
+ const initialProjectId = searchParams.get("project_id");
+
+ const [page, setPage] = useState(1);
+ const [q, setQ] = useState("");
+ const [userId, setUserId] = useState<number | null>(null);
+ const [projectId, setProjectId] = useState(initialProjectId ?? "");
+ const [data, setData] = useState<ListRes | null>(null);
+
+ async function load(nextPage = page) {
+ try {
+ const params = new URLSearchParams({ page: String(nextPage), page_size: String(DEFAULT_PAGE_SIZE) });
+ if (q.trim()) params.set("q", q.trim());
+ if (userId) params.set("user_id", String(userId));
+ if (projectId.trim()) params.set("project_id", projectId.trim());
+ setData(await api<ListRes>(`/api/admin/drama-episodes?${params}`));
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "加载失败");
+ }
+ }
+
+ useEffect(() => {
+ void load();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [page]);
+
+ return (
+ <div className="admin-list-page">
+ <PageHeader description="全站漫剧分集:按项目与用户筛选,可进入分镜明细" />
+ <AdminFilterBar>
+ <Input placeholder="集名 / 项目标题" value={q} onChange={(e) => setQ(e.target.value)} />
+ <AdminUserSearchSelect value={userId} onChange={setUserId} />
+ <Input placeholder="项目 ID" value={projectId} onChange={(e) => setProjectId(e.target.value)} />
+ <Button
+ size="sm"
+ variant="secondary"
+ className="admin-filter-action"
+ onClick={() => {
+ setPage(1);
+ void load(1);
+ }}
+ >
+ 筛选
+ </Button>
+ </AdminFilterBar>
+
+ <div className="admin-table-wrap">
+ <table>
+ <thead>
+ <tr>
+ <th>ID</th>
+ <th>名称</th>
+ <th>项目</th>
+ <th>用户</th>
+ <th>分镜数</th>
+ <th>分镜计划</th>
+ <th>更新时间</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ {(data?.items ?? []).map((row) => (
+ <tr key={row.id}>
+ <td>{row.id}</td>
+ <td className="max-w-[160px] truncate">{row.name}</td>
+ <td>
+ <AdminEntityLink kind="drama" id={row.project_id} label={row.project_title ?? undefined} />
+ </td>
+ <td>
+ {row.user_id ? (
+ <AdminEntityLink kind="user" id={row.user_id} label={row.user_email ?? undefined} />
+ ) : (
+ "—"
+ )}
+ </td>
+ <td>{row.fragment_count}</td>
+ <td className="text-xs text-[var(--admin-muted)]">{row.fragment_plan_status || "—"}</td>
+ <td className="text-xs text-[var(--admin-muted)]">
+ {row.updated_at ? new Date(row.updated_at).toLocaleString() : "—"}
+ </td>
+ <td>
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-episodes/${row.id}`}>查看</Link>
+ </Button>
+ </td>
+ </tr>
+ ))}
+ {(data?.items.length ?? 0) === 0 ? (
+ <tr>
+ <td colSpan={8} className="!text-center text-[var(--admin-muted)]">
+ 暂无分集
+ </td>
+ </tr>
+ ) : null}
+ </tbody>
+ </table>
+ </div>
+
+ {data?.meta ? (
+ <PaginationBar
+ page={data.meta.page}
+ pageSize={data.meta.page_size}
+ total={data.meta.total}
+ onPageChange={setPage}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/admin/src/pages/drama/DramaFragmentDetailPage.tsx b/admin/src/pages/drama/DramaFragmentDetailPage.tsx
new file mode 100644
index 0000000..7467313
--- /dev/null
+++ b/admin/src/pages/drama/DramaFragmentDetailPage.tsx
@@ -0,0 +1,120 @@
+import { useEffect, useState } from "react";
+import { ArrowLeft } from "lucide-react";
+import { Link, useNavigate, useParams } from "react-router-dom";
+import { toast } from "sonner";
+import { api, type AdminDramaFragment } from "@/api/client";
+import {
+ AdminDetailMeta,
+ AdminDetailSection,
+} from "@/components/admin/AdminDetailLayout";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { Button } from "@/components/ui/button";
+import { formatDramaGenerationStatus } from "@/lib/dramaLabels";
+
+/** 漫剧分镜详情 */
+export function DramaFragmentDetailPage() {
+ const { fragmentId } = useParams<{ fragmentId: string }>();
+ const navigate = useNavigate();
+ const [detail, setDetail] = useState<AdminDramaFragment | null>(null);
+ const [loading, setLoading] = useState(true);
+ const id = Number(fragmentId);
+
+ useEffect(() => {
+ if (!id || Number.isNaN(id)) {
+ navigate("/drama-fragments", { replace: true });
+ return;
+ }
+ setLoading(true);
+ void api<AdminDramaFragment>(`/api/admin/drama-fragments/${id}`)
+ .then(setDetail)
+ .catch((err) => {
+ toast.error(err instanceof Error ? err.message : "加载失败");
+ navigate("/drama-fragments", { replace: true });
+ })
+ .finally(() => setLoading(false));
+ }, [id, navigate]);
+
+ if (loading && !detail) {
+ return <div className="admin-detail-page-loading">加载中…</div>;
+ }
+ if (!detail) return null;
+
+ return (
+ <div className="admin-detail-page">
+ <div className="admin-detail-page-toolbar">
+ <Button variant="ghost" size="sm" className="admin-detail-back" asChild>
+ <Link to="/drama-fragments">
+ <ArrowLeft className="h-4 w-4" />
+ 返回分镜列表
+ </Link>
+ </Button>
+ <div className="admin-detail-page-heading">
+ <h2 className="admin-detail-page-title">分镜 #{detail.id}</h2>
+ <p className="admin-detail-page-sub">
+ 分集 {detail.episode_name ?? detail.episode_id} ·{" "}
+ <AdminEntityLink kind="drama" id={detail.project_id} label={detail.project_title ?? undefined} />
+ </p>
+ </div>
+ <div className="admin-detail-page-actions">
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-episodes/${detail.episode_id}`}>打开分集</Link>
+ </Button>
+ </div>
+ </div>
+
+ {(detail.cover || detail.video) ? (
+ <AdminDetailSection title="媒体预览">
+ <div className="admin-detail-media">
+ {detail.video ? (
+ <video src={detail.video} controls className="max-w-full" />
+ ) : detail.cover ? (
+ <img src={detail.cover} alt="" />
+ ) : null}
+ </div>
+ </AdminDetailSection>
+ ) : null}
+
+ <AdminDetailSection title="基本信息">
+ <AdminDetailMeta
+ items={[
+ { label: "序号", value: detail.sort_order },
+ {
+ label: "分集",
+ value: (
+ <Link to={`/drama-episodes/${detail.episode_id}`} className="admin-link">
+ {detail.episode_name ?? `分集#${detail.episode_id}`}
+ </Link>
+ ),
+ },
+ {
+ label: "项目",
+ value: <AdminEntityLink kind="drama" id={detail.project_id} label={detail.project_title ?? undefined} />,
+ },
+ { label: "时长", value: detail.duration_sec != null ? `${detail.duration_sec}s` : "—" },
+ { label: "生成状态", value: formatDramaGenerationStatus(detail.generation_status) },
+ { label: "资产引用数", value: detail.asset_ref_count },
+ { label: "剧本文本", value: detail.content || "—", full: true },
+ ]}
+ />
+ </AdminDetailSection>
+
+ {(detail.asset_ids ?? []).length > 0 ? (
+ <AdminDetailSection title="关联资产">
+ <div className="flex flex-wrap gap-2">
+ {(detail.asset_ids ?? []).map((assetId) => (
+ <Button key={assetId} size="sm" variant="outline" asChild>
+ <Link to={`/drama-assets/${assetId}`}>资产 #{assetId}</Link>
+ </Button>
+ ))}
+ </div>
+ </AdminDetailSection>
+ ) : null}
+
+ {detail.params ? (
+ <AdminDetailSection title="参数 JSON">
+ <pre className="admin-json-preview">{JSON.stringify(detail.params, null, 2)}</pre>
+ </AdminDetailSection>
+ ) : null}
+ </div>
+ );
+}
diff --git a/admin/src/pages/drama/DramaFragmentsPage.tsx b/admin/src/pages/drama/DramaFragmentsPage.tsx
new file mode 100644
index 0000000..0346ab2
--- /dev/null
+++ b/admin/src/pages/drama/DramaFragmentsPage.tsx
@@ -0,0 +1,141 @@
+import { useEffect, useState } from "react";
+import { Link, useSearchParams } from "react-router-dom";
+import { toast } from "sonner";
+import { api, type AdminDramaFragment, type PageMeta } from "@/api/client";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
+import { AdminUserSearchSelect } from "@/components/admin/AdminUserSearchSelect";
+import { PaginationBar } from "@/components/PaginationBar";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { PageHeader } from "@/components/ui/page";
+import { DRAMA_GENERATION_STATUSES, formatDramaGenerationStatus } from "@/lib/dramaLabels";
+import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
+
+type ListRes = { items: AdminDramaFragment[]; meta: PageMeta };
+
+/** 全站漫剧分镜列表 */
+export function DramaFragmentsPage() {
+ const [searchParams] = useSearchParams();
+ const initialProjectId = searchParams.get("project_id");
+ const initialEpisodeId = searchParams.get("episode_id");
+
+ const [page, setPage] = useState(1);
+ const [q, setQ] = useState("");
+ const [userId, setUserId] = useState<number | null>(null);
+ const [projectId, setProjectId] = useState(initialProjectId ?? "");
+ const [episodeId, setEpisodeId] = useState(initialEpisodeId ?? "");
+ const [generationStatus, setGenerationStatus] = useState("");
+ const [data, setData] = useState<ListRes | null>(null);
+
+ async function load(nextPage = page) {
+ try {
+ const params = new URLSearchParams({ page: String(nextPage), page_size: String(DEFAULT_PAGE_SIZE) });
+ if (q.trim()) params.set("q", q.trim());
+ if (userId) params.set("user_id", String(userId));
+ if (projectId.trim()) params.set("project_id", projectId.trim());
+ if (episodeId.trim()) params.set("episode_id", episodeId.trim());
+ if (generationStatus.trim()) params.set("generation_status", generationStatus.trim());
+ setData(await api<ListRes>(`/api/admin/drama-fragments?${params}`));
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "加载失败");
+ }
+ }
+
+ useEffect(() => {
+ void load();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [page]);
+
+ return (
+ <div className="admin-list-page">
+ <PageHeader description="全站漫剧分镜:按项目、分集筛选,查看生成状态与资产引用" />
+ <AdminFilterBar>
+ <Input placeholder="内容 / 集名 / 项目" value={q} onChange={(e) => setQ(e.target.value)} />
+ <AdminUserSearchSelect value={userId} onChange={setUserId} />
+ <Input placeholder="项目 ID" value={projectId} onChange={(e) => setProjectId(e.target.value)} />
+ <Input placeholder="分集 ID" value={episodeId} onChange={(e) => setEpisodeId(e.target.value)} />
+ <select
+ className="admin-native-select"
+ value={generationStatus}
+ onChange={(e) => setGenerationStatus(e.target.value)}
+ >
+ <option value="">全部生成状态</option>
+ {DRAMA_GENERATION_STATUSES.map((s) => (
+ <option key={s} value={s}>
+ {formatDramaGenerationStatus(s)}
+ </option>
+ ))}
+ </select>
+ <Button
+ size="sm"
+ variant="secondary"
+ className="admin-filter-action"
+ onClick={() => {
+ setPage(1);
+ void load(1);
+ }}
+ >
+ 筛选
+ </Button>
+ </AdminFilterBar>
+
+ <div className="admin-table-wrap">
+ <table>
+ <thead>
+ <tr>
+ <th>ID</th>
+ <th>序号</th>
+ <th>内容</th>
+ <th>分集</th>
+ <th>项目</th>
+ <th>时长</th>
+ <th>生成</th>
+ <th>资产</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ {(data?.items ?? []).map((row) => (
+ <tr key={row.id}>
+ <td>{row.id}</td>
+ <td>{row.sort_order}</td>
+ <td className="max-w-[200px] truncate">{row.content || "—"}</td>
+ <td className="max-w-[100px] truncate">{row.episode_name || row.episode_id}</td>
+ <td>
+ <AdminEntityLink kind="drama" id={row.project_id} label={row.project_title ?? undefined} />
+ </td>
+ <td>{row.duration_sec != null ? `${row.duration_sec}s` : "—"}</td>
+ <td className="text-xs text-[var(--admin-muted)]">
+ {formatDramaGenerationStatus(row.generation_status)}
+ </td>
+ <td>{row.asset_ref_count}</td>
+ <td>
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-fragments/${row.id}`}>查看</Link>
+ </Button>
+ </td>
+ </tr>
+ ))}
+ {(data?.items.length ?? 0) === 0 ? (
+ <tr>
+ <td colSpan={9} className="!text-center text-[var(--admin-muted)]">
+ 暂无分镜
+ </td>
+ </tr>
+ ) : null}
+ </tbody>
+ </table>
+ </div>
+
+ {data?.meta ? (
+ <PaginationBar
+ page={data.meta.page}
+ pageSize={data.meta.page_size}
+ total={data.meta.total}
+ onPageChange={setPage}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/admin/src/pages/drama/DramaProjectDetailPage.tsx b/admin/src/pages/drama/DramaProjectDetailPage.tsx
new file mode 100644
index 0000000..ac67a20
--- /dev/null
+++ b/admin/src/pages/drama/DramaProjectDetailPage.tsx
@@ -0,0 +1,274 @@
+import { useEffect, useState } from "react";
+import { ArrowLeft } from "lucide-react";
+import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom";
+import { toast } from "sonner";
+import { api, type AdminDramaProject } from "@/api/client";
+import {
+ AdminDetailMeta,
+ AdminDetailSection,
+ AdminDetailStatGrid,
+ AdminDetailTableWrap,
+} from "@/components/admin/AdminDetailLayout";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { Button } from "@/components/ui/button";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { dramaAssetTypeLabel, formatDramaGenerationStatus } from "@/lib/dramaLabels";
+import { taskStatusLabel, taskTypeLabel } from "@/lib/statusLabels";
+import { fenToYuan } from "@/lib/utils";
+
+const TABS = ["overview", "episodes", "assets", "tasks"] as const;
+type TabKey = (typeof TABS)[number];
+
+function isTabKey(value: string | null): value is TabKey {
+ return TABS.includes(value as TabKey);
+}
+
+/** 漫剧项目二级详情:概览 / 分集 / 资产 / 任务 */
+export function DramaProjectDetailPage() {
+ const { projectId } = useParams<{ projectId: string }>();
+ const navigate = useNavigate();
+ const [searchParams, setSearchParams] = useSearchParams();
+ const tabParam = searchParams.get("tab");
+ const tab: TabKey = isTabKey(tabParam) ? tabParam : "overview";
+
+ const [detail, setDetail] = useState<AdminDramaProject | null>(null);
+ const [loading, setLoading] = useState(true);
+
+ const id = Number(projectId);
+
+ useEffect(() => {
+ if (!id || Number.isNaN(id)) {
+ navigate("/drama-projects", { replace: true });
+ return;
+ }
+ setLoading(true);
+ void api<AdminDramaProject>(`/api/admin/drama-projects/${id}`)
+ .then(setDetail)
+ .catch((err) => {
+ toast.error(err instanceof Error ? err.message : "加载失败");
+ navigate("/drama-projects", { replace: true });
+ })
+ .finally(() => setLoading(false));
+ }, [id, navigate]);
+
+ function setTab(next: TabKey) {
+ const params = new URLSearchParams(searchParams);
+ if (next === "overview") params.delete("tab");
+ else params.set("tab", next);
+ setSearchParams(params, { replace: true });
+ }
+
+ const usage = detail?.usage;
+
+ if (loading && !detail) {
+ return <div className="admin-detail-page-loading">加载中…</div>;
+ }
+ if (!detail) return null;
+
+ return (
+ <div className="admin-detail-page">
+ <div className="admin-detail-page-toolbar">
+ <Button variant="ghost" size="sm" className="admin-detail-back" asChild>
+ <Link to="/drama-projects">
+ <ArrowLeft className="h-4 w-4" />
+ 返回列表
+ </Link>
+ </Button>
+ <div className="admin-detail-page-heading">
+ <h2 className="admin-detail-page-title">
+ 漫剧 #{detail.id} · {detail.title}
+ </h2>
+ <p className="admin-detail-page-sub">
+ <AdminEntityLink kind="user" id={detail.user_id} label={detail.user_email ?? undefined} />
+ {detail.summary_status ? ` · 摘要 ${detail.summary_status}` : ""}
+ </p>
+ </div>
+ <div className="admin-detail-page-actions">
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-assets?project_id=${detail.id}`}>查看资产库</Link>
+ </Button>
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-episodes?project_id=${detail.id}`}>查看分集</Link>
+ </Button>
+ </div>
+ </div>
+
+ <Tabs value={tab} onValueChange={(v) => setTab(v as TabKey)} className="admin-detail-tabs">
+ <TabsList className="admin-detail-tabs-list">
+ <TabsTrigger value="overview">概览</TabsTrigger>
+ <TabsTrigger value="episodes">分集({detail.episode_count ?? 0})</TabsTrigger>
+ <TabsTrigger value="assets">资产({detail.asset_count ?? 0})</TabsTrigger>
+ <TabsTrigger value="tasks">任务({(detail.recent_tasks ?? []).length})</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="overview" className="admin-detail-tab-panel">
+ <AdminDetailSection title="基本信息">
+ <AdminDetailMeta
+ items={[
+ {
+ label: "用户",
+ value: (
+ <AdminEntityLink
+ kind="user"
+ id={detail.user_id}
+ label={detail.user_email ?? undefined}
+ />
+ ),
+ },
+ { label: "描述", value: detail.description || "无描述", full: true },
+ { label: "摘要状态", value: detail.summary_status || "—" },
+ { label: "分集状态", value: detail.episode_content_status || "—" },
+ { label: "资产抽取", value: detail.assets_seed_status || "—" },
+ { label: "集数", value: detail.episode_count ?? 0 },
+ { label: "资产数", value: detail.asset_count ?? 0 },
+ { label: "分镜数", value: detail.fragment_count ?? 0 },
+ {
+ label: "更新时间",
+ value: detail.updated_at ? new Date(detail.updated_at).toLocaleString() : "—",
+ full: true,
+ },
+ ]}
+ />
+ </AdminDetailSection>
+
+ <AdminDetailSection title="费用汇总">
+ <AdminDetailStatGrid
+ items={[
+ { label: "扣费", value: `¥${fenToYuan(usage?.charge_fen ?? detail.charge_fen ?? 0)}` },
+ { label: "成本", value: `¥${fenToYuan(usage?.cost_fen ?? 0)}` },
+ { label: "调用", value: usage?.calls ?? 0 },
+ {
+ label: "图/视/LLM/TTS",
+ value: `${usage?.image_gens ?? 0}/${usage?.video_gens ?? 0}/${usage?.llm_calls ?? 0}/${usage?.tts_gens ?? 0}`,
+ },
+ ]}
+ />
+ </AdminDetailSection>
+ </TabsContent>
+
+ <TabsContent value="episodes" className="admin-detail-tab-panel">
+ <AdminDetailSection title={`分集列表(${(detail.episodes ?? []).length})`}>
+ <AdminDetailTableWrap>
+ <table>
+ <thead>
+ <tr>
+ <th>ID</th>
+ <th>名称</th>
+ <th>分镜数</th>
+ <th>分镜计划</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ {(detail.episodes ?? []).length === 0 ? (
+ <tr>
+ <td colSpan={5} className="!text-center text-[var(--admin-muted)]">
+ 暂无分集
+ </td>
+ </tr>
+ ) : (
+ (detail.episodes ?? []).map((ep) => (
+ <tr key={ep.id}>
+ <td>{ep.id}</td>
+ <td>{ep.name}</td>
+ <td>{ep.fragment_count}</td>
+ <td>{ep.fragment_plan_status || "—"}</td>
+ <td>
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-episodes/${ep.id}`}>查看</Link>
+ </Button>
+ </td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </AdminDetailTableWrap>
+ </AdminDetailSection>
+ </TabsContent>
+
+ <TabsContent value="assets" className="admin-detail-tab-panel">
+ <AdminDetailSection title={`项目资产(${(detail.assets ?? []).length})`}>
+ <AdminDetailTableWrap>
+ <table>
+ <thead>
+ <tr>
+ <th>ID</th>
+ <th>类型</th>
+ <th>名称</th>
+ <th>封面</th>
+ <th>生成</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ {(detail.assets ?? []).length === 0 ? (
+ <tr>
+ <td colSpan={6} className="!text-center text-[var(--admin-muted)]">
+ 暂无资产
+ </td>
+ </tr>
+ ) : (
+ (detail.assets ?? []).map((a) => (
+ <tr key={a.id}>
+ <td>{a.id}</td>
+ <td>{dramaAssetTypeLabel(a.type)}</td>
+ <td className="max-w-[160px] truncate">{a.name || "—"}</td>
+ <td>{a.has_cover ? "有基准图" : "—"}</td>
+ <td>{formatDramaGenerationStatus(a.generation_status)}</td>
+ <td>
+ <Button size="sm" variant="outline" asChild>
+ <Link to={`/drama-assets/${a.id}`}>查看</Link>
+ </Button>
+ </td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </AdminDetailTableWrap>
+ </AdminDetailSection>
+ </TabsContent>
+
+ <TabsContent value="tasks" className="admin-detail-tab-panel">
+ <AdminDetailSection title={`关联任务(最近 ${(detail.recent_tasks ?? []).length})`}>
+ <AdminDetailTableWrap>
+ <table>
+ <thead>
+ <tr>
+ <th>ID</th>
+ <th>类型</th>
+ <th>状态</th>
+ <th>已扣 / 预估</th>
+ </tr>
+ </thead>
+ <tbody>
+ {(detail.recent_tasks ?? []).length === 0 ? (
+ <tr>
+ <td colSpan={4} className="!text-center text-[var(--admin-muted)]">
+ 暂无任务
+ </td>
+ </tr>
+ ) : (
+ (detail.recent_tasks ?? []).map((t) => (
+ <tr key={t.id}>
+ <td>
+ <AdminEntityLink kind="task" id={t.id} />
+ </td>
+ <td>{taskTypeLabel(t.task_type)}</td>
+ <td>{taskStatusLabel(t.status)}</td>
+ <td>
+ ¥{fenToYuan(t.billing_charged_fen)} / ¥{fenToYuan(t.billing_estimate_fen)}
+ </td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </AdminDetailTableWrap>
+ </AdminDetailSection>
+ </TabsContent>
+ </Tabs>
+ </div>
+ );
+}
diff --git a/backend/.env.example b/backend/.env.example
index 783350f..69b6969 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -2,17 +2,15 @@ SECRET_KEY=dev-secret-change-me
# DEBUG=true 时应用日志更详细;SQL_ECHO=true 才打印原始 SQL(默认关,避免刷屏)
# DEBUG=true
# SQL_ECHO=false
-# 本地默认 SQLite;正式可改为 Postgres(Docker 见 deploy/docker-compose.yml)
-# DATABASE_URL=postgresql+asyncpg://printfilm:密码@127.0.0.1:5432/printfilm
-# DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:密码@127.0.0.1:5432/printfilm
-DATABASE_URL=sqlite+aiosqlite:///./ai_movie.db
-DATABASE_URL_SYNC=sqlite:///./ai_movie.db
+# 仅支持 PostgreSQL(Docker 见 deploy/docker-compose.yml)
+DATABASE_URL=postgresql+asyncpg://printfilm:[email protected]:15432/printfilm
+DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:[email protected]:15432/printfilm
# Postgres 生产建议:API uvicorn --workers 1;Celery 设 PRINTFILM_DB_ROLE=celery
# DB_POOL_SIZE=5
# DB_MAX_OVERFLOW=5
# DB_POOL_SIZE_CELERY=2
# DB_MAX_OVERFLOW_CELERY=3
-REDIS_URL=redis://127.0.0.1:6379/0
+REDIS_URL=redis://127.0.0.1:16379/0
CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173,http://localhost:5174,http://127.0.0.1:5174
PUBLIC_BASE_URL=http://127.0.0.1:8000
@@ -20,6 +18,7 @@ PUBLIC_BASE_URL=http://127.0.0.1:8000
ARK_MOCK=false
+# 生图/视频:请在管理后台「模型路由 → 火山方舟」配置 API Key 与模型(也可保留此处作首次导入)
ARK_API_KEY=replace-me
# 文字模型:任意 OpenAI 兼容上游(生图/视频仍走方舟 ARK_*)
@@ -60,8 +59,6 @@ MODEL_IMAGE=doubao-seedream-5-0-260128
MODEL_VIDEO=doubao-seedance-2-5-260628
SEEDANCE_DURATION_MIN=4
SEEDANCE_DURATION_MAX=30
-# 已废弃:科普成片走外部 TTS,不再直出口播(管线忽略此开关)
-KEPU_SEEDANCE_GENERATE_AUDIO=false
# 科普 Seedance 仍出音轨:只要键盘/点击等操作环境音,不要口播与 BGM
KEPU_SEEDANCE_SFX_AUDIO=true
MODEL_AUDIO=seed-tts-2.0
@@ -78,6 +75,13 @@ MODEL_AUDIO=seed-tts-2.0
# VOLC_TTS_VOICE_DESIGN_SPEAKER_IDS=S_xxx,S_yyy
# VOLC_TTS_VOICE_DESIGN_URL=https://openspeech.bytedance.com/api/v3/tts/voice_design
+# 方舟管控面用量查询(GetInferenceUsage,与 ARK_API_KEY 不同)
+# 火山管控面用量(GetInferenceUsage)— 请在管理后台「支付计费 → 上游成本监控」配置
+# VOLC_ACCESS_KEY_ID=
+# VOLC_SECRET_ACCESS_KEY=
+# VOLC_ARK_REGION=cn-beijing
+# VOLC_ARK_USAGE_ENABLED=true
+
ARK_IMAGE_SIZE=2k
ARK_VIDEO_RESOLUTION=480p
ARK_VIDEO_RATIO=16:9
diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py
index 947ce93..7549929 100644
--- a/backend/app/api/admin/__init__.py
+++ b/backend/app/api/admin/__init__.py
@@ -1,7 +1,23 @@
# Admin API router aggregation
from fastapi import APIRouter
-from app.api.admin import dashboard, drama_projects, ledger, orders, projects, queues, settings, tasks, templates, usage, users, works
+from app.api.admin import (
+ dashboard,
+ drama_assets,
+ drama_episodes,
+ drama_fragments,
+ drama_projects,
+ ledger,
+ orders,
+ projects,
+ queues,
+ settings,
+ tasks,
+ templates,
+ usage,
+ users,
+ works,
+)
router = APIRouter(prefix="/admin", tags=["admin"])
router.include_router(dashboard.router)
@@ -16,3 +32,6 @@ router.include_router(projects.router)
router.include_router(works.router)
router.include_router(templates.router)
router.include_router(drama_projects.router)
+router.include_router(drama_assets.router)
+router.include_router(drama_episodes.router)
+router.include_router(drama_fragments.router)
diff --git a/backend/app/api/admin/dashboard.py b/backend/app/api/admin/dashboard.py
index b30755e..e847181 100644
--- a/backend/app/api/admin/dashboard.py
+++ b/backend/app/api/admin/dashboard.py
@@ -1,5 +1,7 @@
# Dashboard stats for admin console
-from fastapi import APIRouter, Depends
+from typing import Literal
+
+from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
@@ -9,20 +11,33 @@ from app.schemas import (
AdminDailyUsageOut,
AdminStatsOut,
AdminTopUserOut,
+ AdminUpstreamUsageOut,
+ AdminUpstreamUsageSyncOut,
AdminUsageBucketOut,
)
from app.services.admin.stats import build_admin_dashboard_stats
+from app.services.admin.upstream_usage import build_upstream_usage_compare, sync_upstream_usage
router = APIRouter()
+StatsWindowDays = Literal[1, 7, 14, 30]
+
@router.get("/stats", response_model=AdminStatsOut)
async def admin_stats(
+ days: StatsWindowDays = Query(default=7, description="趋势与分布时间窗口(天)"),
+ domain: str = Query(default="all", max_length=32, description="领域筛选,all 为全部"),
+ capability: str = Query(default="all", max_length=32, description="能力筛选,all 为全部"),
_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
) -> AdminStatsOut:
"""用户/充值 + AI 调用量/费用/趋势/排行。"""
- raw = await build_admin_dashboard_stats(db)
+ raw = await build_admin_dashboard_stats(
+ db,
+ days=days,
+ domain=domain.strip() or "all",
+ capability=capability.strip() or "all",
+ )
return AdminStatsOut(
user_count=raw["user_count"],
order_paid_total_fen=raw["order_paid_total_fen"],
@@ -43,3 +58,29 @@ async def admin_stats(
daily_usage=[AdminDailyUsageOut(**x) for x in raw["daily_usage"]],
top_users_by_charge=[AdminTopUserOut(**x) for x in raw["top_users_by_charge"]],
)
+
+
[email protected]("/stats/upstream-usage", response_model=AdminUpstreamUsageOut)
+async def admin_upstream_usage(
+ days: int = Query(30, ge=1, le=90),
+ _admin: User = Depends(get_current_admin),
+ db: AsyncSession = Depends(get_db),
+) -> AdminUpstreamUsageOut:
+ """近 N 日官方用量与本地 seedance 成本对照。"""
+ raw = await build_upstream_usage_compare(db, days=days)
+ return AdminUpstreamUsageOut(**raw)
+
+
[email protected]("/stats/upstream-usage/sync", response_model=AdminUpstreamUsageSyncOut)
+async def admin_upstream_usage_sync(
+ days: int = Query(30, ge=1, le=90),
+ force: bool = Query(False),
+ _admin: User = Depends(get_current_admin),
+ db: AsyncSession = Depends(get_db),
+) -> AdminUpstreamUsageSyncOut:
+ """手动刷新官方用量快照。"""
+ try:
+ raw = await sync_upstream_usage(db, days=days, force=force)
+ except RuntimeError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return AdminUpstreamUsageSyncOut(**raw)
diff --git a/backend/app/api/admin/drama_assets.py b/backend/app/api/admin/drama_assets.py
new file mode 100644
index 0000000..abbbb3b
--- /dev/null
+++ b/backend/app/api/admin/drama_assets.py
@@ -0,0 +1,175 @@
+"""Admin drama asset library: cross-project list and detail."""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from pydantic import BaseModel, ConfigDict, Field
+from sqlalchemy import func, or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import aliased
+
+from app.database import get_db
+from app.deps import get_current_admin
+from app.models import User
+from app.models_drama import DramaAsset, DramaProject
+from app.schemas import PageMeta
+
+router = APIRouter()
+
+
+class AdminDramaAssetOut(BaseModel):
+ model_config = ConfigDict(from_attributes=True)
+
+ id: int
+ project_id: int
+ project_title: str | None = None
+ user_id: int | None = None
+ user_email: str | None = None
+ type: str
+ asset_type: str
+ name: str | None = None
+ cover: str | None = None
+ url: str | None = None
+ has_cover: bool = False
+ generation_status: str | None = None
+ derive_id: str | None = None
+ created_at: object | None = None
+ updated_at: object | None = None
+
+
+class AdminDramaAssetDetailOut(AdminDramaAssetOut):
+ params: dict | None = None
+
+
+class AdminDramaAssetListOut(BaseModel):
+ items: list[AdminDramaAssetOut]
+ meta: PageMeta
+
+
+def _asset_generation_status(asset: DramaAsset) -> str | None:
+ params = asset.params if isinstance(asset.params, dict) else {}
+ gen = params.get("generation")
+ if isinstance(gen, dict) and gen.get("status"):
+ return str(gen.get("status"))
+ return None
+
+
+def _asset_to_out(
+ asset: DramaAsset,
+ *,
+ project_title: str | None = None,
+ user_id: int | None = None,
+ user_email: str | None = None,
+) -> AdminDramaAssetOut:
+ return AdminDramaAssetOut(
+ id=asset.id,
+ project_id=asset.project_id,
+ project_title=project_title,
+ user_id=user_id,
+ user_email=user_email,
+ type=str(asset.type or "none"),
+ asset_type=str(asset.asset_type or "image"),
+ name=asset.name,
+ cover=asset.cover,
+ url=asset.url,
+ has_cover=bool(asset.cover or asset.url),
+ generation_status=_asset_generation_status(asset),
+ derive_id=asset.derive_id,
+ created_at=asset.created_at,
+ updated_at=asset.updated_at,
+ )
+
+
[email protected]("/drama-assets", response_model=AdminDramaAssetListOut)
+async def list_drama_assets(
+ page: int = Query(1, ge=1),
+ page_size: int = Query(20, ge=1, le=100),
+ q: str | None = None,
+ user_id: int | None = None,
+ project_id: int | None = None,
+ asset_kind: str | None = Query(None, alias="type"),
+ asset_type: str | None = None,
+ generation_status: str | None = None,
+ _admin: User = Depends(get_current_admin),
+ db: AsyncSession = Depends(get_db),
+) -> AdminDramaAssetListOut:
+ owner = aliased(User)
+ stmt = (
+ select(DramaAsset, DramaProject, owner.email)
+ .join(DramaProject, DramaProject.id == DramaAsset.project_id)
+ .outerjoin(owner, owner.id == DramaProject.user_id)
+ )
+ count_stmt = (
+ select(func.count())
+ .select_from(DramaAsset)
+ .join(DramaProject, DramaProject.id == DramaAsset.project_id)
+ )
+
+ if user_id is not None:
+ stmt = stmt.where(DramaProject.user_id == user_id)
+ count_stmt = count_stmt.where(DramaProject.user_id == user_id)
+ if project_id is not None:
+ stmt = stmt.where(DramaAsset.project_id == project_id)
+ count_stmt = count_stmt.where(DramaAsset.project_id == project_id)
+ if asset_kind and asset_kind.strip():
+ type_val = asset_kind.strip()
+ stmt = stmt.where(DramaAsset.type == type_val)
+ count_stmt = count_stmt.where(DramaAsset.type == type_val)
+ if asset_type and asset_type.strip():
+ at_val = asset_type.strip()
+ stmt = stmt.where(DramaAsset.asset_type == at_val)
+ count_stmt = count_stmt.where(DramaAsset.asset_type == at_val)
+ if q and q.strip():
+ like = f"%{q.strip()}%"
+ filt = or_(DramaAsset.name.ilike(like), DramaAsset.derive_id.ilike(like))
+ stmt = stmt.where(filt)
+ count_stmt = count_stmt.where(filt)
+ if generation_status and generation_status.strip():
+ status_val = generation_status.strip()
+ stmt = stmt.where(DramaAsset.params["generation"]["status"].as_string() == status_val)
+ count_stmt = count_stmt.where(DramaAsset.params["generation"]["status"].as_string() == status_val)
+
+ total = int((await db.execute(count_stmt)).scalar_one() or 0)
+ rows = (
+ await db.execute(
+ stmt.order_by(DramaAsset.id.desc()).offset((page - 1) * page_size).limit(page_size)
+ )
+ ).all()
+
+ items = [
+ _asset_to_out(
+ asset,
+ project_title=project.title,
+ user_id=project.user_id,
+ user_email=email,
+ )
+ for asset, project, email in rows
+ ]
+ return AdminDramaAssetListOut(items=items, meta=PageMeta(page=page, page_size=page_size, total=total))
+
+
[email protected]("/drama-assets/{asset_id}", response_model=AdminDramaAssetDetailOut)
+async def get_drama_asset(
+ asset_id: int,
+ _admin: User = Depends(get_current_admin),
+ db: AsyncSession = Depends(get_db),
+) -> AdminDramaAssetDetailOut:
+ owner = aliased(User)
+ row = (
+ await db.execute(
+ select(DramaAsset, DramaProject, owner.email)
+ .join(DramaProject, DramaProject.id == DramaAsset.project_id)
+ .outerjoin(owner, owner.id == DramaProject.user_id)
+ .where(DramaAsset.id == asset_id)
+ )
+ ).first()
+ if not row:
+ raise HTTPException(status_code=404, detail="漫剧资产不存在")
+ asset, project, email = row
+ base = _asset_to_out(
+ asset,
+ project_title=project.title,
+ user_id=project.user_id,
+ user_email=email,
+ )
+ return AdminDramaAssetDetailOut(**base.model_dump(), params=asset.params if isinstance(asset.params, dict) else None)
diff --git a/backend/app/api/admin/drama_episodes.py b/backend/app/api/admin/drama_episodes.py
new file mode 100644
index 0000000..043e6da
--- /dev/null
+++ b/backend/app/api/admin/drama_episodes.py
@@ -0,0 +1,180 @@
+"""Admin drama episode list and detail with fragments."""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from pydantic import BaseModel, ConfigDict, Field
+from sqlalchemy import func, or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import aliased, selectinload
+
+from app.database import get_db
+from app.deps import get_current_admin
+from app.models import User
+from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaProject
+from app.schemas import PageMeta
+
+router = APIRouter()
+
+
+class AdminDramaFragmentBriefOut(BaseModel):
+ id: int
+ sort_order: int = 0
+ content: str = ""
+ cover: str = ""
+ video: str = ""
+ duration_sec: int | None = None
+ generation_status: str | None = None
+ asset_ref_count: int = 0
+
+
+class AdminDramaEpisodeOut(BaseModel):
+ model_config = ConfigDict(from_attributes=True)
+
+ id: int
+ project_id: int
+ project_title: str | None = None
+ user_id: int | None = None
+ user_email: str | None = None
+ name: str
+ fragment_count: int = 0
+ fragment_plan_status: str | None = None
+ created_at: object | None = None
+ updated_at: object | None = None
+
+
+class AdminDramaEpisodeDetailOut(AdminDramaEpisodeOut):
+ fragments: list[AdminDramaFragmentBriefOut] = Field(default_factory=list)
+
+
+class AdminDramaEpisodeListOut(BaseModel):
+ items: list[AdminDramaEpisodeOut]
+ meta: PageMeta
+
+
+def _fragment_generation_status(fragment: DramaEpisodeFragment) -> str | None:
+ params = fragment.params if isinstance(fragment.params, dict) else {}
+ gen = params.get("generation")
+ if isinstance(gen, dict) and gen.get("status"):
+ return str(gen.get("status"))
+ return None
+
+
+def _episode_plan_status(episode: DramaEpisode) -> str | None:
+ params = episode.params if isinstance(episode.params, dict) else {}
+ raw = params.get("fragment_plan_status")
+ return str(raw) if raw else None
+
+
[email protected]("/drama-episodes", response_model=AdminDramaEpisodeListOut)
+async def list_drama_episodes(
+ page: int = Query(1, ge=1),
+ page_size: int = Query(20, ge=1, le=100),
+ q: str | None = None,
+ user_id: int | None = None,
+ project_id: int | None = None,
+ _admin: User = Depends(get_current_admin),
+ db: AsyncSession = Depends(get_db),
+) -> AdminDramaEpisodeListOut:
+ owner = aliased(User)
+ frag_count = (
+ select(func.count(DramaEpisodeFragment.id))
+ .where(DramaEpisodeFragment.episode_id == DramaEpisode.id)
+ .correlate(DramaEpisode)
+ .scalar_subquery()
+ )
+ stmt = (
+ select(DramaEpisode, DramaProject, owner.email, frag_count)
+ .join(DramaProject, DramaProject.id == DramaEpisode.project_id)
+ .outerjoin(owner, owner.id == DramaProject.user_id)
+ )
+ count_stmt = (
+ select(func.count())
+ .select_from(DramaEpisode)
+ .join(DramaProject, DramaProject.id == DramaEpisode.project_id)
+ )
+
+ if user_id is not None:
+ stmt = stmt.where(DramaProject.user_id == user_id)
+ count_stmt = count_stmt.where(DramaProject.user_id == user_id)
+ if project_id is not None:
+ stmt = stmt.where(DramaEpisode.project_id == project_id)
+ count_stmt = count_stmt.where(DramaEpisode.project_id == project_id)
+ if q and q.strip():
+ like = f"%{q.strip()}%"
+ filt = or_(DramaEpisode.name.ilike(like), DramaProject.title.ilike(like))
+ stmt = stmt.where(filt)
+ count_stmt = count_stmt.where(filt)
+
+ total = int((await db.execute(count_stmt)).scalar_one() or 0)
+ rows = (
+ await db.execute(
+ stmt.order_by(DramaEpisode.id.desc()).offset((page - 1) * page_size).limit(page_size)
+ )
+ ).all()
+
+ items = [
+ AdminDramaEpisodeOut(
+ id=ep.id,
+ project_id=ep.project_id,
+ project_title=project.title,
+ user_id=project.user_id,
+ user_email=email,
+ name=ep.name or f"集 #{ep.id}",
+ fragment_count=int(fcount or 0),
+ fragment_plan_status=_episode_plan_status(ep),
+ created_at=ep.created_at,
+ updated_at=ep.updated_at,
+ )
+ for ep, project, email, fcount in rows
+ ]
+ return AdminDramaEpisodeListOut(items=items, meta=PageMeta(page=page, page_size=page_size, total=total))
+
+
[email protected]("/drama-episodes/{episode_id}", response_model=AdminDramaEpisodeDetailOut)
+async def get_drama_episode(
+ episode_id: int,
+ _admin: User = Depends(get_current_admin),
+ db: AsyncSession = Depends(get_db),
+) -> AdminDramaEpisodeDetailOut:
+ owner = aliased(User)
+ row = (
+ await db.execute(
+ select(DramaEpisode, DramaProject, owner.email)
+ .join(DramaProject, DramaProject.id == DramaEpisode.project_id)
+ .outerjoin(owner, owner.id == DramaProject.user_id)
+ .where(DramaEpisode.id == episode_id)
+ .options(
+ selectinload(DramaEpisode.fragments).selectinload(DramaEpisodeFragment.asset_references)
+ )
+ )
+ ).first()
+ if not row:
+ raise HTTPException(status_code=404, detail="漫剧分集不存在")
+ episode, project, email = row
+ fragments = sorted(episode.fragments or [], key=lambda f: (f.sort_order, f.id))
+ return AdminDramaEpisodeDetailOut(
+ id=episode.id,
+ project_id=episode.project_id,
+ project_title=project.title,
+ user_id=project.user_id,
+ user_email=email,
+ name=episode.name or f"集 #{episode.id}",
+ fragment_count=len(fragments),
+ fragment_plan_status=_episode_plan_status(episode),
+ created_at=episode.created_at,
+ updated_at=episode.updated_at,
+ fragments=[
+ AdminDramaFragmentBriefOut(
+ id=f.id,
+ sort_order=int(f.sort_order or 0),
+ content=f.content or "",
+ cover=f.cover or "",
+ video=f.video or "",
+ duration_sec=f.duration_sec,
+ generation_status=_fragment_generation_status(f),
+ asset_ref_count=len(f.asset_references or []),
+ )
+ for f in fragments
+ ],
+ )
diff --git a/backend/app/api/admin/drama_fragments.py b/backend/app/api/admin/drama_fragments.py
new file mode 100644
index 0000000..aeb8274
--- /dev/null
+++ b/backend/app/api/admin/drama_fragments.py
@@ -0,0 +1,190 @@
+"""Admin drama fragment (storyboard) list and detail."""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from pydantic import BaseModel, ConfigDict
+from sqlalchemy import func, or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import aliased, selectinload
+
+from app.database import get_db
+from app.deps import get_current_admin
+from app.models import User
+from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaFragmentAssetRef, DramaProject
+from app.schemas import PageMeta
+
+router = APIRouter()
+
+
+class AdminDramaFragmentOut(BaseModel):
+ model_config = ConfigDict(from_attributes=True)
+
+ id: int
+ episode_id: int
+ episode_name: str | None = None
+ project_id: int
+ project_title: str | None = None
+ user_id: int | None = None
+ user_email: str | None = None
+ sort_order: int = 0
+ content: str = ""
+ cover: str = ""
+ video: str = ""
+ duration_sec: int | None = None
+ generation_status: str | None = None
+ asset_ref_count: int = 0
+ created_at: object | None = None
+ updated_at: object | None = None
+
+
+class AdminDramaFragmentDetailOut(AdminDramaFragmentOut):
+ params: dict | None = None
+ asset_ids: list[int] = []
+
+
+class AdminDramaFragmentListOut(BaseModel):
+ items: list[AdminDramaFragmentOut]
+ meta: PageMeta
+
+
+def _fragment_generation_status(fragment: DramaEpisodeFragment) -> str | None:
+ params = fragment.params if isinstance(fragment.params, dict) else {}
+ gen = params.get("generation")
+ if isinstance(gen, dict) and gen.get("status"):
+ return str(gen.get("status"))
+ return None
+
+
[email protected]("/drama-fragments", response_model=AdminDramaFragmentListOut)
+async def list_drama_fragments(
+ page: int = Query(1, ge=1),
+ page_size: int = Query(20, ge=1, le=100),
+ q: str | None = None,
+ user_id: int | None = None,
+ project_id: int | None = None,
+ episode_id: int | None = None,
+ generation_status: str | None = None,
+ _admin: User = Depends(get_current_admin),
+ db: AsyncSession = Depends(get_db),
+) -> AdminDramaFragmentListOut:
+ owner = aliased(User)
+ asset_ref_count = (
+ select(func.count(DramaFragmentAssetRef.id))
+ .where(DramaFragmentAssetRef.fragment_id == DramaEpisodeFragment.id)
+ .correlate(DramaEpisodeFragment)
+ .scalar_subquery()
+ )
+
+ stmt = (
+ select(DramaEpisodeFragment, DramaEpisode, DramaProject, owner.email, asset_ref_count)
+ .join(DramaEpisode, DramaEpisode.id == DramaEpisodeFragment.episode_id)
+ .join(DramaProject, DramaProject.id == DramaEpisode.project_id)
+ .outerjoin(owner, owner.id == DramaProject.user_id)
+ )
+ count_stmt = (
+ select(func.count())
+ .select_from(DramaEpisodeFragment)
+ .join(DramaEpisode, DramaEpisode.id == DramaEpisodeFragment.episode_id)
+ .join(DramaProject, DramaProject.id == DramaEpisode.project_id)
+ )
+
+ if user_id is not None:
+ stmt = stmt.where(DramaProject.user_id == user_id)
+ count_stmt = count_stmt.where(DramaProject.user_id == user_id)
+ if project_id is not None:
+ stmt = stmt.where(DramaProject.id == project_id)
+ count_stmt = count_stmt.where(DramaProject.id == project_id)
+ if episode_id is not None:
+ stmt = stmt.where(DramaEpisodeFragment.episode_id == episode_id)
+ count_stmt = count_stmt.where(DramaEpisodeFragment.episode_id == episode_id)
+ if q and q.strip():
+ like = f"%{q.strip()}%"
+ filt = or_(
+ DramaEpisodeFragment.content.ilike(like),
+ DramaEpisode.name.ilike(like),
+ DramaProject.title.ilike(like),
+ )
+ stmt = stmt.where(filt)
+ count_stmt = count_stmt.where(filt)
+ if generation_status and generation_status.strip():
+ status_val = generation_status.strip()
+ stmt = stmt.where(DramaEpisodeFragment.params["generation"]["status"].as_string() == status_val)
+ count_stmt = count_stmt.where(
+ DramaEpisodeFragment.params["generation"]["status"].as_string() == status_val
+ )
+
+ total = int((await db.execute(count_stmt)).scalar_one() or 0)
+ rows = (
+ await db.execute(
+ stmt.order_by(DramaEpisodeFragment.id.desc())
+ .offset((page - 1) * page_size)
+ .limit(page_size)
+ )
+ ).all()
+
+ items = [
+ AdminDramaFragmentOut(
+ id=frag.id,
+ episode_id=frag.episode_id,
+ episode_name=episode.name,
+ project_id=project.id,
+ project_title=project.title,
+ user_id=project.user_id,
+ user_email=email,
+ sort_order=int(frag.sort_order or 0),
+ content=frag.content or "",
+ cover=frag.cover or "",
+ video=frag.video or "",
+ duration_sec=frag.duration_sec,
+ generation_status=_fragment_generation_status(frag),
+ asset_ref_count=int(refs or 0),
+ created_at=frag.created_at,
+ updated_at=frag.updated_at,
+ )
+ for frag, episode, project, email, refs in rows
+ ]
+ return AdminDramaFragmentListOut(items=items, meta=PageMeta(page=page, page_size=page_size, total=total))
+
+
[email protected]("/drama-fragments/{fragment_id}", response_model=AdminDramaFragmentDetailOut)
+async def get_drama_fragment(
+ fragment_id: int,
+ _admin: User = Depends(get_current_admin),
+ db: AsyncSession = Depends(get_db),
+) -> AdminDramaFragmentDetailOut:
+ owner = aliased(User)
+ row = (
+ await db.execute(
+ select(DramaEpisodeFragment, DramaEpisode, DramaProject, owner.email)
+ .join(DramaEpisode, DramaEpisode.id == DramaEpisodeFragment.episode_id)
+ .join(DramaProject, DramaProject.id == DramaEpisode.project_id)
+ .outerjoin(owner, owner.id == DramaProject.user_id)
+ .where(DramaEpisodeFragment.id == fragment_id)
+ .options(selectinload(DramaEpisodeFragment.asset_references))
+ )
+ ).first()
+ if not row:
+ raise HTTPException(status_code=404, detail="漫剧分镜不存在")
+ frag, episode, project, email = row
+ asset_ids = [int(ref.asset_id) for ref in (frag.asset_references or [])]
+ return AdminDramaFragmentDetailOut(
+ id=frag.id,
+ episode_id=frag.episode_id,
+ episode_name=episode.name,
+ project_id=project.id,
+ project_title=project.title,
+ user_id=project.user_id,
+ user_email=email,
+ sort_order=int(frag.sort_order or 0),
+ content=frag.content or "",
+ cover=frag.cover or "",
+ video=frag.video or "",
+ duration_sec=frag.duration_sec,
+ generation_status=_fragment_generation_status(frag),
+ asset_ref_count=len(asset_ids),
+ created_at=frag.created_at,
+ updated_at=frag.updated_at,
+ params=frag.params if isinstance(frag.params, dict) else None,
+ asset_ids=asset_ids,
+ )
diff --git a/backend/app/api/admin/drama_projects.py b/backend/app/api/admin/drama_projects.py
index 90b77de..282c288 100644
--- a/backend/app/api/admin/drama_projects.py
+++ b/backend/app/api/admin/drama_projects.py
@@ -11,7 +11,7 @@ from sqlalchemy.orm import aliased, selectinload
from app.database import get_db
from app.deps import get_current_admin
from app.models import User
-from app.models_drama import DramaAsset, DramaEpisode, DramaProject
+from app.models_drama import DramaAsset, DramaEpisode, DramaProject, DramaScript
from app.models_tasks import TaskRun
from app.schemas import AdminProjectUsageOut, AdminTaskBriefOut, PageMeta
from app.services.admin.stats import aggregate_usage_summary
@@ -93,6 +93,8 @@ async def list_drama_projects(
page_size: int = Query(20, ge=1, le=100),
q: str | None = None,
user_id: int | None = None,
+ summary_status: str | None = None,
+ assets_seed_status: str | None = None,
_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
) -> AdminDramaProjectListOut:
@@ -125,6 +127,18 @@ async def list_drama_projects(
filt = or_(DramaProject.title.ilike(like), DramaProject.description.ilike(like))
stmt = stmt.where(filt)
count_stmt = count_stmt.where(filt)
+ if summary_status and summary_status.strip():
+ status_val = summary_status.strip()
+ stmt = stmt.join(DramaScript, DramaScript.project_id == DramaProject.id).where(
+ DramaScript.params["summary_status"].as_string() == status_val
+ )
+ count_stmt = count_stmt.join(DramaScript, DramaScript.project_id == DramaProject.id).where(
+ DramaScript.params["summary_status"].as_string() == status_val
+ )
+ if assets_seed_status and assets_seed_status.strip():
+ seed_val = assets_seed_status.strip()
+ stmt = stmt.where(DramaProject.params["assets_seed_status"].as_string() == seed_val)
+ count_stmt = count_stmt.where(DramaProject.params["assets_seed_status"].as_string() == seed_val)
total = int((await db.execute(count_stmt)).scalar_one() or 0)
rows = (
@@ -183,7 +197,8 @@ async def get_drama_project(
assets = sorted(project.assets or [], key=lambda a: a.id)
fragment_count = sum(len(ep.fragments or []) for ep in episodes)
- data = AdminDramaProjectDetailOut.model_validate(project)
+ base = AdminDramaProjectOut.model_validate(project)
+ data = AdminDramaProjectDetailOut(**base.model_dump())
data.user_email = email
data.episode_count = len(episodes)
data.asset_count = len(assets)
diff --git a/backend/app/api/admin/orders.py b/backend/app/api/admin/orders.py
index 94b6341..d87a172 100644
--- a/backend/app/api/admin/orders.py
+++ b/backend/app/api/admin/orders.py
@@ -16,6 +16,7 @@ router = APIRouter()
async def list_orders(
status: str | None = None,
user_id: int | None = None,
+ out_trade_no: str | None = None,
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
_admin: User = Depends(get_current_admin),
@@ -32,6 +33,10 @@ async def list_orders(
if user_id is not None:
stmt = stmt.where(Order.user_id == user_id)
count_stmt = count_stmt.where(Order.user_id == user_id)
+ if out_trade_no and out_trade_no.strip():
+ trade = out_trade_no.strip()
+ stmt = stmt.where(Order.out_trade_no == trade)
+ count_stmt = count_stmt.where(Order.out_trade_no == trade)
total = int((await db.execute(count_stmt)).scalar_one() or 0)
rows = (
diff --git a/backend/app/api/admin/projects.py b/backend/app/api/admin/projects.py
index b8574e1..45ed233 100644
--- a/backend/app/api/admin/projects.py
+++ b/backend/app/api/admin/projects.py
@@ -97,9 +97,20 @@ async def get_project(
if not row:
raise HTTPException(status_code=404, detail="项目不存在")
project, email, scount = row
- data = AdminProjectDetailOut.model_validate(project)
- data.user_email = email
- data.shot_count = int(scount or 0)
+ base = AdminProjectOut.model_validate(project)
+ payload = base.model_dump()
+ payload.update(
+ {
+ "user_email": email,
+ "shot_count": int(scount or 0),
+ "source_type": project.source_type,
+ "source_text": project.source_text,
+ "resolution_mode": project.resolution_mode,
+ "output_ratio": project.output_ratio or "",
+ "voice_id": project.voice_id or "",
+ }
+ )
+ data = AdminProjectDetailOut(**payload)
usage = await aggregate_usage_summary(db, project_id=project_id)
assert isinstance(usage, dict)
diff --git a/backend/app/api/admin/settings.py b/backend/app/api/admin/settings.py
index faf2605..306e408 100644
--- a/backend/app/api/admin/settings.py
+++ b/backend/app/api/admin/settings.py
@@ -1,5 +1,6 @@
# Admin model / provider settings API
from fastapi import APIRouter, Depends, HTTPException
+from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
@@ -7,6 +8,7 @@ from app.deps import get_current_admin
from app.models import User
from app.schemas_routing import AdminRoutingSettingsOut, AdminRoutingSettingsPatch, AdminRoutingSettingsSaveOut
from app.schemas_settings import AdminModelSettingsOut, AdminModelSettingsPatch, AdminModelSettingsSaveOut, AdminModelSettingsImportEnvOut
+from app.services.ark_model_catalog import list_ark_models
from app.services.model_settings import (
get_admin_model_settings,
get_admin_routing_settings,
@@ -18,6 +20,11 @@ from app.services.model_settings import (
router = APIRouter()
+class AdminArkModelsRequest(BaseModel):
+ capability: str = "all"
+ api_key: str | None = Field(default=None, max_length=512)
+
+
@router.get("/settings/routing", response_model=AdminRoutingSettingsOut)
async def admin_get_routing_settings(
_admin: User = Depends(get_current_admin),
@@ -76,3 +83,21 @@ async def admin_import_model_settings_from_env(
imported_fields=imported,
skipped_secret_fields=skipped,
)
+
+
[email protected]("/settings/ark/models")
+async def admin_list_ark_models(
+ body: AdminArkModelsRequest,
+ _admin: User = Depends(get_current_admin),
+ db: AsyncSession = Depends(get_db),
+) -> dict:
+ """拉取火山方舟模型目录(临时 Key 仅走 POST body,避免进入 URL 日志)。"""
+ try:
+ models = await list_ark_models(
+ db,
+ capability=body.capability,
+ api_key_override=body.api_key,
+ )
+ except RuntimeError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return {"models": models}
diff --git a/backend/app/api/admin/tasks.py b/backend/app/api/admin/tasks.py
index 13ac754..0c2f725 100644
--- a/backend/app/api/admin/tasks.py
+++ b/backend/app/api/admin/tasks.py
@@ -11,6 +11,7 @@ from app.deps import get_current_admin
from app.models import UsageEvent, User
from app.schemas import PageMeta
from app.schemas_tasks import AdminTaskListOut, AdminTaskRunOut, AdminTaskStatsOut, AdminUsageEventBriefOut, TaskRunOut
+from app.services.billing.display import billing_basis_label, resolve_billing_basis
from app.services.tasks.runtime import runtime_summary
from app.services.tasks.service import cancel_task_admin, get_task_admin, get_task_stats_admin, list_tasks_admin
@@ -34,7 +35,25 @@ async def _load_usage_lines(db: AsyncSession, task_id: int) -> list[AdminUsageEv
.order_by(UsageEvent.id.asc())
)
).scalars().all()
- return [AdminUsageEventBriefOut.model_validate(row) for row in rows]
+ items: list[AdminUsageEventBriefOut] = []
+ for row in rows:
+ basis = resolve_billing_basis(estimated=bool(row.estimated), raw_usage_json=row.raw_usage_json)
+ items.append(
+ AdminUsageEventBriefOut(
+ id=row.id,
+ billing_key=row.billing_key,
+ capability=row.capability,
+ model=row.model or "",
+ total_tokens=int(row.total_tokens or 0),
+ charge_fen=int(row.charge_fen or 0),
+ cost_fen=int(row.cost_fen or 0),
+ estimated=bool(row.estimated),
+ billing_basis=basis,
+ billing_basis_label=billing_basis_label(basis),
+ created_at=row.created_at,
+ )
+ )
+ return items
@router.get("/tasks/stats", response_model=AdminTaskStatsOut)
diff --git a/backend/app/api/admin/templates.py b/backend/app/api/admin/templates.py
index 1f53bdf..bb68aa3 100644
--- a/backend/app/api/admin/templates.py
+++ b/backend/app/api/admin/templates.py
@@ -1,6 +1,7 @@
# Admin template CRUD
from fastapi import APIRouter, Depends, HTTPException, Query
-from sqlalchemy import func, select
+from sqlalchemy import cast, func, or_, select
+from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
@@ -38,14 +39,32 @@ async def templates_meta(
async def list_templates(
page: int = Query(1, ge=1),
page_size: int = Query(50, ge=1, le=100),
+ q: str | None = None,
+ is_active: bool | None = None,
+ category: str | None = None,
_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
) -> AdminTemplateListOut:
# All templates including inactive
- total = int((await db.execute(select(func.count()).select_from(Template))).scalar_one() or 0)
+ stmt = select(Template)
+ count_stmt = select(func.count()).select_from(Template)
+ if q and q.strip():
+ like = f"%{q.strip()}%"
+ filt = or_(Template.id.ilike(like), Template.name.ilike(like), Template.description.ilike(like))
+ stmt = stmt.where(filt)
+ count_stmt = count_stmt.where(filt)
+ if is_active is not None:
+ stmt = stmt.where(Template.is_active == is_active)
+ count_stmt = count_stmt.where(Template.is_active == is_active)
+ if category and category.strip():
+ cat = category.strip()
+ cat_filter = cast(Template.category, JSONB).contains([cat])
+ stmt = stmt.where(cat_filter)
+ count_stmt = count_stmt.where(cat_filter)
+
+ total = int((await db.execute(count_stmt)).scalar_one() or 0)
result = await db.execute(
- select(Template)
- .order_by(Template.sort_order, Template.id)
+ stmt.order_by(Template.sort_order, Template.id)
.offset((page - 1) * page_size)
.limit(page_size)
)
diff --git a/backend/app/api/admin/usage.py b/backend/app/api/admin/usage.py
index 9a7aefe..d49dd84 100644
--- a/backend/app/api/admin/usage.py
+++ b/backend/app/api/admin/usage.py
@@ -12,17 +12,60 @@ from app.models import UsageEvent, User
from app.models_tasks import TaskRun
from app.schemas import PageMeta
from app.schemas_tasks import AdminUsageEventListOut, AdminUsageEventOut
+from app.services.billing.display import (
+ billing_basis_label,
+ billing_basis_sql_filter,
+ resolve_billing_basis,
+)
router = APIRouter()
+def _usage_event_out(
+ ev: UsageEvent,
+ *,
+ email: str | None,
+ task_domain: str | None,
+ task_type: str | None,
+ task_status: str | None,
+) -> AdminUsageEventOut:
+ basis = resolve_billing_basis(estimated=bool(ev.estimated), raw_usage_json=ev.raw_usage_json)
+ return AdminUsageEventOut(
+ id=ev.id,
+ user_id=ev.user_id,
+ user_email=email,
+ task_run_id=ev.task_run_id,
+ project_id=ev.project_id,
+ drama_project_id=ev.drama_project_id,
+ domain=ev.domain,
+ capability=ev.capability,
+ billing_key=ev.billing_key,
+ model=ev.model or "",
+ provider=ev.provider,
+ total_tokens=int(ev.total_tokens or 0),
+ charge_fen=int(ev.charge_fen or 0),
+ cost_fen=int(ev.cost_fen or 0),
+ estimated=bool(ev.estimated),
+ billing_basis=basis,
+ billing_basis_label=billing_basis_label(basis),
+ created_at=ev.created_at,
+ task_domain=task_domain,
+ task_type=task_type,
+ task_status=task_status,
+ )
+
+
@router.get("/usage-events", response_model=AdminUsageEventListOut)
async def list_usage_events(
user_id: int | None = None,
task_run_id: int | None = None,
+ project_id: int | None = None,
+ drama_project_id: int | None = None,
domain: str | None = None,
billing_key: str | None = None,
capability: str | None = None,
+ estimated: bool | None = None,
+ billing_basis: str | None = None,
created_from: datetime | None = None,
created_to: datetime | None = None,
page: int = Query(1, ge=1),
@@ -38,12 +81,23 @@ async def list_usage_events(
filters.append(UsageEvent.user_id == user_id)
if task_run_id is not None:
filters.append(UsageEvent.task_run_id == task_run_id)
+ if project_id is not None:
+ filters.append(UsageEvent.project_id == project_id)
+ if drama_project_id is not None:
+ filters.append(UsageEvent.drama_project_id == drama_project_id)
if domain and domain.strip():
filters.append(UsageEvent.domain == domain.strip())
if billing_key and billing_key.strip():
filters.append(UsageEvent.billing_key == billing_key.strip())
if capability and capability.strip():
filters.append(UsageEvent.capability == capability.strip())
+ if estimated is not None:
+ filters.append(UsageEvent.estimated.is_(estimated))
+ basis = (billing_basis or "").strip().lower()
+ if basis and estimated is None:
+ basis_filter = billing_basis_sql_filter(basis)
+ if basis_filter is not None:
+ filters.append(basis_filter)
if created_from is not None:
filters.append(UsageEvent.created_at >= created_from)
if created_to is not None:
@@ -69,20 +123,9 @@ async def list_usage_events(
items: list[AdminUsageEventOut] = []
for ev, email, task_domain, task_type, task_status in rows:
items.append(
- AdminUsageEventOut(
- id=ev.id,
- user_id=ev.user_id,
- user_email=email,
- task_run_id=ev.task_run_id,
- domain=ev.domain,
- capability=ev.capability,
- billing_key=ev.billing_key,
- model=ev.model or "",
- total_tokens=int(ev.total_tokens or 0),
- charge_fen=int(ev.charge_fen or 0),
- cost_fen=int(ev.cost_fen or 0),
- estimated=bool(ev.estimated),
- created_at=ev.created_at,
+ _usage_event_out(
+ ev,
+ email=email,
task_domain=task_domain,
task_type=task_type,
task_status=task_status,
diff --git a/backend/app/api/admin/users.py b/backend/app/api/admin/users.py
index e4d30bb..cbef00b 100644
--- a/backend/app/api/admin/users.py
+++ b/backend/app/api/admin/users.py
@@ -14,19 +14,37 @@ router = APIRouter()
@router.get("/users", response_model=AdminUserListOut)
async def list_users(
q: str | None = None,
+ plan: str | None = None,
+ role: str | None = None,
+ billing_unlimited: bool | None = None,
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
) -> AdminUserListOut:
- # Paginated user search by email / nickname
+ # Paginated user search by email / nickname / id
stmt = select(User)
count_stmt = select(func.count()).select_from(User)
if q and q.strip():
- like = f"%{q.strip()}%"
+ raw = q.strip()
+ like = f"%{raw}%"
+ id_match = None
+ if raw.isdigit():
+ id_match = int(raw)
filt = or_(User.email.ilike(like), User.nickname.ilike(like))
+ if id_match is not None:
+ filt = or_(filt, User.id == id_match)
stmt = stmt.where(filt)
count_stmt = count_stmt.where(filt)
+ if plan and plan.strip():
+ stmt = stmt.where(User.plan == plan.strip())
+ count_stmt = count_stmt.where(User.plan == plan.strip())
+ if role and role.strip():
+ stmt = stmt.where(User.role == role.strip())
+ count_stmt = count_stmt.where(User.role == role.strip())
+ if billing_unlimited is not None:
+ stmt = stmt.where(User.billing_unlimited == billing_unlimited)
+ count_stmt = count_stmt.where(User.billing_unlimited == billing_unlimited)
total = int((await db.execute(count_stmt)).scalar_one() or 0)
result = await db.execute(
diff --git a/backend/app/api/admin/works.py b/backend/app/api/admin/works.py
index c9eb092..c37fea7 100644
--- a/backend/app/api/admin/works.py
+++ b/backend/app/api/admin/works.py
@@ -1,6 +1,6 @@
# Admin work audit (visibility / audit_status)
from fastapi import APIRouter, Depends, HTTPException, Query
-from sqlalchemy import func, select
+from sqlalchemy import func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased
@@ -16,6 +16,8 @@ router = APIRouter()
async def list_works(
audit_status: str | None = None,
visibility: str | None = None,
+ q: str | None = None,
+ user_id: int | None = None,
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
_admin: User = Depends(get_current_admin),
@@ -32,6 +34,14 @@ async def list_works(
if visibility and visibility.strip():
stmt = stmt.where(Work.visibility == visibility.strip())
count_stmt = count_stmt.where(Work.visibility == visibility.strip())
+ if user_id is not None:
+ stmt = stmt.where(Work.user_id == user_id)
+ count_stmt = count_stmt.where(Work.user_id == user_id)
+ if q and q.strip():
+ like = f"%{q.strip()}%"
+ filt = Work.title.ilike(like)
+ stmt = stmt.where(filt)
+ count_stmt = count_stmt.where(filt)
total = int((await db.execute(count_stmt)).scalar_one() or 0)
rows = (
diff --git a/backend/app/api/billing.py b/backend/app/api/billing.py
index 7aa0971..6997498 100644
--- a/backend/app/api/billing.py
+++ b/backend/app/api/billing.py
@@ -214,6 +214,46 @@ async def usage_summary(
}
[email protected]("/alerts/pending")
+async def billing_alerts_pending(
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ """待展示的用户额度告警(弹窗)。"""
+ from app.services.billing.alerts import list_pending_user_alerts
+
+ rows = await list_pending_user_alerts(db, user.id)
+ return {
+ "items": [
+ {
+ "id": row.id,
+ "kind": row.kind,
+ "title": row.title,
+ "message": row.message,
+ "milestone_fen": int(row.milestone_fen or 0),
+ "milestone_yuan": round(int(row.milestone_fen or 0) / 100, 2),
+ "created_at": row.created_at.isoformat() if row.created_at else None,
+ }
+ for row in rows
+ ]
+ }
+
+
[email protected]("/alerts/{alert_id}/ack")
+async def billing_alert_ack(
+ alert_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ from app.services.billing.alerts import acknowledge_user_alert
+
+ ok = await acknowledge_user_alert(db, user.id, alert_id)
+ if not ok:
+ raise HTTPException(status_code=404, detail="告警不存在")
+ await db.commit()
+ return {"ok": True}
+
+
@router.get("/usage/events")
async def usage_events(
db: AsyncSession = Depends(get_db),
diff --git a/backend/app/api/tools.py b/backend/app/api/tools.py
index d970a67..353e0e2 100644
--- a/backend/app/api/tools.py
+++ b/backend/app/api/tools.py
@@ -161,6 +161,9 @@ async def get_tool_task(
poll_status=str(data.get("status") or ""),
error=str(data.get("error") or "") or None,
billing_task_id=billing_task_id,
+ usage_tokens=int((data.get("usage") or {}).get("total_tokens") or 0),
+ completion_tokens=int((data.get("usage") or {}).get("completion_tokens") or 0),
+ raw_usage=data.get("raw_usage") if isinstance(data.get("raw_usage"), dict) else None,
)
await update_tool_run_task(db, user.id, tid, data)
await db.commit()
diff --git a/backend/app/api/v1/generation.py b/backend/app/api/v1/generation.py
index e935f4e..e867b30 100644
--- a/backend/app/api/v1/generation.py
+++ b/backend/app/api/v1/generation.py
@@ -17,11 +17,11 @@ from app.schemas_api import (
)
from app.services.ark import get_ark
from app.services.billing import (
- record_line,
run_billed_ephemeral,
run_billed_ephemeral_deferred,
settle_deferred_video_poll,
)
+from app.services.drama.billing_util import record_seedream_image_usage
from app.services.studio_tools import poll_video_task, ratio_to_size
from app.services import storage
@@ -69,14 +69,13 @@ async def generate_image(
except Exception as exc: # noqa: BLE001
raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc
- await record_line(
+ await record_seedream_image_usage(
db,
user_id=user.id,
- billing_key="seedream",
model=get_settings().model_image,
- estimated=True,
domain="api",
- raw={"source": "api_v1_image"},
+ image_result=result,
+ extra_raw={"source": "api_v1_image"},
)
url = result.local_url or result.remote_url or ""
if url:
@@ -214,6 +213,9 @@ async def get_task(
provider_task_id=tid,
poll_status=str(data.get("status") or ""),
error=str(data.get("error") or "") or None,
+ usage_tokens=int((data.get("usage") or {}).get("total_tokens") or 0),
+ completion_tokens=int((data.get("usage") or {}).get("completion_tokens") or 0),
+ raw_usage=data.get("raw_usage") if isinstance(data.get("raw_usage"), dict) else None,
)
await db.commit()
return V1GenerationOut(
diff --git a/backend/app/config.py b/backend/app/config.py
index db81f8d..8636e17 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -1,10 +1,18 @@
from functools import lru_cache
+from pathlib import Path
from pydantic_settings import BaseSettings, SettingsConfigDict
+_BACKEND_DIR = Path(__file__).resolve().parent.parent
+_ENV_FILE = _BACKEND_DIR / ".env"
+
class Settings(BaseSettings):
- model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
+ model_config = SettingsConfigDict(
+ env_file=str(_ENV_FILE) if _ENV_FILE.is_file() else ".env",
+ env_file_encoding="utf-8",
+ extra="ignore",
+ )
app_name: str = "PRINTFILM"
debug: bool = True
@@ -13,8 +21,8 @@ class Settings(BaseSettings):
secret_key: str = "dev-secret-change-me"
access_token_expire_minutes: int = 60 * 24 * 7
- database_url: str = "sqlite+aiosqlite:///./ai_movie.db"
- database_url_sync: str = "sqlite:///./ai_movie.db"
+ database_url: str = "postgresql+asyncpg://printfilm:[email protected]:15432/printfilm"
+ database_url_sync: str = "postgresql+psycopg2://printfilm:[email protected]:15432/printfilm"
# Postgres 连接池(统一任务平台 / API 共用)
db_pool_size: int = 5
db_max_overflow: int = 5
@@ -63,8 +71,6 @@ class Settings(BaseSettings):
drama_user_video_job_limit: int = 12
# 单个分镜视频最大尝试次数;超过后直接失败,避免长时间卡在同一镜
drama_fragment_max_attempts: int = 3
- # 已废弃:科普不再直出口播(即使 .env 为 true 也会被管线忽略)
- kepu_seedance_generate_audio: bool = False
# 科普 Seedance 仍出音轨:只要操作/环境音效,不要口播与 BGM
kepu_seedance_sfx_audio: bool = True
@@ -102,6 +108,33 @@ class Settings(BaseSettings):
# Signup grant (fen)
billing_signup_grant_fen: int = 500
+ # 用户消费里程碑弹窗(累计扣费每达 interval 分提醒一次;1000 = ¥10)
+ billing_user_alert_enabled: bool = True
+ billing_user_alert_interval_fen: int = 1000
+
+ # 平台总费用邮件告警(按上游 cost_fen 聚合)
+ billing_admin_cost_alert_enabled: bool = False
+ billing_admin_cost_alert_threshold_fen: int = 0
+ billing_admin_cost_alert_emails: str = ""
+ billing_admin_cost_alert_period: str = "monthly"
+ billing_admin_cost_alert_last_period_key: str = ""
+ billing_admin_cost_alert_last_level: int = 0
+
+ # SMTP(管理员费用告警邮件)
+ smtp_enabled: bool = False
+ smtp_host: str = ""
+ smtp_port: int = 587
+ smtp_user: str = ""
+ smtp_password: str = ""
+ smtp_from: str = ""
+ smtp_use_tls: bool = True
+
+ # 火山方舟管控面用量查询(GetInferenceUsage,与 ARK_API_KEY 分离)
+ volc_access_key_id: str = ""
+ volc_secret_access_key: str = ""
+ volc_ark_region: str = "cn-beijing"
+ volc_ark_usage_enabled: bool = True
+
# Epay (pay.gitcc.com)
epay_api_url: str = "https://pay.gitcc.com"
epay_pid: str = ""
diff --git a/backend/app/database.py b/backend/app/database.py
index 187059a..6233047 100644
--- a/backend/app/database.py
+++ b/backend/app/database.py
@@ -1,4 +1,4 @@
-"""Async SQLAlchemy engine / session for API and task runtime."""
+"""Async SQLAlchemy engine / session for API and task runtime(仅 PostgreSQL)。"""
from __future__ import annotations
@@ -15,10 +15,18 @@ settings = get_settings()
class Base(DeclarativeBase):
pass
+
+def _require_postgres(url: str) -> None:
+ """拒绝非 Postgres 连接串,避免误连 SQLite。"""
+ if not (url or "").startswith("postgresql"):
+ raise RuntimeError(
+ "仅支持 PostgreSQL。请设置 DATABASE_URL=postgresql+asyncpg://..."
+ f"(当前:{(url or '')[:48]!r})"
+ )
+
+
def _postgres_pool_kwargs() -> dict:
- """Build QueuePool kwargs for Postgres; empty for SQLite."""
- if not settings.database_url.startswith("postgresql"):
- return {}
+ """Build QueuePool kwargs for Postgres."""
return {
"pool_pre_ping": True,
"pool_size": max(1, int(settings.db_pool_size)),
@@ -28,6 +36,8 @@ def _postgres_pool_kwargs() -> dict:
}
+_require_postgres(settings.database_url)
+
_engine_kwargs: dict = {"echo": bool(settings.sql_echo)}
_engine_kwargs.update(_postgres_pool_kwargs())
@@ -62,9 +72,7 @@ async def dispose_engine() -> None:
def pool_status() -> dict | None:
- """Snapshot SQLAlchemy pool counters for /api/health (Postgres only)."""
- if not settings.database_url.startswith("postgresql"):
- return None
+ """Snapshot SQLAlchemy pool counters for /api/health."""
pool = engine.pool
return {
"role": "api",
diff --git a/backend/app/logging_setup.py b/backend/app/logging_setup.py
index 383490c..7d1cb07 100644
--- a/backend/app/logging_setup.py
+++ b/backend/app/logging_setup.py
@@ -1,4 +1,4 @@
-"""统一应用日志:可读业务日志,默认不刷 SQL / aiosqlite DEBUG。"""
+"""统一应用日志:可读业务日志,默认不刷 SQL DEBUG。"""
from __future__ import annotations
@@ -27,23 +27,20 @@ def configure_logging(*, level: str = "INFO", sql_echo: bool = False) -> None:
root.setLevel(logging.INFO)
logging.getLogger("app").setLevel(getattr(logging, level.upper(), logging.INFO))
- # SQL / SQLite 驱动默认关闭
- sql_level = logging.INFO if sql_echo else logging.WARNING
+ # SQLAlchemy 驱动默认关闭
for name in (
"sqlalchemy",
"sqlalchemy.engine",
"sqlalchemy.pool",
"sqlalchemy.dialects",
- "aiosqlite",
- "sqlite3",
+ "asyncpg",
):
- logging.getLogger(name).setLevel(sql_level if name.startswith("sqlalchemy") else logging.WARNING)
+ logging.getLogger(name).setLevel(logging.WARNING)
if sql_echo:
logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO)
else:
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
- logging.getLogger("aiosqlite").setLevel(logging.WARNING)
# 其他噪音
for name in ("uvicorn.access", "httpx", "httpcore", "celery", "asyncio", "multipart"):
@@ -54,7 +51,7 @@ def configure_logging(*, level: str = "INFO", sql_echo: bool = False) -> None:
if not _configured:
logging.getLogger("app").info(
- "日志已配置 app_level=%s sql_echo=%s(已关闭 aiosqlite/SQL DEBUG)",
+ "日志已配置 app_level=%s sql_echo=%s(已关闭 SQL DEBUG)",
level,
sql_echo,
)
diff --git a/backend/app/main.py b/backend/app/main.py
index c42d651..df8e5ed 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -20,7 +20,7 @@ from app.services.tasks.runtime import runtime_summary, start_task_runtime, stop
from app.services.templates_seed import TEMPLATES
settings = get_settings()
-# 业务日志 INFO;DEBUG=true 不再把根日志打成 DEBUG(避免 aiosqlite 刷屏)
+# 业务日志 INFO;DEBUG=true 不再把根日志打成 DEBUG(避免 SQL 驱动刷屏)
configure_logging(level="INFO", sql_echo=settings.sql_echo)
logger = logging.getLogger("app.http")
@@ -96,7 +96,7 @@ app.include_router(admin_router, prefix="/api")
@app.on_event("startup")
async def on_startup() -> None:
await init_db()
- await _migrate_sqlite()
+ await _apply_schema_patches()
async with AsyncSessionLocal() as db:
from app.services.model_settings import load_model_settings_cache
@@ -122,43 +122,26 @@ async def on_shutdown() -> None:
await dispose_engine()
-async def _migrate_sqlite() -> None:
- """Lightweight additive migrations (SQLite + Postgres)."""
- is_sqlite = settings.database_url.startswith("sqlite")
+async def _pg_columns(conn, table: str) -> set[str]:
+ """读取 information_schema 列名。"""
+ result = await conn.execute(
+ text(
+ "SELECT column_name FROM information_schema.columns "
+ "WHERE table_schema = 'public' AND table_name = :table"
+ ),
+ {"table": table},
+ )
+ return {row[0] for row in result.fetchall()}
+
+
+async def _apply_schema_patches() -> None:
+ """Lightweight additive migrations(仅 PostgreSQL)。"""
async with engine.begin() as conn:
- if is_sqlite:
- result = await conn.execute(text("PRAGMA table_info(shots)"))
- cols = {row[1] for row in result.fetchall()}
- if "image_ark_url" not in cols:
- await conn.execute(text("ALTER TABLE shots ADD COLUMN image_ark_url VARCHAR(1024)"))
- if "overlay_title" not in cols:
- await conn.execute(text("ALTER TABLE shots ADD COLUMN overlay_title VARCHAR(128) DEFAULT ''"))
- if "overlay_subtitle" not in cols:
- await conn.execute(text("ALTER TABLE shots ADD COLUMN overlay_subtitle VARCHAR(256) DEFAULT ''"))
- if "segment_script" not in cols:
- await conn.execute(text("ALTER TABLE shots ADD COLUMN segment_script TEXT DEFAULT ''"))
-
- result = await conn.execute(text("PRAGMA table_info(projects)"))
- pcols = {row[1] for row in result.fetchall()}
- else:
- result = await conn.execute(
- text(
- "SELECT column_name FROM information_schema.columns "
- "WHERE table_name = 'shots'"
- )
- )
- scols = {row[0] for row in result.fetchall()}
- if "segment_script" not in scols:
- await conn.execute(text("ALTER TABLE shots ADD COLUMN segment_script TEXT DEFAULT ''"))
-
- result = await conn.execute(
- text(
- "SELECT column_name FROM information_schema.columns "
- "WHERE table_name = 'projects'"
- )
- )
- pcols = {row[0] for row in result.fetchall()}
+ scols = await _pg_columns(conn, "shots")
+ if "segment_script" not in scols:
+ await conn.execute(text("ALTER TABLE shots ADD COLUMN segment_script TEXT DEFAULT ''"))
+ pcols = await _pg_columns(conn, "projects")
if "pipeline_mode" not in pcols:
await conn.execute(text("ALTER TABLE projects ADD COLUMN pipeline_mode VARCHAR(32) DEFAULT 'full'"))
if "output_ratio" not in pcols:
@@ -177,17 +160,7 @@ async def _migrate_sqlite() -> None:
await conn.execute(text("ALTER TABLE projects ADD COLUMN extra_prompt TEXT DEFAULT ''"))
# User billing columns
- if is_sqlite:
- result = await conn.execute(text("PRAGMA table_info(users)"))
- ucols = {row[1] for row in result.fetchall()}
- else:
- result = await conn.execute(
- text(
- "SELECT column_name FROM information_schema.columns "
- "WHERE table_name = 'users'"
- )
- )
- ucols = {row[0] for row in result.fetchall()}
+ ucols = await _pg_columns(conn, "users")
if "balance_fen" not in ucols:
await conn.execute(text("ALTER TABLE users ADD COLUMN balance_fen INTEGER DEFAULT 0"))
if "frozen_fen" not in ucols:
@@ -204,19 +177,13 @@ async def _migrate_sqlite() -> None:
await conn.execute(text("ALTER TABLE users ADD COLUMN avatar_url VARCHAR(512) DEFAULT ''"))
if "phone" not in ucols:
await conn.execute(text("ALTER TABLE users ADD COLUMN phone VARCHAR(32) DEFAULT ''"))
+ if "billing_alert_last_milestone_fen" not in ucols:
+ await conn.execute(
+ text("ALTER TABLE users ADD COLUMN billing_alert_last_milestone_fen INTEGER DEFAULT 0")
+ )
# UsageEvent.drama_project_id for drama module billing
- if is_sqlite:
- result = await conn.execute(text("PRAGMA table_info(usage_events)"))
- uecols = {row[1] for row in result.fetchall()}
- else:
- result = await conn.execute(
- text(
- "SELECT column_name FROM information_schema.columns "
- "WHERE table_name = 'usage_events'"
- )
- )
- uecols = {row[0] for row in result.fetchall()}
+ uecols = await _pg_columns(conn, "usage_events")
if "drama_project_id" not in uecols:
await conn.execute(text("ALTER TABLE usage_events ADD COLUMN drama_project_id INTEGER"))
if "task_run_id" not in uecols:
@@ -227,41 +194,7 @@ async def _migrate_sqlite() -> None:
await conn.execute(text("ALTER TABLE usage_events ADD COLUMN capability VARCHAR(16)"))
# Task platform additive columns
- if is_sqlite:
- result = await conn.execute(text("PRAGMA table_info(task_runs)"))
- trcols = {row[1] for row in result.fetchall()}
- result = await conn.execute(
- text(
- "CREATE TABLE IF NOT EXISTS task_steps ("
- "id INTEGER PRIMARY KEY, "
- "task_id INTEGER NOT NULL, "
- "step_key VARCHAR(64), "
- "step_type VARCHAR(64) DEFAULT 'job', "
- "status VARCHAR(32) DEFAULT 'pending', "
- "attempt_count INTEGER DEFAULT 0, "
- "provider_name VARCHAR(64), "
- "provider_task_id VARCHAR(128), "
- "input_payload JSON, "
- "output_payload JSON, "
- "error_code VARCHAR(64), "
- "error_message TEXT, "
- "next_poll_at DATETIME, "
- "started_at DATETIME, "
- "finished_at DATETIME, "
- "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
- "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
- "FOREIGN KEY(task_id) REFERENCES task_runs(id) ON DELETE CASCADE"
- ")"
- )
- )
- else:
- result = await conn.execute(
- text(
- "SELECT column_name FROM information_schema.columns "
- "WHERE table_name = 'task_runs'"
- )
- )
- trcols = {row[0] for row in result.fetchall()}
+ trcols = await _pg_columns(conn, "task_runs")
if "dedupe_key" not in trcols:
await conn.execute(text("ALTER TABLE task_runs ADD COLUMN dedupe_key VARCHAR(128)"))
if "batch_key" not in trcols:
@@ -271,13 +204,13 @@ async def _migrate_sqlite() -> None:
if "current_step_status" not in trcols:
await conn.execute(text("ALTER TABLE task_runs ADD COLUMN current_step_status VARCHAR(32)"))
if "scheduled_at" not in trcols:
- await conn.execute(text("ALTER TABLE task_runs ADD COLUMN scheduled_at DATETIME"))
+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN scheduled_at TIMESTAMP"))
if "next_action_at" not in trcols:
- await conn.execute(text("ALTER TABLE task_runs ADD COLUMN next_action_at DATETIME"))
+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN next_action_at TIMESTAMP"))
if "lease_token" not in trcols:
await conn.execute(text("ALTER TABLE task_runs ADD COLUMN lease_token VARCHAR(64)"))
if "lease_until" not in trcols:
- await conn.execute(text("ALTER TABLE task_runs ADD COLUMN lease_until DATETIME"))
+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN lease_until TIMESTAMP"))
if "billing_estimate_fen" not in trcols:
await conn.execute(text("ALTER TABLE task_runs ADD COLUMN billing_estimate_fen INTEGER DEFAULT 0"))
if "billing_charged_fen" not in trcols:
diff --git a/backend/app/models.py b/backend/app/models.py
index 1aeaa46..989a9e3 100644
--- a/backend/app/models.py
+++ b/backend/app/models.py
@@ -1,7 +1,7 @@
-from datetime import datetime
+from datetime import date, datetime
from enum import StrEnum
-from sqlalchemy import JSON, Boolean, DateTime, Float, ForeignKey, Integer, String, Text, func
+from sqlalchemy import JSON, Boolean, Date, DateTime, Float, ForeignKey, Integer, String, Text, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database import Base
@@ -50,11 +50,28 @@ class User(Base):
avatar_url: Mapped[str] = mapped_column(String(512), default="")
# 联系手机,仅记录,不走短信验证
phone: Mapped[str] = mapped_column(String(32), default="")
+ # 用户消费里程碑告警:上次已提醒的累计扣费档位(分)
+ billing_alert_last_milestone_fen: Mapped[int] = mapped_column(Integer, default=0)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
projects: Mapped[list["Project"]] = relationship(back_populates="owner")
+class BillingAlertNotification(Base):
+ """待展示的用户额度告警(弹窗)。"""
+
+ __tablename__ = "billing_alert_notifications"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ user_id: Mapped[int] = mapped_column(Integer, index=True)
+ kind: Mapped[str] = mapped_column(String(32), default="user_milestone")
+ title: Mapped[str] = mapped_column(String(128), default="")
+ message: Mapped[str] = mapped_column(Text, default="")
+ milestone_fen: Mapped[int] = mapped_column(Integer, default=0)
+ acknowledged: Mapped[bool] = mapped_column(Boolean, default=False)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+
+
class Template(Base):
__tablename__ = "templates"
@@ -205,6 +222,21 @@ class UsageEvent(Base):
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+class UpstreamUsageDaily(Base):
+ """方舟官方日用量快照,用于与本地 usage_events 对照。"""
+
+ __tablename__ = "upstream_usage_daily"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ usage_date: Mapped[date] = mapped_column(Date, unique=True, index=True)
+ official_tokens: Mapped[int] = mapped_column(Integer, default=0)
+ official_cost_fen: Mapped[int] = mapped_column(Integer, default=0)
+ local_cost_fen: Mapped[int] = mapped_column(Integer, default=0)
+ local_tokens: Mapped[int] = mapped_column(Integer, default=0)
+ raw_json: Mapped[str | None] = mapped_column(Text, nullable=True)
+ fetched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+
+
class WalletLedger(Base):
__tablename__ = "wallet_ledger"
diff --git a/backend/app/schemas.py b/backend/app/schemas.py
index 99b69a9..bbe2e05 100644
--- a/backend/app/schemas.py
+++ b/backend/app/schemas.py
@@ -272,12 +272,14 @@ class AdminUsageBucketOut(BaseModel):
key: str
calls: int = 0
charge_fen: int = 0
+ cost_fen: int = 0
class AdminDailyUsageOut(BaseModel):
date: str
calls: int = 0
charge_fen: int = 0
+ cost_fen: int = 0
class AdminTopUserOut(BaseModel):
@@ -287,6 +289,32 @@ class AdminTopUserOut(BaseModel):
charge_fen: int = 0
+class AdminUpstreamUsageDayOut(BaseModel):
+ """官方与本地上游成本对照(单日)。"""
+
+ date: str
+ local_cost_fen: int = 0
+ local_tokens: int = 0
+ official_tokens: int = 0
+ official_cost_fen: int = 0
+ delta_fen: int = 0
+ delta_pct: float | None = None
+
+
+class AdminUpstreamUsageOut(BaseModel):
+ configured: bool = False
+ days: int = 30
+ last_sync_at: str | None = None
+ series: list[AdminUpstreamUsageDayOut] = Field(default_factory=list)
+
+
+class AdminUpstreamUsageSyncOut(BaseModel):
+ configured: bool = False
+ synced: int = 0
+ skipped: int = 0
+ last_sync_at: str | None = None
+
+
class AdminProjectUsageOut(BaseModel):
"""项目级用量摘要。"""
@@ -495,7 +523,7 @@ class AdminProjectDetailOut(AdminProjectOut):
class AdminWorkOut(BaseModel):
id: int
- project_id: int
+ project_id: int | None = None
user_id: int
user_email: str | None = None
title: str
diff --git a/backend/app/schemas_settings.py b/backend/app/schemas_settings.py
index a32c1ff..1bdb95b 100644
--- a/backend/app/schemas_settings.py
+++ b/backend/app/schemas_settings.py
@@ -112,6 +112,33 @@ class AdminModelSettingsOut(BaseModel):
quota_enabled: bool = False
new_user_quota: int = 5
+ # 额度告警
+ billing_user_alert_enabled: bool = True
+ billing_user_alert_interval_fen: int = 1000
+ billing_admin_cost_alert_enabled: bool = False
+ billing_admin_cost_alert_threshold_fen: int = 0
+ billing_admin_cost_alert_emails: str = ""
+ billing_admin_cost_alert_period: str = "monthly"
+ billing_admin_cost_alert_last_period_key: str = ""
+ billing_admin_cost_alert_last_level: int = 0
+
+ smtp_enabled: bool = False
+ smtp_host: str = ""
+ smtp_port: int = 587
+ smtp_user: str = ""
+ smtp_password: str = ""
+ smtp_from: str = ""
+ smtp_use_tls: bool = True
+ has_smtp_password: bool = False
+
+ # 火山管控面用量查询(GetInferenceUsage,后台配置,不入 .env)
+ volc_access_key_id: str = ""
+ volc_secret_access_key: str = ""
+ volc_ark_region: str = "cn-beijing"
+ volc_ark_usage_enabled: bool = True
+ has_volc_access_key_id: bool = False
+ has_volc_secret_access_key: bool = False
+
# 站点与工具
public_base_url: str = ""
ffmpeg_path: str = "ffmpeg"
@@ -212,6 +239,29 @@ class AdminModelSettingsPatch(BaseModel):
quota_enabled: bool | None = None
new_user_quota: int | None = None
+ billing_user_alert_enabled: bool | None = None
+ billing_user_alert_interval_fen: int | None = None
+ billing_admin_cost_alert_enabled: bool | None = None
+ billing_admin_cost_alert_threshold_fen: int | None = None
+ billing_admin_cost_alert_emails: str | None = None
+ billing_admin_cost_alert_period: str | None = None
+
+ smtp_enabled: bool | None = None
+ smtp_host: str | None = None
+ smtp_port: int | None = None
+ smtp_user: str | None = None
+ smtp_password: str | None = None
+ smtp_from: str | None = None
+ smtp_use_tls: bool | None = None
+ clear_smtp_password: bool = False
+
+ volc_access_key_id: str | None = None
+ volc_secret_access_key: str | None = None
+ volc_ark_region: str | None = None
+ volc_ark_usage_enabled: bool | None = None
+ clear_volc_access_key_id: bool = False
+ clear_volc_secret_access_key: bool = False
+
public_base_url: str | None = None
ffmpeg_path: str | None = None
ffprobe_path: str | None = None
@@ -305,6 +355,25 @@ def model_config_field_names() -> tuple[str, ...]:
"billing_signup_grant_fen",
"quota_enabled",
"new_user_quota",
+ "billing_user_alert_enabled",
+ "billing_user_alert_interval_fen",
+ "billing_admin_cost_alert_enabled",
+ "billing_admin_cost_alert_threshold_fen",
+ "billing_admin_cost_alert_emails",
+ "billing_admin_cost_alert_period",
+ "billing_admin_cost_alert_last_period_key",
+ "billing_admin_cost_alert_last_level",
+ "smtp_enabled",
+ "smtp_host",
+ "smtp_port",
+ "smtp_user",
+ "smtp_password",
+ "smtp_from",
+ "smtp_use_tls",
+ "volc_access_key_id",
+ "volc_secret_access_key",
+ "volc_ark_region",
+ "volc_ark_usage_enabled",
"public_base_url",
"ffmpeg_path",
"ffprobe_path",
@@ -321,6 +390,9 @@ SECRET_FIELD_FLAGS: dict[str, str] = {
"tos_access_key": "has_tos_access_key",
"tos_secret_key": "has_tos_secret_key",
"epay_key": "has_epay_key",
+ "volc_access_key_id": "has_volc_access_key_id",
+ "volc_secret_access_key": "has_volc_secret_access_key",
+ "smtp_password": "has_smtp_password",
}
SECRET_FIELDS = tuple(SECRET_FIELD_FLAGS.keys())
diff --git a/backend/app/schemas_tasks.py b/backend/app/schemas_tasks.py
index d1d11f3..a2be124 100644
--- a/backend/app/schemas_tasks.py
+++ b/backend/app/schemas_tasks.py
@@ -242,7 +242,10 @@ class AdminUsageEventBriefOut(BaseModel):
model: str = ""
total_tokens: int = 0
charge_fen: int = 0
+ cost_fen: int = 0
estimated: bool = False
+ billing_basis: str = "estimate"
+ billing_basis_label: str = "估算"
created_at: datetime | None = None
model_config = {"from_attributes": True}
@@ -255,14 +258,19 @@ class AdminUsageEventOut(BaseModel):
user_id: int
user_email: str | None = None
task_run_id: int | None = None
+ project_id: int | None = None
+ drama_project_id: int | None = None
domain: str | None = None
capability: str | None = None
billing_key: str
model: str = ""
+ provider: str | None = None
total_tokens: int = 0
charge_fen: int = 0
cost_fen: int = 0
estimated: bool = False
+ billing_basis: str = "estimate"
+ billing_basis_label: str = "估算"
created_at: datetime | None = None
task_domain: str | None = None
task_type: str | None = None
diff --git a/backend/app/services/admin/stats.py b/backend/app/services/admin/stats.py
index 65f942a..6354b7d 100644
--- a/backend/app/services/admin/stats.py
+++ b/backend/app/services/admin/stats.py
@@ -33,23 +33,33 @@ def _day_key(value: Any) -> str:
async def _usage_day_expr(db: AsyncSession):
- """
- 按日历日分桶。
- Postgres 用 CAST AS DATE;SQLite 用 date()(cast(Date) 会踩到结果处理器)。
- """
- conn = await db.connection()
- if conn.dialect.name.startswith("postgres"):
- return cast(UsageEvent.created_at, Date)
- return func.date(UsageEvent.created_at)
+ """按日历日分桶(PostgreSQL CAST AS DATE)。"""
+ _ = db
+ return cast(UsageEvent.created_at, Date)
+
+
+def _usage_scope_filters(
+ *,
+ domain: str = "all",
+ capability: str = "all",
+) -> list[Any]:
+ """领域 / 能力筛选条件(不含时间)。"""
+ filters: list[Any] = []
+ if domain and domain != "all":
+ filters.append(UsageEvent.domain == domain)
+ if capability and capability != "all":
+ filters.append(UsageEvent.capability == capability)
+ return filters
async def _usage_window_totals(
db: AsyncSession,
*,
since: datetime | None = None,
+ scope_filters: list[Any] | None = None,
) -> dict[str, int]:
"""聚合 usage_events:calls / charge / cost。"""
- filters = []
+ filters: list[Any] = list(scope_filters or [])
if since is not None:
filters.append(UsageEvent.created_at >= since)
stmt = select(
@@ -72,6 +82,7 @@ async def _group_usage(
*,
group_col,
since: datetime | None = None,
+ scope_filters: list[Any] | None = None,
limit: int | None = None,
) -> list[dict[str, Any]]:
"""按某一列分组聚合 usage。"""
@@ -81,27 +92,43 @@ async def _group_usage(
key.label("key"),
func.count(UsageEvent.id).label("calls"),
func.coalesce(func.sum(UsageEvent.charge_fen), 0).label("charge_fen"),
+ func.coalesce(func.sum(UsageEvent.cost_fen), 0).label("cost_fen"),
)
.group_by(key)
.order_by(func.coalesce(func.sum(UsageEvent.charge_fen), 0).desc())
)
+ filters: list[Any] = list(scope_filters or [])
if since is not None:
- stmt = stmt.where(UsageEvent.created_at >= since)
+ filters.append(UsageEvent.created_at >= since)
+ for clause in filters:
+ stmt = stmt.where(clause)
if limit is not None:
stmt = stmt.limit(limit)
rows = (await db.execute(stmt)).all()
return [
- {"key": str(r.key or "unknown"), "calls": int(r.calls or 0), "charge_fen": int(r.charge_fen or 0)}
+ {
+ "key": str(r.key or "unknown"),
+ "calls": int(r.calls or 0),
+ "charge_fen": int(r.charge_fen or 0),
+ "cost_fen": int(r.cost_fen or 0),
+ }
for r in rows
]
-async def build_admin_dashboard_stats(db: AsyncSession) -> dict[str, Any]:
+async def build_admin_dashboard_stats(
+ db: AsyncSession,
+ *,
+ days: int = 7,
+ domain: str = "all",
+ capability: str = "all",
+) -> dict[str, Any]:
"""组装管理端仪表盘全部统计字段。"""
today = _utc_today_start()
month = _utc_month_start()
- week_ago = today - timedelta(days=6)
- month_ago = today - timedelta(days=29)
+ window_days = max(1, min(30, int(days)))
+ range_start = today - timedelta(days=window_days - 1)
+ scope = _usage_scope_filters(domain=domain, capability=capability)
user_count = int((await db.execute(select(func.count()).select_from(User))).scalar_one() or 0)
drama_project_count = int(
@@ -138,52 +165,67 @@ async def build_admin_dashboard_stats(db: AsyncSession) -> dict[str, Any]:
today_u = await _usage_window_totals(db, since=today)
month_u = await _usage_window_totals(db, since=month)
- by_capability = await _group_usage(db, group_col=UsageEvent.capability, since=month)
- by_domain = await _group_usage(db, group_col=UsageEvent.domain, since=month)
+ by_capability = await _group_usage(
+ db, group_col=UsageEvent.capability, since=range_start, scope_filters=scope
+ )
+ by_domain = await _group_usage(
+ db, group_col=UsageEvent.domain, since=range_start, scope_filters=scope
+ )
- # 近 7 日按日趋势(方言安全的日分桶)
+ # 按日趋势(筛选窗口内补零)
day_expr = await _usage_day_expr(db)
- daily_rows = (
- await db.execute(
- select(
- day_expr.label("day"),
- func.count(UsageEvent.id).label("calls"),
- func.coalesce(func.sum(UsageEvent.charge_fen), 0).label("charge_fen"),
- )
- .where(UsageEvent.created_at >= week_ago)
- .group_by(day_expr)
- .order_by(day_expr.asc())
+ daily_stmt = (
+ select(
+ day_expr.label("day"),
+ func.count(UsageEvent.id).label("calls"),
+ func.coalesce(func.sum(UsageEvent.charge_fen), 0).label("charge_fen"),
+ func.coalesce(func.sum(UsageEvent.cost_fen), 0).label("cost_fen"),
)
- ).all()
+ .where(UsageEvent.created_at >= range_start)
+ .group_by(day_expr)
+ .order_by(day_expr.asc())
+ )
+ for clause in scope:
+ daily_stmt = daily_stmt.where(clause)
+ daily_rows = (await db.execute(daily_stmt)).all()
daily_map: dict[str, dict[str, int]] = {}
for r in daily_rows:
daily_map[_day_key(r.day)] = {
"calls": int(r.calls or 0),
"charge_fen": int(r.charge_fen or 0),
+ "cost_fen": int(r.cost_fen or 0),
}
daily_usage: list[dict[str, Any]] = []
- for i in range(7):
- key = (week_ago + timedelta(days=i)).date().isoformat()
- hit = daily_map.get(key) or {"calls": 0, "charge_fen": 0}
- daily_usage.append({"date": key, "calls": hit["calls"], "charge_fen": hit["charge_fen"]})
+ for i in range(window_days):
+ key = (range_start + timedelta(days=i)).date().isoformat()
+ hit = daily_map.get(key) or {"calls": 0, "charge_fen": 0, "cost_fen": 0}
+ daily_usage.append(
+ {
+ "date": key,
+ "calls": hit["calls"],
+ "charge_fen": hit["charge_fen"],
+ "cost_fen": hit["cost_fen"],
+ }
+ )
- # 近 30 日用户消费 Top10
+ # 筛选窗口内用户消费 Top10
owner = aliased(User)
- top_rows = (
- await db.execute(
- select(
- UsageEvent.user_id,
- owner.email,
- func.count(UsageEvent.id).label("calls"),
- func.coalesce(func.sum(UsageEvent.charge_fen), 0).label("charge_fen"),
- )
- .outerjoin(owner, owner.id == UsageEvent.user_id)
- .where(UsageEvent.created_at >= month_ago)
- .group_by(UsageEvent.user_id, owner.email)
- .order_by(func.coalesce(func.sum(UsageEvent.charge_fen), 0).desc())
- .limit(10)
+ top_stmt = (
+ select(
+ UsageEvent.user_id,
+ owner.email,
+ func.count(UsageEvent.id).label("calls"),
+ func.coalesce(func.sum(UsageEvent.charge_fen), 0).label("charge_fen"),
)
- ).all()
+ .outerjoin(owner, owner.id == UsageEvent.user_id)
+ .where(UsageEvent.created_at >= range_start)
+ .group_by(UsageEvent.user_id, owner.email)
+ .order_by(func.coalesce(func.sum(UsageEvent.charge_fen), 0).desc())
+ .limit(10)
+ )
+ for clause in scope:
+ top_stmt = top_stmt.where(clause)
+ top_rows = (await db.execute(top_stmt)).all()
top_users_by_charge = [
{
"user_id": int(r.user_id),
diff --git a/backend/app/services/admin/upstream_usage.py b/backend/app/services/admin/upstream_usage.py
new file mode 100644
index 0000000..ff792cf
--- /dev/null
+++ b/backend/app/services/admin/upstream_usage.py
@@ -0,0 +1,185 @@
+"""管理端:官方上游用量快照与本地成本对照。"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, date, datetime, timedelta
+from typing import Any
+
+from sqlalchemy import Date, cast, func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import Settings, get_settings
+from app.models import UpstreamUsageDaily, UsageEvent
+from app.services.ark_control_usage import get_inference_usage, volc_usage_configured
+from app.services.billing.pricing import charge_fen_for_tokens
+
+
+def _utc_today() -> date:
+ return datetime.now(UTC).date()
+
+
+def _tokens_to_official_cost_fen(tokens: int, settings: Settings | None = None) -> int:
+ """按 seedance video0 单价估算官方 token 成本(对照图仅供参考)。"""
+ s = settings or get_settings()
+ cost, _charge = charge_fen_for_tokens(int(tokens), "seedance2:video0", settings=s)
+ return int(cost or 0)
+
+
+async def _local_seedance_daily(
+ db: AsyncSession,
+ *,
+ since: date,
+ until: date,
+) -> dict[str, dict[str, int]]:
+ day_expr = cast(UsageEvent.created_at, Date)
+ rows = (
+ await db.execute(
+ select(
+ day_expr.label("day"),
+ func.coalesce(func.sum(UsageEvent.cost_fen), 0).label("cost_fen"),
+ func.coalesce(func.sum(UsageEvent.total_tokens), 0).label("tokens"),
+ )
+ .where(
+ UsageEvent.billing_key.like("seedance%"),
+ day_expr >= since,
+ day_expr <= until,
+ )
+ .group_by(day_expr)
+ .order_by(day_expr.asc())
+ )
+ ).all()
+ out: dict[str, dict[str, int]] = {}
+ for row in rows:
+ key = str(row.day)[:10]
+ out[key] = {
+ "local_cost_fen": int(row.cost_fen or 0),
+ "local_tokens": int(row.tokens or 0),
+ }
+ return out
+
+
+async def sync_upstream_usage(
+ db: AsyncSession,
+ *,
+ days: int = 30,
+ force: bool = False,
+) -> dict[str, Any]:
+ """拉取官方日用量并写入 upstream_usage_daily。"""
+ if not volc_usage_configured():
+ return {"configured": False, "synced": 0, "skipped": 0}
+
+ s = get_settings()
+ today = _utc_today()
+ start = today - timedelta(days=max(1, int(days)) - 1)
+ local_map = await _local_seedance_daily(db, since=start, until=today)
+
+ synced = 0
+ skipped = 0
+ now = datetime.now(UTC)
+ one_hour_ago = now - timedelta(hours=1)
+
+ # 按 7 日窗口批量请求,减少管控面调用次数
+ window_start = start
+ official_daily: dict[str, int] = {}
+ while window_start <= today:
+ window_end = min(window_start + timedelta(days=6), today)
+ payload = await get_inference_usage(
+ window_start.isoformat(),
+ window_end.isoformat(),
+ settings=s,
+ )
+ for day_key, tokens in (payload.get("daily_tokens") or {}).items():
+ official_daily[str(day_key)[:10]] = int(tokens or 0)
+ window_start = window_end + timedelta(days=1)
+
+ cur = start
+ while cur <= today:
+ day_key = cur.isoformat()
+ existing = (
+ await db.execute(select(UpstreamUsageDaily).where(UpstreamUsageDaily.usage_date == cur))
+ ).scalar_one_or_none()
+ if (
+ existing
+ and not force
+ and existing.fetched_at
+ and existing.fetched_at.replace(tzinfo=UTC) >= one_hour_ago
+ ):
+ skipped += 1
+ cur += timedelta(days=1)
+ continue
+
+ tokens = int(official_daily.get(day_key, 0))
+ local_hit = local_map.get(day_key) or {"local_cost_fen": 0, "local_tokens": 0}
+ row = existing or UpstreamUsageDaily(usage_date=cur)
+ row.official_tokens = tokens
+ row.official_cost_fen = _tokens_to_official_cost_fen(tokens, s)
+ row.local_cost_fen = int(local_hit["local_cost_fen"])
+ row.local_tokens = int(local_hit["local_tokens"])
+ row.raw_json = json.dumps({"day": day_key, "official_tokens": tokens}, ensure_ascii=False)[:4000]
+ row.fetched_at = now
+ if existing is None:
+ db.add(row)
+ synced += 1
+ cur += timedelta(days=1)
+
+ await db.commit()
+ return {"configured": True, "synced": synced, "skipped": skipped, "last_sync_at": now.isoformat()}
+
+
+async def build_upstream_usage_compare(
+ db: AsyncSession,
+ *,
+ days: int = 30,
+) -> dict[str, Any]:
+ """返回近 N 日官方/本地成本对照序列。"""
+ today = _utc_today()
+ start = today - timedelta(days=max(1, int(days)) - 1)
+ rows = (
+ await db.execute(
+ select(UpstreamUsageDaily)
+ .where(UpstreamUsageDaily.usage_date >= start)
+ .order_by(UpstreamUsageDaily.usage_date.asc())
+ )
+ ).scalars().all()
+ row_map = {r.usage_date.isoformat(): r for r in rows}
+ local_map = await _local_seedance_daily(db, since=start, until=today)
+
+ series: list[dict[str, Any]] = []
+ cur = start
+ last_sync_at: str | None = None
+ while cur <= today:
+ key = cur.isoformat()
+ snap = row_map.get(key)
+ local_hit = local_map.get(key) or {"local_cost_fen": 0, "local_tokens": 0}
+ official_tokens = int(snap.official_tokens if snap else 0)
+ official_cost = int(snap.official_cost_fen if snap else 0)
+ local_cost = int(snap.local_cost_fen if snap else local_hit["local_cost_fen"])
+ local_tokens = int(snap.local_tokens if snap else local_hit["local_tokens"])
+ delta_fen = local_cost - official_cost
+ delta_pct: float | None = None
+ if official_cost > 0:
+ delta_pct = round(delta_fen / official_cost * 100.0, 2)
+ elif local_cost > 0:
+ delta_pct = None
+ series.append(
+ {
+ "date": key,
+ "local_cost_fen": local_cost,
+ "local_tokens": local_tokens,
+ "official_tokens": official_tokens,
+ "official_cost_fen": official_cost,
+ "delta_fen": delta_fen,
+ "delta_pct": delta_pct,
+ }
+ )
+ if snap and snap.fetched_at:
+ last_sync_at = snap.fetched_at.isoformat()
+ cur += timedelta(days=1)
+
+ return {
+ "configured": volc_usage_configured(),
+ "days": int(days),
+ "last_sync_at": last_sync_at,
+ "series": series,
+ }
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index 0ee400e..648bc07 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -17,6 +17,7 @@ from urllib.parse import urlparse
import httpx
from app.config import Settings, get_settings
+from app.services.billing.pricing import parse_upstream_cost_fen, parse_usage_dict
from app.schemas_routing import ResolvedModelRoute
from app.services.logical_model_router import resolve_logical_model, resolve_logical_model_id
from app.services import storage
@@ -159,6 +160,50 @@ class TaskResult:
url: str | None = None
last_frame_url: str | None = None
error: str | None = None
+ total_tokens: int = 0
+ completion_tokens: int = 0
+ raw_usage: dict[str, Any] | None = None
+ provider_task_id: str | None = None
+
+
+# 从 Seedance 任务查询响应解析状态、媒体 URL 与官方 usage
+def _build_task_result_from_payload(data: dict[str, Any]) -> TaskResult:
+ status = str(data.get("status", "")).lower() or "running"
+ usage_parsed = parse_usage_dict(data)
+ total_tokens = int(usage_parsed.get("total_tokens") or 0)
+ completion_tokens = int(usage_parsed.get("completion_tokens") or 0)
+ raw_usage = data.get("usage") if isinstance(data.get("usage"), dict) else None
+
+ if status in {"succeeded", "success"}:
+ url = None
+ content = data.get("content")
+ if isinstance(content, dict):
+ url = content.get("video_url")
+ if not url:
+ url = data.get("video_url")
+ return TaskResult(
+ status="succeeded",
+ url=url,
+ last_frame_url=_extract_seedance_last_frame_url(data),
+ total_tokens=total_tokens,
+ completion_tokens=completion_tokens,
+ raw_usage=raw_usage,
+ )
+ if status in {"failed", "cancelled", "canceled", "expired"}:
+ err = data.get("error") or data.get("message") or status
+ return TaskResult(
+ status="failed",
+ error=str(err),
+ total_tokens=total_tokens,
+ completion_tokens=completion_tokens,
+ raw_usage=raw_usage,
+ )
+ return TaskResult(
+ status="running",
+ total_tokens=total_tokens,
+ completion_tokens=completion_tokens,
+ raw_usage=raw_usage,
+ )
# 从 Seedance 任务成功响应中提取尾帧 URL
@@ -240,6 +285,11 @@ def _format_seedance_create_error(
class ImageResult:
local_url: str
remote_url: str | None = None
+ total_tokens: int = 0
+ prompt_tokens: int = 0
+ completion_tokens: int = 0
+ raw_usage: dict[str, Any] | None = None
+ upstream_cost_fen: int | None = None
class ArkGateway:
@@ -250,13 +300,37 @@ class ArkGateway:
def settings(self) -> Settings:
return self._settings_override or get_settings()
+ # 优先后台渠道 Key,env 仅作空渠道时的兜底
+ def _ark_api_key(self) -> str:
+ try:
+ from app.services.model_settings import get_routing_snapshot
+
+ channels = get_routing_snapshot().channels
+ except Exception: # noqa: BLE001
+ channels = []
+ ark_channels = [
+ ch
+ for ch in channels
+ if ch.enabled
+ and (ch.api_key or "").strip()
+ and (
+ ch.protocol == "ark"
+ or ch.api_format == "ark"
+ or "ark.cn-beijing.volces.com" in (ch.base_url or "")
+ )
+ ]
+ if ark_channels:
+ preferred = next((ch for ch in ark_channels if ch.id == "ark-default"), ark_channels[0])
+ return (preferred.api_key or "").strip()
+ return (self.settings.ark_api_key or "").strip()
+
@property
def mock(self) -> bool:
- return self.settings.ark_mock or not self.settings.ark_api_key
+ return self.settings.ark_mock or not self._ark_api_key()
def _headers(self) -> dict[str, str]:
return {
- "Authorization": f"Bearer {self.settings.ark_api_key}",
+ "Authorization": f"Bearer {self._ark_api_key()}",
"Content-Type": "application/json",
}
@@ -595,6 +669,17 @@ class ArkGateway:
_raise_seedream_http_error(resp.status_code, resp.text)
data = resp.json()
+ usage_parsed = parse_usage_dict(data)
+ raw_usage = data.get("usage") if isinstance(data.get("usage"), dict) else None
+ if not raw_usage and isinstance(data.get("data"), list) and data["data"]:
+ first = data["data"][0]
+ if isinstance(first, dict) and isinstance(first.get("usage"), dict):
+ raw_usage = first["usage"]
+ usage_parsed = parse_usage_dict({"usage": raw_usage})
+ upstream_cost_fen = parse_upstream_cost_fen(data)
+ if upstream_cost_fen is None and raw_usage:
+ upstream_cost_fen = parse_upstream_cost_fen({"usage": raw_usage})
+
remote = self._extract_image_url(data)
if not remote:
raise RuntimeError(f"Seedream missing url: {json.dumps(data)[:500]}")
@@ -603,7 +688,15 @@ class ArkGateway:
name = f"shot_{(shot_no or 0):03d}_{hashlib.md5(prompt_hash_src.encode()).hexdigest()[:8]}.png"
dest = dest_dir / name
await storage.download_to(remote, dest)
- return ImageResult(local_url=storage.publish_local(dest), remote_url=remote)
+ return ImageResult(
+ local_url=storage.publish_local(dest),
+ remote_url=remote,
+ total_tokens=int(usage_parsed.get("total_tokens") or 0),
+ prompt_tokens=int(usage_parsed.get("prompt_tokens") or 0),
+ completion_tokens=int(usage_parsed.get("completion_tokens") or 0),
+ raw_usage=raw_usage,
+ upstream_cost_fen=upstream_cost_fen,
+ )
@staticmethod
def _sanitize_seedream_prompt(prompt: str) -> str:
@@ -872,8 +965,8 @@ class ArkGateway:
shot_no: int,
max_attempts: int = 2,
content_labels: list[str] | None = None,
- ) -> tuple[str, str | None]:
- """创建 Seedance 多模态任务并等待完成;返回 (本地视频 URL, 可选本地尾帧 URL)。"""
+ ) -> tuple[str, str | None, TaskResult]:
+ """创建 Seedance 多模态任务并等待完成;返回 (本地视频 URL, 可选本地尾帧 URL, 任务结果)。"""
def _is_audio_download_error(err: Exception) -> bool:
msg = str(err)
return "audio_url" in msg and "resource download failed" in msg
@@ -952,24 +1045,14 @@ class ArkGateway:
if resp.status_code >= 400:
return TaskResult(status="failed", error=resp.text[:500])
data = resp.json()
- status = str(data.get("status", "")).lower()
- if status in {"succeeded", "success"}:
- url = None
- content = data.get("content")
- if isinstance(content, dict):
- url = content.get("video_url")
- if not url:
- url = data.get("video_url")
- return TaskResult(
- status="succeeded",
- url=url,
- last_frame_url=_extract_seedance_last_frame_url(data),
- )
- if status in {"failed", "cancelled", "canceled", "expired"}:
- err = data.get("error") or data.get("message") or status
- return TaskResult(status="failed", error=str(err))
+ result = _build_task_result_from_payload(data)
+ result.provider_task_id = task_id
+ if result.status == "succeeded":
+ return result
+ if result.status == "failed":
+ return result
await asyncio.sleep(self.settings.ark_video_poll_interval)
- return TaskResult(status="failed", error="poll timeout")
+ return TaskResult(status="failed", error="poll timeout", provider_task_id=task_id)
async def fetch_task_once(self, task_id: str) -> TaskResult:
"""单次查询 Seedance 任务,不阻塞等待。"""
@@ -985,25 +1068,10 @@ class ArkGateway:
headers=self._headers(),
)
if resp.status_code >= 400:
- return TaskResult(status="failed", error=resp.text[:500])
- data = resp.json()
- status = str(data.get("status", "")).lower() or "running"
- if status in {"succeeded", "success"}:
- url = None
- content = data.get("content")
- if isinstance(content, dict):
- url = content.get("video_url")
- if not url:
- url = data.get("video_url")
- return TaskResult(
- status="succeeded",
- url=url,
- last_frame_url=_extract_seedance_last_frame_url(data),
- )
- if status in {"failed", "cancelled", "canceled", "expired"}:
- err = data.get("error") or data.get("message") or status
- return TaskResult(status="failed", error=str(err))
- return TaskResult(status="running")
+ return TaskResult(status="failed", error=resp.text[:500], provider_task_id=task_id)
+ result = _build_task_result_from_payload(resp.json())
+ result.provider_task_id = task_id
+ return result
async def save_video_assets_from_result(
self,
@@ -1048,14 +1116,15 @@ class ArkGateway:
*,
project_id: int,
shot_no: int,
- ) -> tuple[str, str | None]:
+ ) -> tuple[str, str | None, TaskResult]:
"""等待任务完成并落盘视频;若有尾帧则一并落盘。"""
result = await self.poll_task(task_id)
- return await self.save_video_assets_from_result(
+ video_local, last_local = await self.save_video_assets_from_result(
result,
project_id=project_id,
shot_no=shot_no,
)
+ return video_local, last_local, result
async def wait_video(
self,
@@ -1063,11 +1132,11 @@ class ArkGateway:
*,
project_id: int,
shot_no: int,
- ) -> str:
- video_local, _last = await self.wait_video_assets(
+ ) -> tuple[str, TaskResult]:
+ video_local, _last, result = await self.wait_video_assets(
task_id, project_id=project_id, shot_no=shot_no
)
- return video_local
+ return video_local, result
async def gen_and_wait_video(
self,
@@ -1082,7 +1151,7 @@ class ArkGateway:
ratio: str | None = None,
max_attempts: int = 3,
generate_audio: bool = False,
- ) -> str:
+ ) -> tuple[str, TaskResult]:
"""Create Seedance i2v task and wait; retry on summary_caption / transient BodyFormat."""
last_err: Exception | None = None
for attempt in range(max_attempts):
@@ -1098,7 +1167,11 @@ class ArkGateway:
prompt_as_json=use_json,
generate_audio=generate_audio,
)
- return await self.wait_video(task_id, project_id=project_id, shot_no=shot_no)
+ return await self.wait_video(
+ task_id,
+ project_id=project_id,
+ shot_no=shot_no,
+ )
except Exception as exc: # noqa: BLE001
last_err = exc
msg = str(exc)
diff --git a/backend/app/services/ark_control_usage.py b/backend/app/services/ark_control_usage.py
new file mode 100644
index 0000000..5df1a63
--- /dev/null
+++ b/backend/app/services/ark_control_usage.py
@@ -0,0 +1,204 @@
+"""火山方舟管控面 GetInferenceUsage 客户端(HMAC 签名)。"""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import json
+import logging
+from datetime import UTC, datetime
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from app.config import Settings, get_settings
+
+logger = logging.getLogger(__name__)
+
+HOST = "open.volcengineapi.com"
+SERVICE = "ark"
+VERSION = "2024-01-01"
+ACTION = "GetInferenceUsage"
+
+
+def volc_usage_configured(settings: Settings | None = None) -> bool:
+ s = settings or get_settings()
+ return bool(
+ s.volc_ark_usage_enabled
+ and (s.volc_access_key_id or "").strip()
+ and (s.volc_secret_access_key or "").strip()
+ )
+
+
+def _hash_sha256(content: str) -> str:
+ return hashlib.sha256(content.encode("utf-8")).hexdigest()
+
+
+def _hmac_sha256(key: bytes, msg: str) -> bytes:
+ return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
+
+
+def _signing_key(secret_key: str, date_stamp: str, region: str, service: str) -> bytes:
+ k_date = _hmac_sha256(secret_key.encode("utf-8"), date_stamp)
+ k_region = _hmac_sha256(k_date, region)
+ k_service = _hmac_sha256(k_region, service)
+ return _hmac_sha256(k_service, "request")
+
+
+def _canonical_query(action: str, version: str) -> str:
+ params = [("Action", action), ("Version", version)]
+ return "&".join(f"{quote(k, safe='')}={quote(v, safe='')}" for k, v in sorted(params))
+
+
+def _signed_headers(
+ *,
+ method: str,
+ query: str,
+ body: str,
+ access_key: str,
+ secret_key: str,
+ region: str,
+ service: str,
+) -> dict[str, str]:
+ now = datetime.now(UTC)
+ amz_date = now.strftime("%Y%m%dT%H%M%SZ")
+ date_stamp = now.strftime("%Y%m%d")
+ payload_hash = _hash_sha256(body)
+ canonical_headers = (
+ f"host:{HOST}\n"
+ f"x-content-sha256:{payload_hash}\n"
+ f"x-date:{amz_date}\n"
+ )
+ signed_headers = "host;x-content-sha256;x-date"
+ canonical_request = "\n".join(
+ [
+ method.upper(),
+ "/",
+ query,
+ canonical_headers,
+ signed_headers,
+ payload_hash,
+ ]
+ )
+ credential_scope = f"{date_stamp}/{region}/{service}/request"
+ string_to_sign = "\n".join(
+ [
+ "HMAC-SHA256",
+ amz_date,
+ credential_scope,
+ _hash_sha256(canonical_request),
+ ]
+ )
+ signature = hmac.new(
+ _signing_key(secret_key, date_stamp, region, service),
+ string_to_sign.encode("utf-8"),
+ hashlib.sha256,
+ ).hexdigest()
+ authorization = (
+ f"HMAC-SHA256 Credential={access_key}/{credential_scope}, "
+ f"SignedHeaders={signed_headers}, Signature={signature}"
+ )
+ return {
+ "Host": HOST,
+ "Content-Type": "application/json; charset=utf-8",
+ "X-Date": amz_date,
+ "X-Content-Sha256": payload_hash,
+ "Authorization": authorization,
+ }
+
+
+def parse_inference_usage_rows(result: dict[str, Any]) -> list[dict[str, Any]]:
+ """把 GetInferenceUsage 的 Fields/Data 表结构解析为行 dict。"""
+ fields = result.get("Fields") or []
+ data = result.get("Data") or []
+ names: list[str] = []
+ for field in fields:
+ if isinstance(field, dict):
+ names.append(str(field.get("Name") or ""))
+ rows: list[dict[str, Any]] = []
+ for item in data:
+ if not isinstance(item, list):
+ continue
+ row = {names[i]: item[i] for i in range(min(len(names), len(item))) if names[i]}
+ rows.append(row)
+ return rows
+
+
+def aggregate_usage_by_day(rows: list[dict[str, Any]]) -> dict[str, int]:
+ """按日聚合 token(优先 Value / TotalTokens 字段)。"""
+ daily: dict[str, int] = {}
+ for row in rows:
+ day_raw = row.get("Day") or row.get("Date") or row.get("day")
+ if not day_raw:
+ continue
+ day_key = str(day_raw)[:10]
+ model_name = str(row.get("ModelName") or row.get("Model") or row.get("Endpoint") or "").lower()
+ if model_name and "seedance" not in model_name and "video" not in model_name:
+ # 未标注模型时仍计入;有模型名则尽量只统计视频
+ if any(token in model_name for token in ("gpt", "llm", "chat", "seedream", "tts", "text")):
+ continue
+ value = row.get("Value")
+ if value is None:
+ value = row.get("TotalTokens") or row.get("Tokens") or row.get("Token") or 0
+ try:
+ tokens = int(value or 0)
+ except (TypeError, ValueError):
+ tokens = 0
+ if tokens <= 0:
+ continue
+ daily[day_key] = daily.get(day_key, 0) + tokens
+ return daily
+
+
+def build_inference_usage_request_body(start_date: str, end_date: str) -> dict[str, Any]:
+ """构造 GetInferenceUsage 请求体(按日粒度)。"""
+ return {
+ "StartTime": start_date,
+ "EndTime": end_date,
+ "QueryInterval": "Day",
+ }
+
+
+async def get_inference_usage(
+ start_date: str,
+ end_date: str,
+ *,
+ settings: Settings | None = None,
+) -> dict[str, Any]:
+ """调用方舟 GetInferenceUsage,返回原始 Result 与按日 token 聚合。"""
+ s = settings or get_settings()
+ if not volc_usage_configured(s):
+ raise RuntimeError("请先在后台「支付计费 → 上游成本监控」配置火山 Access Key")
+
+ body_obj = build_inference_usage_request_body(start_date, end_date)
+ body = json.dumps(body_obj, ensure_ascii=False, separators=(",", ":"))
+ query = _canonical_query(ACTION, VERSION)
+ headers = _signed_headers(
+ method="POST",
+ query=query,
+ body=body,
+ access_key=s.volc_access_key_id.strip(),
+ secret_key=s.volc_secret_access_key.strip(),
+ region=(s.volc_ark_region or "cn-beijing").strip(),
+ service=SERVICE,
+ )
+ url = f"https://{HOST}/?{query}"
+ async with httpx.AsyncClient(timeout=60.0) as client:
+ resp = await client.post(url, content=body.encode("utf-8"), headers=headers)
+ if resp.status_code >= 400:
+ raise RuntimeError(f"GetInferenceUsage HTTP {resp.status_code}: {resp.text[:500]}")
+ payload = resp.json()
+ metadata = payload.get("ResponseMetadata") or {}
+ if metadata.get("Error"):
+ err = metadata["Error"]
+ raise RuntimeError(f"GetInferenceUsage error: {err}")
+ result = payload.get("Result") or {}
+ rows = parse_inference_usage_rows(result)
+ daily_tokens = aggregate_usage_by_day(rows)
+ return {
+ "result": result,
+ "rows": rows,
+ "daily_tokens": daily_tokens,
+ "request_id": metadata.get("RequestId"),
+ }
diff --git a/backend/app/services/ark_model_catalog.py b/backend/app/services/ark_model_catalog.py
new file mode 100644
index 0000000..21f6bd9
--- /dev/null
+++ b/backend/app/services/ark_model_catalog.py
@@ -0,0 +1,99 @@
+"""火山方舟 /v1/models 目录拉取(管理端选模型)。"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+import httpx
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import get_settings
+from app.services.model_routing_config import infer_model_capability, normalize_model_name
+
+logger = logging.getLogger(__name__)
+
+ARK_DEFAULT_BASE = "https://ark.cn-beijing.volces.com/api/v3"
+
+
+def _model_id(item: dict[str, Any]) -> str:
+ for key in ("id", "name", "model"):
+ raw = item.get(key)
+ if isinstance(raw, str) and raw.strip():
+ return raw.strip()
+ return ""
+
+
+async def _resolve_ark_credentials(
+ db: AsyncSession | None,
+ *,
+ api_key_override: str | None = None,
+) -> tuple[str, str]:
+ key = (api_key_override or "").strip()
+ base = (get_settings().ark_base_url or ARK_DEFAULT_BASE).rstrip("/")
+ if key:
+ return key, base
+ settings = get_settings()
+ key = (settings.ark_api_key or "").strip()
+ if key:
+ return key, base
+ if db is not None:
+ from app.services.model_settings import _load_channels
+
+ channels = await _load_channels(db, runtime=True)
+ for channel in channels:
+ if channel.protocol != "ark" or not channel.enabled:
+ continue
+ candidate = (channel.api_key or "").strip()
+ if candidate:
+ return candidate, (channel.base_url or base).rstrip("/")
+ return "", base
+
+
+async def list_ark_models(
+ db: AsyncSession | None = None,
+ *,
+ capability: str = "all",
+ api_key_override: str | None = None,
+) -> list[dict[str, str]]:
+ """拉取方舟模型列表,并按 image/video 过滤。"""
+ api_key, base = await _resolve_ark_credentials(db, api_key_override=api_key_override)
+ if not api_key:
+ raise RuntimeError("请先在「模型路由 → 火山方舟」配置 API Key")
+
+ headers = {"Authorization": f"Bearer {api_key}"}
+ models: list[dict[str, Any]] = []
+ url: str | None = f"{base}/models"
+ async with httpx.AsyncClient(timeout=60.0) as client:
+ while url:
+ resp = await client.get(url, headers=headers)
+ if resp.status_code >= 400:
+ raise RuntimeError(f"拉取模型目录失败 HTTP {resp.status_code}: {resp.text[:300]}")
+ payload = resp.json()
+ data = payload.get("data")
+ if isinstance(data, list):
+ models.extend([item for item in data if isinstance(item, dict)])
+ url = payload.get("next_page") or payload.get("next_page_url")
+ if isinstance(url, str) and not url.strip():
+ url = None
+
+ cap_filter = (capability or "all").strip().lower()
+ out: list[dict[str, str]] = []
+ seen: set[str] = set()
+ for item in models:
+ model_id = _model_id(item)
+ if not model_id:
+ continue
+ cap = infer_model_capability(model_id)
+ if cap_filter in {"image", "video"} and cap != cap_filter:
+ continue
+ if cap_filter == "all" and cap not in {"image", "video"}:
+ continue
+ key = normalize_model_name(model_id)
+ if key in seen:
+ continue
+ seen.add(key)
+ label = str(item.get("display_name") or item.get("object") or model_id)
+ out.append({"id": model_id, "label": label, "capability": cap})
+ out.sort(key=lambda row: row["id"])
+ return out
diff --git a/backend/app/services/billing/alerts.py b/backend/app/services/billing/alerts.py
new file mode 100644
index 0000000..f08a519
--- /dev/null
+++ b/backend/app/services/billing/alerts.py
@@ -0,0 +1,233 @@
+# -*- coding: utf-8 -*-
+"""额度告警:用户消费里程碑弹窗 + 平台总费用邮件。"""
+from __future__ import annotations
+
+import logging
+from datetime import datetime, timezone
+from typing import Any
+
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import Settings, get_settings
+from app.models import BillingAlertNotification, UsageEvent, User
+from app.models_settings import AppSettings
+from app.services.admin.stats import _usage_window_totals
+from app.services.email import send_email
+from app.services.model_settings import _decrypt_flat_config, _encrypt_flat_config, _settings_to_dict
+
+logger = logging.getLogger(__name__)
+
+
+def _fen_to_yuan(fen: int) -> str:
+ return f"¥{int(fen) / 100:.2f}"
+
+
+async def _user_total_charge_fen(db: AsyncSession, user_id: int) -> int:
+ row = (
+ await db.execute(
+ select(func.coalesce(func.sum(UsageEvent.charge_fen), 0)).where(
+ UsageEvent.user_id == int(user_id),
+ UsageEvent.settled.is_(True),
+ )
+ )
+ ).scalar_one()
+ return int(row or 0)
+
+
+def _period_key(period: str, now: datetime | None = None) -> tuple[str, datetime | None]:
+ """返回统计周期键与 since 时间。"""
+ current = now or datetime.now(timezone.utc)
+ p = (period or "monthly").strip().lower()
+ if p == "daily":
+ start = current.replace(hour=0, minute=0, second=0, microsecond=0)
+ return start.date().isoformat(), start
+ if p == "all_time":
+ return "all_time", None
+ start = current.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+ return start.strftime("%Y-%m"), start
+
+
+async def _get_or_create_settings_row(db: AsyncSession) -> AppSettings:
+ row = (await db.execute(select(AppSettings).where(AppSettings.id == "default"))).scalar_one_or_none()
+ if row:
+ return row
+ row = AppSettings(id="default", config_json={"flat": _settings_to_dict()})
+ db.add(row)
+ await db.flush()
+ return row
+
+
+async def _read_admin_alert_dedup(db: AsyncSession) -> tuple[str, int]:
+ row = await _get_or_create_settings_row(db)
+ flat = _decrypt_flat_config(dict(row.config_json or {}))
+ return (
+ str(flat.get("billing_admin_cost_alert_last_period_key") or ""),
+ int(flat.get("billing_admin_cost_alert_last_level") or 0),
+ )
+
+
+async def _persist_flat_keys(db: AsyncSession, updates: dict[str, Any]) -> None:
+ """写入 app_settings.flat 运行时去重字段。"""
+ row = await _get_or_create_settings_row(db)
+ config = dict(row.config_json or {})
+ flat = _decrypt_flat_config(config)
+ flat.update(updates)
+ config["flat"] = _encrypt_flat_config(flat)
+ row.config_json = config
+ await db.flush()
+
+
+async def _resolve_admin_recipients(db: AsyncSession, settings: Settings) -> list[str]:
+ raw = str(settings.billing_admin_cost_alert_emails or "").strip()
+ emails = [e.strip() for e in raw.split(",") if e.strip()]
+ if emails:
+ return emails
+ rows = (
+ await db.execute(
+ select(User.email).where(User.role == "admin", User.email.is_not(None)).order_by(User.id.asc())
+ )
+ ).all()
+ return [str(r[0]).strip() for r in rows if r[0]]
+
+
+async def process_user_milestone_alert(
+ db: AsyncSession,
+ user: User,
+ *,
+ settings: Settings | None = None,
+) -> list[BillingAlertNotification]:
+ """结算后检查用户累计扣费是否跨越里程碑,写入待弹窗通知。"""
+ s = settings or get_settings()
+ if not s.billing_user_alert_enabled:
+ return []
+ interval = int(s.billing_user_alert_interval_fen or 0)
+ if interval <= 0:
+ return []
+ if getattr(user, "billing_unlimited", False):
+ return []
+
+ total = await _user_total_charge_fen(db, int(user.id))
+ last = int(getattr(user, "billing_alert_last_milestone_fen", 0) or 0)
+ created: list[BillingAlertNotification] = []
+
+ while last + interval <= total:
+ last += interval
+ note = BillingAlertNotification(
+ user_id=int(user.id),
+ kind="user_milestone",
+ title="消费提醒",
+ message=(
+ f"您已累计消费 {_fen_to_yuan(last)}。"
+ f"当前累计扣费 {_fen_to_yuan(total)},请注意账户余额。"
+ ),
+ milestone_fen=last,
+ )
+ db.add(note)
+ created.append(note)
+
+ if created:
+ user.billing_alert_last_milestone_fen = last
+ await db.flush()
+ return created
+
+
+async def process_admin_cost_alert(
+ db: AsyncSession,
+ *,
+ settings: Settings | None = None,
+) -> bool:
+ """平台总上游成本达阈值时发邮件给管理员(按周期去重)。"""
+ s = settings or get_settings()
+ if not s.billing_admin_cost_alert_enabled:
+ return False
+ threshold = int(s.billing_admin_cost_alert_threshold_fen or 0)
+ if threshold <= 0:
+ return False
+
+ period = str(s.billing_admin_cost_alert_period or "monthly")
+ period_key, since = _period_key(period)
+ totals = await _usage_window_totals(db, since=since)
+ cost_fen = int(totals.get("cost_fen") or 0)
+ if cost_fen < threshold:
+ return False
+
+ stored_period, last_level = await _read_admin_alert_dedup(db)
+ if stored_period != period_key:
+ last_level = 0
+
+ target_level = cost_fen // threshold
+ if target_level <= last_level:
+ return False
+
+ recipients = await _resolve_admin_recipients(db, s)
+ if not recipients:
+ logger.warning("admin cost alert skipped: no recipients cost_fen=%s", cost_fen)
+ return False
+
+ subject = f"[{s.app_name}] 平台费用告警"
+ body = (
+ f"统计周期:{period_key}\n"
+ f"累计上游成本:{_fen_to_yuan(cost_fen)}\n"
+ f"告警阈值:每 {_fen_to_yuan(threshold)}\n"
+ f"当前档位:{target_level}\n\n"
+ f"请登录管理后台查看用量详情。"
+ )
+ sent = await send_email(to_addrs=recipients, subject=subject, body=body, settings=s)
+ if not sent:
+ return False
+
+ await _persist_flat_keys(
+ db,
+ {
+ "billing_admin_cost_alert_last_period_key": period_key,
+ "billing_admin_cost_alert_last_level": target_level,
+ },
+ )
+ logger.info(
+ "admin cost alert sent period=%s level=%s cost_fen=%s recipients=%s",
+ period_key,
+ target_level,
+ cost_fen,
+ len(recipients),
+ )
+ return True
+
+
+async def process_billing_alerts_after_charge(
+ db: AsyncSession,
+ user: User | None,
+ *,
+ charged_fen: int,
+ settings: Settings | None = None,
+) -> None:
+ """结算产生扣费后触发用户弹窗与管理员邮件检查。"""
+ if int(charged_fen or 0) <= 0:
+ return
+ s = settings or get_settings()
+ if user is not None:
+ await process_user_milestone_alert(db, user, settings=s)
+ await process_admin_cost_alert(db, settings=s)
+
+
+async def list_pending_user_alerts(db: AsyncSession, user_id: int) -> list[BillingAlertNotification]:
+ rows = (
+ await db.execute(
+ select(BillingAlertNotification)
+ .where(
+ BillingAlertNotification.user_id == int(user_id),
+ BillingAlertNotification.acknowledged.is_(False),
+ )
+ .order_by(BillingAlertNotification.id.asc())
+ )
+ ).scalars().all()
+ return list(rows)
+
+
+async def acknowledge_user_alert(db: AsyncSession, user_id: int, alert_id: int) -> bool:
+ row = await db.get(BillingAlertNotification, int(alert_id))
+ if not row or int(row.user_id) != int(user_id):
+ return False
+ row.acknowledged = True
+ await db.flush()
+ return True
diff --git a/backend/app/services/billing/display.py b/backend/app/services/billing/display.py
new file mode 100644
index 0000000..696ae2a
--- /dev/null
+++ b/backend/app/services/billing/display.py
@@ -0,0 +1,95 @@
+# -*- coding: utf-8 -*-
+"""用量展示:计费依据标签与筛选。"""
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from sqlalchemy import Integer, and_, cast, func, or_
+from sqlalchemy.dialects.postgresql import JSONB
+from sqlalchemy.sql.elements import ColumnElement
+
+from app.models import UsageEvent
+from app.services.billing.pricing import parse_upstream_cost_fen
+
+_BASIS_LABELS = {
+ "estimate": "估算",
+ "upstream_usage": "实测(token)",
+ "upstream_cost": "实测(费用)",
+ "unknown": "实测(未分类)",
+}
+
+_UPSTREAM_COST_JSON_KEYS = (
+ "cost_fen",
+ "cost_cents",
+ "cost",
+ "total_cost",
+ "amount",
+ "cost_yuan",
+ "total_cost_yuan",
+)
+
+
+def resolve_billing_basis(*, estimated: bool, raw_usage_json: str | None = None) -> str:
+ """推断计费依据:estimate | upstream_usage | upstream_cost | unknown。"""
+ if estimated:
+ return "estimate"
+ raw: dict[str, Any] | None = None
+ if raw_usage_json:
+ try:
+ parsed = json.loads(raw_usage_json)
+ if isinstance(parsed, dict):
+ raw = parsed
+ except json.JSONDecodeError:
+ raw = None
+ usage = raw.get("usage") if isinstance(raw, dict) and isinstance(raw.get("usage"), dict) else raw
+ if isinstance(usage, dict):
+ if parse_upstream_cost_fen({"usage": usage}) is not None:
+ return "upstream_cost"
+ if int(usage.get("total_tokens") or 0) > 0:
+ return "upstream_usage"
+ return "unknown"
+
+
+def billing_basis_label(basis: str) -> str:
+ return _BASIS_LABELS.get(basis, basis or "—")
+
+
+def _raw_usage_jsonb() -> ColumnElement[Any]:
+ return cast(UsageEvent.raw_usage_json, JSONB)
+
+
+def _usage_has_upstream_cost_clause() -> ColumnElement[Any]:
+ """JSON 块内是否含上游费用字段(与 parse_upstream_cost_fen 键集合一致)。"""
+ raw = _raw_usage_jsonb()
+ usage = raw["usage"]
+ return or_(*[usage.has_key(key) for key in _UPSTREAM_COST_JSON_KEYS])
+
+
+def _usage_has_upstream_tokens_clause() -> ColumnElement[Any]:
+ raw = _raw_usage_jsonb()
+ usage = raw["usage"]
+ return cast(func.coalesce(usage["total_tokens"].astext, "0"), Integer) > 0
+
+
+def billing_basis_sql_filter(basis: str) -> ColumnElement[bool] | None:
+ """按计费依据生成 UsageEvent SQL 筛选条件;未知 basis 返回 None。"""
+ normalized = (basis or "").strip().lower()
+ if normalized == "estimate":
+ return UsageEvent.estimated.is_(True)
+ if normalized == "upstream":
+ return UsageEvent.estimated.is_(False)
+ if normalized == "upstream_cost":
+ return and_(
+ UsageEvent.estimated.is_(False),
+ UsageEvent.raw_usage_json.isnot(None),
+ _usage_has_upstream_cost_clause(),
+ )
+ if normalized == "upstream_usage":
+ return and_(
+ UsageEvent.estimated.is_(False),
+ UsageEvent.raw_usage_json.isnot(None),
+ ~_usage_has_upstream_cost_clause(),
+ _usage_has_upstream_tokens_clause(),
+ )
+ return None
diff --git a/backend/app/services/billing/ephemeral.py b/backend/app/services/billing/ephemeral.py
index a3eb043..e214d8f 100644
--- a/backend/app/services/billing/ephemeral.py
+++ b/backend/app/services/billing/ephemeral.py
@@ -291,6 +291,10 @@ async def settle_deferred_video_poll(
poll_status: str,
error: str | None = None,
billing_task_id: int | None = None,
+ usage_tokens: int = 0,
+ completion_tokens: int = 0,
+ raw_usage: dict | None = None,
+ billing_key: str | None = None,
) -> None:
"""轮询终态后结算轻量视频任务:成功才记 seedance 用量。
@@ -333,17 +337,32 @@ async def settle_deferred_video_poll(
if terminal == "succeeded":
payload = task.payload if isinstance(task.payload, dict) else {}
async with billing_scope(task.id):
- await record_line(
+ from app.services.drama.billing_util import record_seedance_video_usage, seedance_billing_key
+
+ generate_audio = bool(payload.get("generate_audio", True))
+ key = billing_key or seedance_billing_key(generate_audio=generate_audio)
+ task_result = None
+ if usage_tokens > 0:
+ from app.services.ark import TaskResult
+
+ task_result = TaskResult(
+ status="succeeded",
+ total_tokens=int(usage_tokens),
+ completion_tokens=int(completion_tokens or usage_tokens),
+ raw_usage=raw_usage,
+ )
+ await record_seedance_video_usage(
db,
user_id=user.id,
- billing_key="seedance2:video0",
+ billing_key=key,
model=get_settings().model_video,
- estimated=True,
- domain=task.domain,
- raw={
- "source": f"deferred_poll:{task.task_type}",
- "duration": payload.get("duration"),
- },
+ domain=task.domain or "api",
+ task_result=task_result,
+ fallback_duration_sec=payload.get("duration"),
+ provider_task_id=provider_task_id,
+ project_id=task.project_id,
+ drama_project_id=task.drama_project_id,
+ shot_id=task.shot_id,
)
task.status = "succeeded"
task.progress_percent = 100
diff --git a/backend/app/services/billing/pricing.py b/backend/app/services/billing/pricing.py
index fbafd54..ab4c127 100644
--- a/backend/app/services/billing/pricing.py
+++ b/backend/app/services/billing/pricing.py
@@ -47,6 +47,48 @@ def charge_fen_for_tokens(
return cost, charge
+def parse_upstream_cost_fen(data: dict[str, Any] | None) -> int | None:
+ """从火山 usage / 响应块解析上游成本(分);无则 None。"""
+ if not data:
+ return None
+ usage = data.get("usage") if isinstance(data.get("usage"), dict) else data
+ if not isinstance(usage, dict):
+ return None
+ for key in ("cost_fen", "cost_cents"):
+ if usage.get(key) is not None:
+ try:
+ return max(0, int(usage[key]))
+ except (TypeError, ValueError):
+ pass
+ for key in ("cost", "total_cost", "amount", "cost_yuan", "total_cost_yuan"):
+ if usage.get(key) is not None:
+ try:
+ return max(0, int(math.ceil(float(usage[key]) * 100)))
+ except (TypeError, ValueError):
+ pass
+ return None
+
+
+def charge_fen_for_usage(
+ tokens: int,
+ billing_key: str,
+ *,
+ raw_usage: dict[str, Any] | None = None,
+ settings: Settings | None = None,
+) -> tuple[int, int, bool]:
+ """按火山返回的实际成本或 token 用量计算 (cost_fen, charge_fen, used_upstream_cost)。"""
+ s = settings or get_settings()
+ upstream_cost = parse_upstream_cost_fen(raw_usage)
+ if upstream_cost is not None and upstream_cost > 0:
+ cost = upstream_cost
+ charge = math.ceil(cost * float(s.billing_markup))
+ if charge < 1:
+ charge = 1
+ return cost, charge, True
+ cost, charge = charge_fen_for_tokens(tokens, billing_key, settings=s)
+ return cost, charge, False
+
+
def parse_usage_dict(data: dict[str, Any] | None) -> dict[str, int]:
if not data:
return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
diff --git a/backend/app/services/billing/settlement.py b/backend/app/services/billing/settlement.py
index fddc4af..63ad5b1 100644
--- a/backend/app/services/billing/settlement.py
+++ b/backend/app/services/billing/settlement.py
@@ -242,6 +242,10 @@ async def settle_task(db: AsyncSession, task_id: int) -> dict[str, int]:
if events:
task.billing_status = "settled"
await db.flush()
+ if charged > 0 and user:
+ from app.services.billing.alerts import process_billing_alerts_after_charge
+
+ await process_billing_alerts_after_charge(db, user, charged_fen=charged)
return {"charged": charged, "refunded": 0}
frozen_for_task = int(task.billing_estimate_fen or 0)
@@ -290,6 +294,10 @@ async def settle_task(db: AsyncSession, task_id: int) -> dict[str, int]:
note=f"charged={charged} freeze={frozen_for_task} refund={refund}",
)
await db.flush()
+ if charged > 0 and user:
+ from app.services.billing.alerts import process_billing_alerts_after_charge
+
+ await process_billing_alerts_after_charge(db, user, charged_fen=charged)
return {"charged": charged, "refunded": refund}
@@ -351,6 +359,10 @@ async def settle_project(db: AsyncSession, project_id: int) -> dict[str, int]:
note=f"charged={charged} refund={refund}",
)
await db.flush()
+ if charged > 0 and user:
+ from app.services.billing.alerts import process_billing_alerts_after_charge
+
+ await process_billing_alerts_after_charge(db, user, charged_fen=charged)
return {"charged": charged, "refunded": refund}
@@ -437,6 +449,9 @@ async def settle_usage_charge(
user.balance_fen = locked.balance_fen
user.frozen_fen = locked.frozen_fen
await db.flush()
+ from app.services.billing.alerts import process_billing_alerts_after_charge
+
+ await process_billing_alerts_after_charge(db, target, charged_fen=need)
async def get_task_usage_lines(db: AsyncSession, task_id: int) -> list[UsageEvent]:
diff --git a/backend/app/services/billing/usage.py b/backend/app/services/billing/usage.py
index f9ab293..c08fe1d 100644
--- a/backend/app/services/billing/usage.py
+++ b/backend/app/services/billing/usage.py
@@ -10,7 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.config import get_settings
from app.models import UsageEvent
from app.services.billing.context import get_current_task_run_id
-from app.services.billing.pricing import billing_key_to_capability, charge_fen_for_tokens
+from app.services.billing.pricing import billing_key_to_capability, charge_fen_for_usage
async def record_line(
@@ -47,7 +47,17 @@ async def record_line(
elif billing_key.startswith("seedance"):
total = s.billing_est_seedance_tokens_per_sec * 5
estimated = True
- cost, charge = charge_fen_for_tokens(total, billing_key, settings=s)
+ cost, charge, from_upstream = charge_fen_for_usage(
+ total, billing_key, raw_usage=raw, settings=s
+ )
+ if from_upstream:
+ estimated = False
+ elif total > 0 and not estimated:
+ pass
+ elif total > 0 and estimated and raw:
+ usage_parsed = raw.get("usage") if isinstance(raw.get("usage"), dict) else raw
+ if isinstance(usage_parsed, dict) and int(usage_parsed.get("total_tokens") or 0) > 0:
+ estimated = False
capability = billing_key_to_capability(billing_key)
ev = UsageEvent(
user_id=user_id,
diff --git a/backend/app/services/drama/asset_video.py b/backend/app/services/drama/asset_video.py
index d012f17..dd22399 100644
--- a/backend/app/services/drama/asset_video.py
+++ b/backend/app/services/drama/asset_video.py
@@ -12,8 +12,7 @@ from app.config import get_settings
from app.models import User
from app.models_drama import DramaAsset, DramaProject
from app.services.ark import get_ark
-from app.services.billing import record_line
-from app.services.drama.billing_util import seedance_video_billing_tokens
+from app.services.drama.billing_util import record_seedance_video_usage, seedance_billing_key
from app.services.drama.build_seedance_generate_body import (
build_seedance_generate_body,
drama_asset_to_payload,
@@ -108,7 +107,7 @@ async def generate_asset_video(
"duration_fallback": duration,
}
)
- local_video, local_last_frame = await ark.gen_and_wait_seedance_body(
+ local_video, local_last_frame, task_result = await ark.gen_and_wait_seedance_body(
body,
project_id=project.id,
shot_no=asset.id,
@@ -148,16 +147,16 @@ async def generate_asset_video(
}
asset.params = params
- await record_line(
+ await record_seedance_video_usage(
db,
user_id=user.id,
- project_id=None,
- drama_project_id=project.id,
- billing_key="seedance2:video0",
+ billing_key=seedance_billing_key(generate_audio=True),
model=settings.model_video,
- tokens=seedance_video_billing_tokens(duration),
- estimated=True,
domain="drama",
+ task_result=task_result,
+ fallback_duration_sec=duration,
+ provider_task_id=getattr(task_result, "provider_task_id", None),
+ drama_project_id=project.id,
)
await db.commit()
await db.refresh(asset)
diff --git a/backend/app/services/drama/billing_util.py b/backend/app/services/drama/billing_util.py
index b04161c..cabfd13 100644
--- a/backend/app/services/drama/billing_util.py
+++ b/backend/app/services/drama/billing_util.py
@@ -2,13 +2,18 @@
from __future__ import annotations
+from typing import TYPE_CHECKING, Any
+
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import get_settings
-from app.models import User
+from app.models import UsageEvent, User
from app.services.billing import record_line
from app.services.drama.seed import SeedAssetsResult
+if TYPE_CHECKING:
+ from app.services.ark import ImageResult, TaskResult
+
# 按分镜时长估算 Seedance 视频 token(与科普 pipeline 一致)
def seedance_video_billing_tokens(duration_sec: int | float | None) -> int:
@@ -17,6 +22,144 @@ def seedance_video_billing_tokens(duration_sec: int | float | None) -> int:
return int(dur * settings.billing_est_seedance_tokens_per_sec)
+def seedance_billing_key(*, generate_audio: bool = True) -> str:
+ return "seedance2:video0" if generate_audio else "seedance2:video1"
+
+
+async def record_seedance_video_usage(
+ db: AsyncSession,
+ *,
+ user_id: int,
+ billing_key: str,
+ model: str,
+ domain: str,
+ task_result: TaskResult | None = None,
+ fallback_duration_sec: float | None = None,
+ provider_task_id: str | None = None,
+ drama_project_id: int | None = None,
+ project_id: int | None = None,
+ shot_id: int | None = None,
+) -> UsageEvent:
+ """按官方任务 usage / 成本或时长估算写入 Seedance 视频用量行。"""
+ if (
+ (not task_result or int(getattr(task_result, "total_tokens", 0) or 0) <= 0)
+ and provider_task_id
+ ):
+ from app.services.ark import get_ark
+
+ try:
+ refreshed = await get_ark().fetch_task_once(provider_task_id.strip())
+ if int(getattr(refreshed, "total_tokens", 0) or 0) > 0 or refreshed.raw_usage:
+ task_result = refreshed
+ except Exception: # noqa: BLE001
+ pass
+
+ total_tokens = int(getattr(task_result, "total_tokens", 0) or 0)
+ completion_tokens = int(getattr(task_result, "completion_tokens", 0) or 0)
+ raw_usage = getattr(task_result, "raw_usage", None)
+ raw: dict[str, Any] | None = None
+ if raw_usage:
+ raw = {"usage": dict(raw_usage)}
+ elif provider_task_id:
+ raw = {"provider_task_id": provider_task_id, "usage": raw_usage or {}}
+
+ from app.services.billing.pricing import parse_upstream_cost_fen
+
+ upstream_cost = parse_upstream_cost_fen(raw) if raw else None
+ if upstream_cost is not None and raw is not None:
+ raw["usage"] = {**(raw.get("usage") or {}), "cost_fen": upstream_cost}
+
+ if total_tokens > 0 or upstream_cost:
+ return await record_line(
+ db,
+ user_id=user_id,
+ billing_key=billing_key,
+ model=model,
+ tokens=total_tokens,
+ completion_tokens=completion_tokens,
+ estimated=False,
+ raw=raw,
+ project_id=project_id,
+ drama_project_id=drama_project_id,
+ shot_id=shot_id,
+ domain=domain,
+ )
+
+ fallback_tokens = 0
+ if fallback_duration_sec is not None:
+ fallback_tokens = seedance_video_billing_tokens(fallback_duration_sec)
+
+ return await record_line(
+ db,
+ user_id=user_id,
+ billing_key=billing_key,
+ model=model,
+ tokens=fallback_tokens,
+ estimated=True,
+ raw=raw,
+ project_id=project_id,
+ drama_project_id=drama_project_id,
+ shot_id=shot_id,
+ domain=domain,
+ )
+
+
+async def record_seedream_image_usage(
+ db: AsyncSession,
+ *,
+ user_id: int,
+ model: str,
+ domain: str,
+ image_result: ImageResult | None = None,
+ project_id: int | None = None,
+ drama_project_id: int | None = None,
+ shot_id: int | None = None,
+ extra_raw: dict[str, Any] | None = None,
+) -> UsageEvent:
+ """按 Seedream 响应 usage / 成本写入图片用量行;缺失时回退估算 token。"""
+ total_tokens = int(getattr(image_result, "total_tokens", 0) or 0)
+ completion_tokens = int(getattr(image_result, "completion_tokens", 0) or 0)
+ prompt_tokens = int(getattr(image_result, "prompt_tokens", 0) or 0)
+ raw_usage = getattr(image_result, "raw_usage", None)
+ upstream_cost = getattr(image_result, "upstream_cost_fen", None)
+
+ raw: dict[str, Any] = dict(extra_raw or {})
+ if raw_usage:
+ raw["usage"] = dict(raw_usage)
+ if upstream_cost is not None:
+ raw["usage"] = {**(raw.get("usage") or {}), "cost_fen": int(upstream_cost)}
+
+ if total_tokens > 0 or upstream_cost:
+ return await record_line(
+ db,
+ user_id=user_id,
+ billing_key="seedream",
+ model=model,
+ tokens=total_tokens,
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ estimated=False,
+ raw=raw or None,
+ project_id=project_id,
+ drama_project_id=drama_project_id,
+ shot_id=shot_id,
+ domain=domain,
+ )
+
+ return await record_line(
+ db,
+ user_id=user_id,
+ billing_key="seedream",
+ model=model,
+ estimated=True,
+ raw=raw or None,
+ project_id=project_id,
+ drama_project_id=drama_project_id,
+ shot_id=shot_id,
+ domain=domain,
+ )
+
+
async def record_seed_assets_llm_usage(
db: AsyncSession,
user: User,
diff --git a/backend/app/services/drama/fragment_content_duration.py b/backend/app/services/drama/fragment_content_duration.py
index afa38c3..591fc9e 100644
--- a/backend/app/services/drama/fragment_content_duration.py
+++ b/backend/app/services/drama/fragment_content_duration.py
@@ -6,7 +6,6 @@ import re
FRAGMENT_CONTENT_DURATION_MAX = 30
SEEDANCE_DURATION_MIN = 4
-SEEDANCE_SMART_DURATION = -1
DURATION_MENTION_TOKEN_PATTERN = re.compile(r"@duration:(\d+)")
diff --git a/backend/app/services/drama/generation.py b/backend/app/services/drama/generation.py
index 76073e8..06355c6 100644
--- a/backend/app/services/drama/generation.py
+++ b/backend/app/services/drama/generation.py
@@ -17,7 +17,7 @@ from app.config import get_settings
from app.models import User
from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaFragmentAssetRef, DramaProject
from app.services.ark import get_ark
-from app.services.drama.billing_util import seedance_video_billing_tokens
+from app.services.drama.billing_util import record_seedance_video_usage, record_seedream_image_usage, seedance_billing_key
from app.services.drama.output_settings import (
infer_aspect_ratio_from_pixels,
resolve_episode_video_output,
@@ -1013,15 +1013,13 @@ async def generate_asset_image(
)
logger.info("Seedream 返回 project_id=%s url=%s", project.id, (url or "")[:100])
- await record_line(
+ await record_seedream_image_usage(
db,
user_id=user.id,
- project_id=None,
- drama_project_id=project.id,
- billing_key="seedream",
model=model or settings.model_image,
- estimated=True,
domain="drama",
+ image_result=result,
+ drama_project_id=project.id,
)
# gen_meta 写入资产 params,便于前端回显上次选项
@@ -1118,200 +1116,6 @@ def build_fragment_ref_payloads(
return ref_payloads
-async def generate_fragment_video(
- db: AsyncSession,
- user: User,
- project: DramaProject,
- fragment: DramaEpisodeFragment,
-) -> DramaEpisodeFragment:
- """为单个分镜片段生成 Seedance 视频(含参考图与角色音色 reference_audio)。"""
- settings = get_settings()
- ark = get_ark()
- prompt = (fragment.content or "").strip() or "短剧分镜"
- duration = int(fragment.duration_sec or 8)
- duration = max(settings.seedance_duration_min, min(duration, settings.seedance_duration_max))
- episode = await db.get(DramaEpisode, fragment.episode_id)
- ratio, resolution = resolve_episode_video_output(
- episode.params if episode else None,
- project.params,
- )
-
- refs = (
- await db.execute(
- select(DramaFragmentAssetRef)
- .where(DramaFragmentAssetRef.fragment_id == fragment.id)
- .order_by(DramaFragmentAssetRef.id.asc())
- )
- ).scalars().all()
- ref_assets: list[DramaAsset] = []
- seen_ids: set[int] = set()
- for ref in refs:
- if ref.asset_id in seen_ids:
- continue
- asset = await db.get(DramaAsset, ref.asset_id)
- if asset:
- seen_ids.add(ref.asset_id)
- ref_assets.append(asset)
-
- # 缺图的引用资产先动态生图,再组 Seedance 参考
- ref_assets = await ensure_fragment_reference_images(
- db,
- user,
- project,
- fragment,
- ref_assets=ref_assets,
- )
- # 已有本地图的资产同步上 OSS,避免 Seedance 拿不到公网 URL
- ref_assets = await ensure_reference_assets_public_urls(db, ref_assets)
- ref_assets = await ensure_fragment_reference_audios(
- db,
- user,
- project,
- fragment,
- ref_assets,
- )
-
- ref_payloads = build_fragment_ref_payloads(project, ref_assets)
- style_id = str((project.params or {}).get("image_style_id") or "").strip() or None
- catalog = build_seedance_reference_catalog(ref_payloads)
-
- continuity_url: str | None = None
- if project_link_last_frame_enabled(project):
- prev = await find_previous_episode_fragment(db, fragment)
- continuity_url = read_fragment_last_frame_url(prev)
- if continuity_url:
- continuity_url = storage_svc_early_republish(continuity_url)
-
- t0 = time.time()
- image_url = ""
- for item in catalog.images:
- image_url = item.url
- break
-
- local_last_frame: str | None = None
- burn_subtitles = resolve_episode_burn_subtitles(episode.params if episode else None)
- if ref_payloads and (catalog.images or catalog.audios):
- body = build_seedance_generate_body(
- {
- "content": prompt,
- "reference": ref_payloads,
- "video_style_id": style_id,
- "aspect_ratio": ratio,
- "resolution": resolution,
- "duration_fallback": duration,
- "continuity_first_frame_url": continuity_url,
- "burn_subtitles": burn_subtitles,
- }
- )
- content_labels = describe_seedance_content_slots(
- ref_payloads,
- continuity_url,
- has_text=bool((prompt or "").strip()),
- )
- local_video, local_last_frame = await ark.gen_and_wait_seedance_body(
- body,
- project_id=project.id,
- shot_no=fragment.id,
- content_labels=content_labels,
- )
- elif image_url:
- local_video = await ark.gen_and_wait_video(
- image_url,
- prompt,
- duration,
- project_id=project.id,
- shot_no=fragment.id,
- ratio=ratio,
- generate_audio=True,
- )
- else:
- still = await ark.gen_image(
- prompt[:500],
- project_id=project.id,
- shot_no=fragment.id,
- size=seedream_still_size_for_video_ratio(ratio),
- )
- await record_line(
- db,
- user_id=user.id,
- project_id=None,
- drama_project_id=project.id,
- billing_key="seedream",
- model=settings.model_image,
- estimated=True,
- domain="drama",
- )
- image_url = still.local_url or ""
- local_video = await ark.gen_and_wait_video(
- still.local_url,
- prompt,
- duration,
- project_id=project.id,
- shot_no=fragment.id,
- ratio=ratio,
- generate_audio=True,
- )
-
- # Seedance 成片落盘后立即同步 OSS,避免库里长期留 /static
- from app.services import storage as storage_svc
- from app.services.ffmpeg_compose import extract_video_poster_frame
-
- # 覆盖前先归档旧成片(复制为独立 hist 文件)
- archive_fragment_video_version(fragment)
- video_url = storage_svc.republish_url(local_video, sync=True) or local_video
- # 封面必须来自成片帧,禁止用角色/场景参考图冒充
- cover_url = ""
- video_path = storage_svc.local_path_from_url(local_video)
- if video_path is None and isinstance(local_video, str) and not local_video.startswith("http"):
- candidate = Path(local_video)
- if candidate.exists():
- video_path = candidate
- if video_path and video_path.exists():
- poster_dest = (
- storage_svc.project_dir(project.id)
- / f"shot_{fragment.id}_{int(time.time())}_cover.jpg"
- )
- if extract_video_poster_frame(video_path, poster_dest):
- cover_src = storage_svc.rel_static_url(poster_dest)
- cover_url = storage_svc.republish_url(cover_src, sync=True) or cover_src
- last_frame_url = None
- if local_last_frame:
- last_frame_url = storage_svc.republish_url(local_last_frame, sync=True) or local_last_frame
- if not cover_url:
- cover_url = last_frame_url
- fragment.video = video_url
- fragment.cover = cover_url or ""
- write_fragment_last_frame_url(fragment, last_frame_url)
- write_fragment_video_output_meta(
- fragment,
- aspect_ratio=ratio,
- resolution=resolution,
- video_path=video_path,
- )
- await record_line(
- db,
- user_id=user.id,
- project_id=None,
- drama_project_id=project.id,
- billing_key="seedance2:video0",
- model=settings.model_video,
- tokens=seedance_video_billing_tokens(fragment.duration_sec),
- estimated=True,
- domain="drama",
- )
- await db.commit()
- await db.refresh(fragment)
- logger.info(
- "fragment video done id=%s secs=%.1f url=%s last_frame=%s continuity=%s",
- fragment.id,
- time.time() - t0,
- (video_url or "")[:80],
- bool(last_frame_url),
- bool(continuity_url),
- )
- return fragment
-
-
@dataclass
class FragmentVideoPrepared:
"""分镜视频提交前上下文(Worker 准备阶段产物,写入 task.payload)。"""
@@ -1327,13 +1131,6 @@ class FragmentVideoPrepared:
content_labels: list[str] | None = None
-@dataclass
-class FragmentVideoSubmitResult:
- """分镜视频提交结果:一律异步轮询,不在 Worker 内阻塞等待。"""
-
- provider_task_id: str
-
-
# Worker 准备阶段:参考图 / 衔接帧 / 请求体(可耗时,但不等待上游成片)。
async def prepare_fragment_video_for_submit(
db: AsyncSession,
@@ -1521,18 +1318,6 @@ def deserialize_fragment_video_prepared(raw: dict[str, Any]) -> FragmentVideoPre
)
-# 兼容旧调用:准备 + 提交,不在 Worker 内 wait。
-async def submit_fragment_video_generation(
- db: AsyncSession,
- user: User,
- project: DramaProject,
- fragment: DramaEpisodeFragment,
-) -> FragmentVideoSubmitResult:
- prepared = await prepare_fragment_video_for_submit(db, user, project, fragment)
- provider_task_id = await submit_prepared_fragment_video(prepared, project_id=project.id)
- return FragmentVideoSubmitResult(provider_task_id=provider_task_id)
-
-
# 将本地/上游视频落盘结果写回分镜并计费。
async def apply_fragment_video_assets(
db: AsyncSession,
@@ -1544,6 +1329,8 @@ async def apply_fragment_video_assets(
local_last_frame: str | None = None,
attempts: int = 1,
attempt_limit: int = 3,
+ task_result: "TaskResult | None" = None,
+ provider_task_id: str | None = None,
) -> DramaEpisodeFragment:
from app.services import storage as storage_svc
from app.services.ffmpeg_compose import extract_video_poster_frame
@@ -1600,16 +1387,17 @@ async def apply_fragment_video_assets(
if last_frame_url:
params["lastFrameUrl"] = last_frame_url
fragment.params = params
- await record_line(
+ generate_audio = bool((fragment.params or {}).get("generate_audio", True))
+ await record_seedance_video_usage(
db,
user_id=user.id,
- project_id=None,
- drama_project_id=project.id,
- billing_key="seedance2:video0",
+ billing_key=seedance_billing_key(generate_audio=generate_audio),
model=settings.model_video,
- tokens=seedance_video_billing_tokens(fragment.duration_sec),
- estimated=True,
domain="drama",
+ task_result=task_result,
+ fallback_duration_sec=fragment.duration_sec,
+ provider_task_id=provider_task_id,
+ drama_project_id=project.id,
)
await db.commit()
await db.refresh(fragment)
diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.py
index 10aa72e..38022ce 100644
--- a/backend/app/services/drama/jobs.py
+++ b/backend/app/services/drama/jobs.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import asyncio
import logging
from datetime import UTC, datetime, timedelta
from typing import Any
@@ -39,11 +38,8 @@ from app.services.drama.generation import (
apply_fragment_video_assets,
build_failed_generation_params,
deserialize_fragment_video_prepared,
- fragment_generation_status,
generate_asset_image,
- generate_fragment_video,
prepare_fragment_video_for_submit,
- project_link_last_frame_enabled,
serialize_fragment_video_prepared,
submit_prepared_fragment_video,
)
@@ -51,8 +47,6 @@ from app.services.drama.visual_prompt import resolve_visual_prompt_for_asset
logger = logging.getLogger(__name__)
-# in-process fallback handles
-_running: dict[str, asyncio.Task] = {}
# 分集视频取消标记(episode_id)
_video_cancelled_episodes: set[int] = set()
ACTIVE_VIDEO_GEN_STATUSES = frozenset({"queued", "running", "generating"})
@@ -75,21 +69,6 @@ def clear_episode_video_cancelled(episode_id: int) -> None:
_clear_episode_video_cancelled(episode_id)
-def _cancel_inprocess_episode_video(episode_id: int) -> bool:
- # 同时取消旧版整集任务与按分镜拆开的进程内任务
- cancelled = False
- prefix = f"frag:{int(episode_id)}:"
- epgen_key = f"epgen:{int(episode_id)}"
- for key, task in list(_running.items()):
- if key != epgen_key and not str(key).startswith(prefix):
- continue
- if task is None or task.done():
- continue
- task.cancel()
- cancelled = True
- return cancelled
-
-
async def _reset_fragment_video_generation(
db,
*,
@@ -115,21 +94,19 @@ async def _reset_fragment_video_generation(
async def cancel_episode_video_jobs(episode_id: int) -> dict[str, Any]:
- """取消单集视频任务:终止进程内任务并重置分镜状态。"""
+ """取消单集视频任务:标记取消并重置分镜生成状态。"""
_mark_episode_video_cancelled(episode_id)
- cancelled_inprocess = _cancel_inprocess_episode_video(episode_id)
async with AsyncSessionLocal() as db:
fragments = await _reset_fragment_video_generation(db, episode_id=episode_id)
logger.info(
- "取消分集视频 episode_id=%s inprocess=%s fragments=%s",
+ "取消分集视频 episode_id=%s fragments=%s",
episode_id,
- cancelled_inprocess,
fragments,
)
return {
"ok": True,
"episode_id": episode_id,
- "inprocess": cancelled_inprocess,
+ "inprocess": 0,
"purged": 0,
"revoked": 0,
"fragments": fragments,
@@ -149,7 +126,6 @@ async def cancel_all_episode_video_jobs() -> dict[str, Any]:
episode_ids.add(int(frag.episode_id))
for ep_id in list(episode_ids):
_mark_episode_video_cancelled(ep_id)
- _cancel_inprocess_episode_video(ep_id)
async with AsyncSessionLocal() as db:
fragments = await _reset_fragment_video_generation(db)
@@ -167,10 +143,6 @@ async def cancel_all_episode_video_jobs() -> dict[str, Any]:
}
-def _job_key(kind: str, entity_id: int) -> str:
- return f"{kind}:{entity_id}"
-
-
async def _enqueue_drama_task(
db: AsyncSession,
user: User,
@@ -454,19 +426,6 @@ async def run_episode_scripts_job(project_id: int, force: bool = False) -> dict[
# ---------- episode fragment plan (LLM) ----------
-def dispatch_episode_fragment_plan_job(episode_id: int, *, fallback_rules: bool = True) -> str:
- # Legacy:进程内 dispatch,无任务平台计费。API 已改 create_task(fragment_plan);无外部调用方。
- key = _job_key("fragplan", episode_id)
- if key in _running and not _running[key].done():
- logger.info("dispatch 单集分镜 → 进程内已在跑 episode_id=%s", episode_id)
- return "in-process"
- _running[key] = asyncio.create_task(
- run_episode_fragment_plan_job(episode_id, fallback_rules=fallback_rules)
- )
- logger.info("dispatch 单集分镜 → 进程内新建 episode_id=%s", episode_id)
- return "in-process"
-
-
async def run_episode_fragment_plan_job(
episode_id: int,
*,
@@ -684,319 +643,7 @@ async def run_episode_fragment_plan_job(
}
-# ---------- episode video ----------
-
-
-async def _queued_remaining_fragment_ids(fragment_ids: list[int]) -> list[int]:
- # 取消后库里已不是 queued,不再派发下一镜
- still: list[int] = []
- async with AsyncSessionLocal() as db:
- for fid in fragment_ids:
- frag = await db.get(DramaEpisodeFragment, int(fid))
- if not frag:
- continue
- status = str(fragment_generation_status(frag).get("status") or "")
- if status == "queued":
- still.append(int(fid))
- return still
-
-
-async def _fail_remaining_fragment_videos(fragment_ids: list[int], error: str) -> None:
- # 上一镜失败/取消后,后续镜无法取尾帧,标记失败避免一直「排队中」
- if not fragment_ids:
- return
- async with AsyncSessionLocal() as db:
- changed = 0
- for fid in fragment_ids:
- frag = await db.get(DramaEpisodeFragment, int(fid))
- if not frag:
- continue
- params = dict(frag.params or {})
- gen = params.get("generation") if isinstance(params.get("generation"), dict) else {}
- status = str(gen.get("status") or "")
- if status not in ACTIVE_VIDEO_GEN_STATUSES:
- continue
- params["generation"] = build_failed_generation_params(
- gen if isinstance(gen, dict) else None,
- error,
- )
- frag.params = params
- changed += 1
- if changed:
- await db.commit()
- logger.info("后续分镜已标记失败 count=%s error=%s", changed, error[:80])
-
-
-async def _run_fragment_chain_inprocess(
- episode_id: int,
- user_id: int,
- fragment_ids: list[int],
-) -> None:
- # 进程内按镜序生成,后一镜等上一镜写出尾帧
- remaining = [int(x) for x in fragment_ids]
- while remaining:
- if _is_episode_video_cancelled(episode_id):
- return
- fid = remaining.pop(0)
- ok = await _generate_one_fragment_video(
- episode_id=episode_id,
- user_id=user_id,
- fragment_id=fid,
- sem=asyncio.Semaphore(1),
- )
- if ok:
- continue
- if remaining and not _is_episode_video_cancelled(episode_id):
- await _fail_remaining_fragment_videos(remaining, "上一镜失败,无法衔接尾帧")
- return
-
-
-def dispatch_episode_generate_job(
- episode_id: int,
- user_id: int,
- fragment_ids: list[int],
- *,
- sequential: bool = True,
-) -> str:
- # Legacy:进程内 dispatch,无任务平台计费。API 已改 create_task(fragment_video);无外部调用方。
- ids = [int(x) for x in fragment_ids]
- _clear_episode_video_cancelled(episode_id)
- if not ids:
- return "queued"
-
- if sequential:
- key = f"epgen:{int(episode_id)}"
- existing = _running.get(key)
- if existing and not existing.done():
- logger.info("dispatch 分镜视频链 → 进程内已在跑 episode_id=%s", episode_id)
- return "in-process"
- _running[key] = asyncio.create_task(
- _run_fragment_chain_inprocess(episode_id, user_id, ids)
- )
- logger.info(
- "dispatch 分镜视频链 → 进程内异步 episode_id=%s fragments=%s",
- episode_id,
- len(ids),
- )
- return "in-process"
-
- for fid in ids:
- key = f"frag:{int(episode_id)}:{int(fid)}"
- existing = _running.get(key)
- if existing and not existing.done():
- continue
- _running[key] = asyncio.create_task(
- _generate_one_fragment_video(
- episode_id=episode_id,
- user_id=user_id,
- fragment_id=int(fid),
- sem=asyncio.Semaphore(1),
- )
- )
- logger.info(
- "dispatch 分镜视频并行 → 进程内异步 episode_id=%s fragments=%s",
- episode_id,
- len(ids),
- )
- return "in-process"
-
-
-# Legacy:单分镜同步生成(独立 DB session)。任务平台请用 submit_fragment_video_task。
-async def _generate_one_fragment_video(
- *,
- episode_id: int,
- user_id: int,
- fragment_id: int,
- sem: asyncio.Semaphore,
-) -> bool:
- async with sem:
- async with AsyncSessionLocal() as db:
- ep = await db.get(
- DramaEpisode,
- episode_id,
- options=[
- selectinload(DramaEpisode.project).selectinload(DramaProject.script),
- ],
- )
- if not ep or not ep.project:
- logger.warning(
- "分镜视频跳过:分集/项目不存在 episode_id=%s fragment_id=%s",
- episode_id,
- fragment_id,
- )
- return False
- project = ep.project
- user = await db.get(User, user_id)
- if not user:
- return False
- frag = await db.get(
- DramaEpisodeFragment,
- fragment_id,
- options=[
- selectinload(DramaEpisodeFragment.asset_references).selectinload(
- DramaFragmentAssetRef.asset
- )
- ],
- )
- if not frag or frag.episode_id != episode_id:
- return False
-
- gen = frag.params.get("generation") if isinstance(frag.params, dict) else None
- gen_status = str(gen.get("status") or "") if isinstance(gen, dict) else ""
- if _is_episode_video_cancelled(episode_id) or gen_status == "cancelled":
- params = dict(frag.params or {})
- params.pop("generation_attempts", None)
- params["generation"] = {"status": "cancelled", "error": "任务已取消"}
- frag.params = params
- await db.commit()
- logger.info(
- "分镜视频已取消 fragment_id=%s episode_id=%s",
- fragment_id,
- episode_id,
- )
- return False
-
- params = dict(frag.params or {})
- persisted_attempts = int(params.get("generation_attempts") or 0)
- prev_attempts = persisted_attempts
- if isinstance(gen, dict):
- prev_attempts = max(prev_attempts, int(gen.get("attempts") or 0))
- max_attempts = max(1, int(get_settings().drama_fragment_max_attempts or 3))
- attempts = prev_attempts + 1
- if attempts > max_attempts:
- params["generation_attempts"] = prev_attempts
- params["generation"] = build_failed_generation_params(
- gen if isinstance(gen, dict) else None,
- f"分镜重试超过上限({max_attempts} 次)",
- attempts=prev_attempts,
- attempt_limit=max_attempts,
- )
- frag.params = params
- await db.commit()
- logger.warning(
- "分镜视频跳过:超过重试上限 fragment_id=%s attempts=%s limit=%s",
- fragment_id,
- prev_attempts,
- max_attempts,
- )
- return False
- params["generation_attempts"] = attempts
- params["generation"] = {
- "status": "running",
- "attempts": attempts,
- "attempt_limit": max_attempts,
- }
- frag.params = params
- await db.commit()
- try:
- logger.info(
- "生成分镜视频 fragment_id=%s episode_id=%s attempt=%s/%s",
- fragment_id,
- episode_id,
- attempts,
- max_attempts,
- )
- await generate_fragment_video(db, user, project, frag)
- await db.refresh(frag)
- params = dict(frag.params or {})
- last_frame = ""
- if isinstance(frag.params, dict):
- raw = frag.params.get("lastFrameUrl") or frag.params.get("last_frame_url")
- if isinstance(raw, str):
- last_frame = raw
- params.pop("generation_attempts", None)
- params["generation"] = {
- "status": "done",
- "video": frag.video,
- "cover": frag.cover,
- "lastFrameUrl": last_frame or None,
- "attempts": attempts,
- "attempt_limit": max_attempts,
- }
- if last_frame:
- params["lastFrameUrl"] = last_frame
- frag.params = params
- await db.commit()
- return True
- except Exception as exc: # noqa: BLE001
- params = dict(frag.params or {})
- prev_gen = params.get("generation") if isinstance(params.get("generation"), dict) else None
- params["generation_attempts"] = attempts
- params["generation"] = build_failed_generation_params(
- prev_gen if isinstance(prev_gen, dict) else None,
- str(exc),
- attempts=attempts,
- attempt_limit=max_attempts,
- )
- frag.params = params
- await db.commit()
- logger.exception(
- "分镜视频失败 fragment_id=%s attempt=%s/%s",
- fragment_id,
- attempts,
- max_attempts,
- )
- return False
-
-
-async def run_fragment_generate_job(
- episode_id: int,
- user_id: int,
- fragment_id: int,
- remaining_ids: list[int] | None = None,
-) -> dict[str, Any]:
- # Legacy:单镜 + 链式衔接的进程内路径,无任务平台计费。
- remaining = [int(x) for x in (remaining_ids or [])]
- logger.info(
- "开始生成分镜视频 episode_id=%s fragment_id=%s rest=%s",
- episode_id,
- fragment_id,
- len(remaining),
- )
- ok = await _generate_one_fragment_video(
- episode_id=episode_id,
- user_id=user_id,
- fragment_id=int(fragment_id),
- sem=asyncio.Semaphore(1),
- )
- logger.info(
- "分镜视频结束 episode_id=%s fragment_id=%s ok=%s rest=%s",
- episode_id,
- fragment_id,
- ok,
- len(remaining),
- )
- if remaining and not _is_episode_video_cancelled(episode_id):
- if ok:
- still_queued: list[int] = []
- async with AsyncSessionLocal() as db:
- for fid in remaining:
- frag = await db.get(DramaEpisodeFragment, int(fid))
- if not frag:
- continue
- gen = frag.params.get("generation") if isinstance(frag.params, dict) else None
- status = str(gen.get("status") or "") if isinstance(gen, dict) else ""
- if status in {"queued", "running"}:
- still_queued.append(int(fid))
- if still_queued:
- next_id = still_queued[0]
- rest = still_queued[1:]
- asyncio.create_task(_run_fragment_chain_inprocess(episode_id, user_id, still_queued))
- logger.info(
- "已衔接下一镜 episode_id=%s next=%s rest=%s",
- episode_id,
- next_id,
- len(rest),
- )
- else:
- await _fail_remaining_fragment_videos(remaining, "上一镜失败,无法衔接尾帧")
- return {
- "ok": ok,
- "episode_id": episode_id,
- "fragment_id": fragment_id,
- "remaining": len(remaining),
- }
-
+# ---------- episode video (task platform) ----------
# 任务平台(NIO):Worker 短生命周期 — prepare → submit → 注册 awaiting_poll,由 Selector 轮询。
async def submit_fragment_video_task(task: TaskRun) -> dict[str, Any]:
@@ -1234,6 +881,8 @@ async def poll_fragment_video_task(task_id: int) -> None:
local_last_frame=local_last_frame,
attempts=attempts,
attempt_limit=attempt_limit,
+ task_result=result,
+ provider_task_id=task.provider_task_id,
)
batch_index = int(payload.get("batch_index", 0))
await activate_next_sequential_task(db, task.batch_key, batch_index)
@@ -1241,85 +890,6 @@ async def poll_fragment_video_task(task_id: int) -> None:
await _complete_task(db, task, {"ok": True, "fragment_id": fragment_id})
-async def run_episode_generate_job(
- episode_id: int,
- user_id: int,
- fragment_ids: list[int],
-) -> dict[str, Any]:
- # Legacy:整批分镜进程内生成,绕过任务平台 freeze/settle。handlers 已改 submit_fragment_video_task。
- _clear_episode_video_cancelled(episode_id)
- logger.info(
- "开始生成分集视频 episode_id=%s fragments=%s",
- episode_id,
- len(fragment_ids),
- )
- async with AsyncSessionLocal() as db:
- ep = await db.get(
- DramaEpisode,
- episode_id,
- options=[
- selectinload(DramaEpisode.project).selectinload(DramaProject.script),
- ],
- )
- if not ep:
- logger.warning("分集视频失败:分集不存在 episode_id=%s", episode_id)
- return {"ok": False, "error": "missing_episode"}
- project = ep.project
- user = await db.get(User, user_id)
- if not project or not user:
- return {"ok": False, "error": "missing_project_or_user"}
-
- # valid_ids 属于本集且存在的分镜(保持入队顺序)
- valid_ids: list[int] = []
- for fid in fragment_ids:
- frag = await db.get(DramaEpisodeFragment, fid)
- if frag and frag.episode_id == episode_id:
- valid_ids.append(fid)
- link = project_link_last_frame_enabled(project)
-
- if link:
- # 旧版整集任务也按镜序,避免并行丢掉尾帧
- logger.info(
- "分集视频串行衔接 episode_id=%s fragments=%s",
- episode_id,
- len(valid_ids),
- )
- await _run_fragment_chain_inprocess(episode_id, user_id, valid_ids)
- _clear_episode_video_cancelled(episode_id)
- return {"ok": True, "episode_id": episode_id}
-
- # 未开启衔接时按 Seedance 并发上限并行
- limit = max(1, int(get_settings().pipeline_video_concurrency or 10))
- sem = asyncio.Semaphore(limit)
- logger.info(
- "分集视频并发 episode_id=%s concurrency=%s fragments=%s",
- episode_id,
- limit,
- len(valid_ids),
- )
- results = await asyncio.gather(
- *[
- _generate_one_fragment_video(
- episode_id=episode_id,
- user_id=user_id,
- fragment_id=fid,
- sem=sem,
- )
- for fid in valid_ids
- ]
- )
- ok_count = sum(1 for ok in results if ok)
- fail_count = len(results) - ok_count
- _clear_episode_video_cancelled(episode_id)
- logger.info(
- "分集视频结束 episode_id=%s ok=%s fail=%s",
- episode_id,
- ok_count,
- fail_count,
- )
- return {"ok": True, "episode_id": episode_id}
-
-
# ---------- asset image ----------
diff --git a/backend/app/services/email.py b/backend/app/services/email.py
new file mode 100644
index 0000000..a4b8d45
--- /dev/null
+++ b/backend/app/services/email.py
@@ -0,0 +1,92 @@
+# -*- coding: utf-8 -*-
+"""SMTP 邮件发送(管理员告警等)。"""
+from __future__ import annotations
+
+import asyncio
+import logging
+import smtplib
+from email.message import EmailMessage
+
+from app.config import Settings, get_settings
+
+logger = logging.getLogger(__name__)
+
+
+def _smtp_configured(settings: Settings | None = None) -> bool:
+ s = settings or get_settings()
+ return bool(
+ s.smtp_enabled
+ and str(s.smtp_host or "").strip()
+ and str(s.smtp_from or "").strip()
+ )
+
+
+def _send_email_sync(
+ *,
+ to_addrs: list[str],
+ subject: str,
+ body: str,
+ settings: Settings | None = None,
+) -> None:
+ s = settings or get_settings()
+ if not _smtp_configured(s):
+ raise RuntimeError("SMTP 未配置或未启用")
+ recipients = [addr.strip() for addr in to_addrs if addr and addr.strip()]
+ if not recipients:
+ raise RuntimeError("无有效收件人")
+
+ msg = EmailMessage()
+ msg["Subject"] = subject
+ msg["From"] = str(s.smtp_from).strip()
+ msg["To"] = ", ".join(recipients)
+ msg.set_content(body)
+
+ port = int(s.smtp_port or 587)
+ use_tls = bool(s.smtp_use_tls)
+ user = str(s.smtp_user or "").strip()
+ password = str(s.smtp_password or "").strip()
+
+ if use_tls:
+ server = smtplib.SMTP(str(s.smtp_host).strip(), port, timeout=30)
+ try:
+ server.ehlo()
+ server.starttls()
+ server.ehlo()
+ if user and password:
+ server.login(user, password)
+ server.send_message(msg)
+ finally:
+ server.quit()
+ else:
+ server = smtplib.SMTP(str(s.smtp_host).strip(), port, timeout=30)
+ try:
+ if user and password:
+ server.login(user, password)
+ server.send_message(msg)
+ finally:
+ server.quit()
+
+
+async def send_email(
+ *,
+ to_addrs: list[str],
+ subject: str,
+ body: str,
+ settings: Settings | None = None,
+) -> bool:
+ """异步发送邮件;失败记录日志并返回 False。"""
+ if not _smtp_configured(settings):
+ logger.warning("skip email: smtp not configured subject=%s", subject)
+ return False
+ try:
+ await asyncio.to_thread(
+ _send_email_sync,
+ to_addrs=to_addrs,
+ subject=subject,
+ body=body,
+ settings=settings,
+ )
+ return True
+ except Exception:
+ logger.exception("send email failed subject=%s", subject)
+ return False
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
index 9929336..9fa4041 100644
--- a/backend/app/services/pipeline.py
+++ b/backend/app/services/pipeline.py
@@ -78,6 +78,67 @@ async def _record_usage_est(
await db.commit()
except Exception: # noqa: BLE001
logger.exception("billing record failed project=%s key=%s", project_id, billing_key)
+
+
+async def _record_seedream_usage(
+ project_id: int,
+ *,
+ image_result,
+ model: str,
+ shot_id: int | None = None,
+) -> None:
+ try:
+ from app.services.drama.billing_util import record_seedream_image_usage
+
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if not project:
+ return
+ await record_seedream_image_usage(
+ db,
+ user_id=project.user_id,
+ model=model,
+ domain="kepu",
+ image_result=image_result,
+ project_id=project_id,
+ shot_id=shot_id,
+ )
+ await db.commit()
+ except Exception: # noqa: BLE001
+ logger.exception("seedream billing record failed project=%s", project_id)
+
+
+async def _record_seedance_usage(
+ project_id: int,
+ *,
+ billing_key: str,
+ model: str,
+ task_result,
+ fallback_duration_sec: float,
+ shot_id: int | None = None,
+) -> None:
+ try:
+ from app.services.drama.billing_util import record_seedance_video_usage
+
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if not project:
+ return
+ await record_seedance_video_usage(
+ db,
+ user_id=project.user_id,
+ billing_key=billing_key,
+ model=model,
+ domain="kepu",
+ task_result=task_result,
+ fallback_duration_sec=fallback_duration_sec,
+ provider_task_id=getattr(task_result, "provider_task_id", None),
+ project_id=project_id,
+ shot_id=shot_id,
+ )
+ await db.commit()
+ except Exception: # noqa: BLE001
+ logger.exception("seedance billing record failed project=%s key=%s", project_id, billing_key)
# Seedream min pixels ~3686400; portrait 9:16 ≈ 1440x2560
_IMAGE_SIZE_BY_RATIO = {
"9:16": "1440x2560",
@@ -905,11 +966,11 @@ async def _parallel_image_and_audio(project_id: int) -> None:
size=image_size,
)
s = get_settings()
- await _record_usage_est(
+ await _record_seedream_usage(
project_id,
- "seedream",
- tokens=s.billing_est_seedream_tokens,
+ image_result=img,
model=s.model_image,
+ shot_id=meta["id"],
)
await persist_image(meta, img)
return img.remote_url or img.local_url
@@ -1111,7 +1172,7 @@ async def _parallel_videos(project_id: int) -> None:
hi=cfg.seedance_duration_max,
)
try:
- local_video = await ark.gen_and_wait_video(
+ local_video, task_result = await ark.gen_and_wait_video(
meta["image_ref"],
prompt,
int(dur),
@@ -1160,11 +1221,14 @@ async def _parallel_videos(project_id: int) -> None:
raise
s = get_settings()
dur = max(float(dur), 2.0)
- await _record_usage_est(
+ billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"
+ await _record_seedance_usage(
project_id,
- "seedance2:video0" if generate_audio else "seedance2:video1",
- tokens=int(dur * s.billing_est_seedance_tokens_per_sec),
+ billing_key=billing_key,
model=s.model_video,
+ task_result=task_result,
+ fallback_duration_sec=dur,
+ shot_id=meta["id"],
)
async with _db_write_lock():
async with AsyncSessionLocal() as db:
@@ -1336,7 +1400,7 @@ async def _video_stage(project_id: int) -> None:
hi=cfg.seedance_duration_max,
)
image_ref = shot.image_ark_url or shot.image_url or ""
- local_video = await ark.gen_and_wait_video(
+ local_video, task_result = await ark.gen_and_wait_video(
image_ref,
prompt,
int(dur),
@@ -1349,6 +1413,15 @@ async def _video_stage(project_id: int) -> None:
)
shot.video_url = local_video
shot.status = ShotStatus.VIDEO_READY
+ billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"
+ await _record_seedance_usage(
+ project_id,
+ billing_key=billing_key,
+ model=cfg.model_video,
+ task_result=task_result,
+ fallback_duration_sec=max(float(dur), 2.0),
+ shot_id=shot.id,
+ )
pct = 50 + int(25 * (idx + 1) / max(total, 1))
project.progress = pct
await db.commit()
@@ -1623,10 +1696,9 @@ async def regen_shot_image(project_id: int, shot_id: int) -> None:
project.final_video_url = None
await db.commit()
s = get_settings()
- await _record_usage_est(
+ await _record_seedream_usage(
project_id,
- "seedream",
- tokens=s.billing_est_seedream_tokens,
+ image_result=img,
model=s.model_image,
shot_id=shot_id,
)
@@ -1671,7 +1743,7 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
hi=cfg.seedance_duration_max,
)
image_ref = shot.image_ark_url or shot.image_url or ""
- local_video = await ark.gen_and_wait_video(
+ local_video, task_result = await ark.gen_and_wait_video(
image_ref,
prompt,
int(dur),
@@ -1687,16 +1759,16 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
shot.version += 1
project.final_video_url = None
project.status = ProjectStatus.VIDEO_READY
+ billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"
+ await _record_seedance_usage(
+ project_id,
+ billing_key=billing_key,
+ model=cfg.model_video,
+ task_result=task_result,
+ fallback_duration_sec=max(float(dur), 2.0),
+ shot_id=shot_id,
+ )
await db.commit()
- billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"
- tok = int(max(float(dur), 2.0) * cfg.billing_est_seedance_tokens_per_sec)
- await _record_usage_est(
- project_id,
- billing_key,
- tokens=tok,
- model=cfg.model_video,
- shot_id=shot_id,
- )
@storage.without_intermediate_oss
diff --git a/backend/app/services/studio_tools.py b/backend/app/services/studio_tools.py
index 2dfecf4..2a527c0 100644
--- a/backend/app/services/studio_tools.py
+++ b/backend/app/services/studio_tools.py
@@ -17,6 +17,7 @@ from app.models import ToolRun, User
from app.models_tasks import TaskRun
from app.services.ark import get_ark
from app.services.billing import record_line, run_billed_ephemeral
+from app.services.drama.billing_util import record_seedream_image_usage
from app.services.billing.estimates import estimate_task_fen
from app.services.billing.settlement import billing_active
from app.services.ffmpeg_compose import extract_video_poster_frame
@@ -196,14 +197,13 @@ async def run_image_tool(
shot_no=user.id,
size=size,
)
- await record_line(
+ await record_seedream_image_usage(
db,
user_id=user.id,
- billing_key="seedream",
model=get_settings().model_image,
- estimated=True,
domain="studio",
- raw={"tool_id": tool_id},
+ image_result=result,
+ extra_raw={"tool_id": tool_id},
)
url = result.local_url or result.remote_url or ""
if url:
@@ -387,13 +387,13 @@ async def start_video_tool(
shot_no=user.id,
size=ratio_to_size(ratio or "9:16"),
)
- await record_line(
+ await record_seedream_image_usage(
db,
user_id=user.id,
- billing_key="seedream",
- estimated=True,
+ model=get_settings().model_image,
domain="studio",
- raw={"tool_id": "t2v-still"},
+ image_result=still,
+ extra_raw={"tool_id": "t2v-still"},
)
preview_url = still.local_url or still.remote_url
if preview_url:
@@ -444,6 +444,10 @@ async def start_video_tool(
async def poll_video_task(user: User, task_id: str) -> dict:
ark = get_ark()
result = await ark.fetch_task_once(task_id)
+ usage = {
+ "total_tokens": int(result.total_tokens or 0),
+ "completion_tokens": int(result.completion_tokens or 0),
+ }
if result.status == "succeeded" and result.url:
dest = tools_dir(user.id) / f"v_{task_id[-10:]}.mp4"
if result.url.startswith("/static/"):
@@ -453,10 +457,23 @@ async def poll_video_task(user: User, task_id: str) -> dict:
else:
await storage.download_to(result.url, dest)
url = publish_public(dest)
- return {"status": "succeeded", "kind": "video", "urls": [url]}
+ return {
+ "status": "succeeded",
+ "kind": "video",
+ "urls": [url],
+ "usage": usage,
+ "raw_usage": result.raw_usage,
+ }
if result.status == "failed":
- return {"status": "failed", "kind": "video", "urls": [], "error": result.error or "生成失败"}
- return {"status": "running", "kind": "video", "urls": []}
+ return {
+ "status": "failed",
+ "kind": "video",
+ "urls": [],
+ "error": result.error or "生成失败",
+ "usage": usage,
+ "raw_usage": result.raw_usage,
+ }
+ return {"status": "running", "kind": "video", "urls": [], "usage": usage}
# 把一次工具生成写入 tool_runs(结果 URL 优先 OSS)
diff --git a/backend/app/services/tasks/poller.py b/backend/app/services/tasks/poller.py
index 8443480..faa0dca 100644
--- a/backend/app/services/tasks/poller.py
+++ b/backend/app/services/tasks/poller.py
@@ -213,5 +213,8 @@ async def _poll_ephemeral_deferred_tasks() -> None:
poll_status=status,
error=str(data.get("error") or "") or None,
billing_task_id=task.id,
+ usage_tokens=int((data.get("usage") or {}).get("total_tokens") or 0),
+ completion_tokens=int((data.get("usage") or {}).get("completion_tokens") or 0),
+ raw_usage=data.get("raw_usage") if isinstance(data.get("raw_usage"), dict) else None,
)
await db.commit()
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 37c1d06..57edce5 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -1,7 +1,6 @@
fastapi==0.115.12
uvicorn[standard]==0.34.2
sqlalchemy==2.0.40
-aiosqlite==0.21.0
asyncpg==0.30.0
psycopg2-binary==2.9.10
pydantic==2.11.3
diff --git a/backend/scripts/resplit_episode_overlong_fragments.py b/backend/scripts/resplit_episode_overlong_fragments.py
deleted file mode 100644
index e13cdae..0000000
--- a/backend/scripts/resplit_episode_overlong_fragments.py
+++ /dev/null
@@ -1,188 +0,0 @@
-"""将指定分集中 @duration 合计 >30s 的分镜按软/硬上限拆开并写回库。"""
-from __future__ import annotations
-
-import json
-import re
-import sqlite3
-from pathlib import Path
-
-from app.services.drama.build_fragments import (
- FRAGMENT_TOTAL_MAX,
- split_overlong_fragment_content,
-)
-
-DB = Path(__file__).resolve().parents[1] / "ai_movie.db"
-ASSET_RE = re.compile(r"@asset:(\d+)")
-DURATION_RE = re.compile(r"@duration:(\d+)")
-
-
-def sum_duration(content: str) -> int:
- return sum(int(m) for m in DURATION_RE.findall(content or ""))
-
-
-def extract_asset_ids(content: str) -> list[int]:
- seen: set[int] = set()
- out: list[int] = []
- for m in ASSET_RE.finditer(content or ""):
- aid = int(m.group(1))
- if aid and aid not in seen:
- seen.add(aid)
- out.append(aid)
- return out
-
-
-def find_episode_id(conn: sqlite3.Connection, episode_number: int = 2) -> int:
- rows = conn.execute(
- "SELECT id, name, params FROM drama_episodes ORDER BY id"
- ).fetchall()
- for row in rows:
- try:
- params = json.loads(row["params"] or "{}")
- except Exception:
- params = {}
- if int(params.get("episodeNumber") or params.get("episode_number") or 0) == episode_number:
- return int(row["id"])
- raise SystemExit(f"未找到第 {episode_number} 集")
-
-
-def main() -> None:
- conn = sqlite3.connect(DB)
- conn.row_factory = sqlite3.Row
- episode_id = find_episode_id(conn, 2)
- frags = conn.execute(
- """
- SELECT id, sort_order, duration_sec, content, cover, video, params
- FROM drama_episode_fragments
- WHERE episode_id=?
- ORDER BY sort_order, id
- """,
- (episode_id,),
- ).fetchall()
-
- # old_id -> asset_ids
- ref_map: dict[int, list[int]] = {}
- for f in frags:
- rows = conn.execute(
- "SELECT asset_id FROM drama_fragment_asset_refs WHERE fragment_id=? ORDER BY id",
- (f["id"],),
- ).fetchall()
- ref_map[int(f["id"])] = [int(r["asset_id"]) for r in rows]
-
- rebuilt: list[dict] = []
- split_count = 0
- for f in frags:
- content = f["content"] or ""
- total = sum_duration(content)
- params = {}
- try:
- params = json.loads(f["params"] or "{}") if f["params"] else {}
- except Exception:
- params = {}
- if not isinstance(params, dict):
- params = {}
-
- if total <= FRAGMENT_TOTAL_MAX:
- rebuilt.append(
- {
- "content": content,
- "cover": f["cover"] or "",
- "video": f["video"] or "",
- "duration_sec": int(f["duration_sec"] or total or 8),
- "params": params,
- "asset_ids": ref_map.get(int(f["id"])) or extract_asset_ids(content),
- }
- )
- continue
-
- chunks = split_overlong_fragment_content(content)
- if len(chunks) <= 1:
- rebuilt.append(
- {
- "content": content,
- "cover": f["cover"] or "",
- "video": f["video"] or "",
- "duration_sec": min(FRAGMENT_TOTAL_MAX, total),
- "params": params,
- "asset_ids": ref_map.get(int(f["id"])) or extract_asset_ids(content),
- }
- )
- continue
-
- split_count += 1
- print(
- f"split frag sort={f['sort_order']} id={f['id']} {total}s -> "
- f"{[d for _, d in chunks]}"
- )
- for idx, (chunk_content, chunk_dur) in enumerate(chunks):
- chunk_params = {
- **params,
- "user_edited": True,
- "resplit_from": int(f["id"]),
- "resplit_index": idx,
- }
- # 拆开后旧成片不再对应,清空 video;封面仅保留首块
- chunk_cover = (f["cover"] or "") if idx == 0 else ""
- asset_ids = extract_asset_ids(chunk_content)
- if not asset_ids:
- asset_ids = list(ref_map.get(int(f["id"])) or [])
- rebuilt.append(
- {
- "content": chunk_content,
- "cover": chunk_cover,
- "video": "",
- "duration_sec": chunk_dur,
- "params": chunk_params,
- "asset_ids": asset_ids,
- }
- )
-
- if split_count == 0:
- print("没有需要拆分的超长分镜")
- return
-
- # 事务:删旧分镜(级联删 refs)再插入
- cur = conn.cursor()
- cur.execute("BEGIN")
- try:
- cur.execute(
- "DELETE FROM drama_episode_fragments WHERE episode_id=?",
- (episode_id,),
- )
- for order, item in enumerate(rebuilt):
- cur.execute(
- """
- INSERT INTO drama_episode_fragments
- (episode_id, sort_order, content, cover, video, duration_sec, params)
- VALUES (?, ?, ?, ?, ?, ?, ?)
- """,
- (
- episode_id,
- order,
- item["content"],
- item["cover"],
- item["video"],
- item["duration_sec"],
- json.dumps(item["params"], ensure_ascii=False),
- ),
- )
- frag_id = cur.lastrowid
- for aid in item["asset_ids"]:
- cur.execute(
- """
- INSERT OR IGNORE INTO drama_fragment_asset_refs (fragment_id, asset_id)
- VALUES (?, ?)
- """,
- (frag_id, aid),
- )
- conn.commit()
- except Exception:
- conn.rollback()
- raise
-
- print(f"done episode_id={episode_id} fragments={len(rebuilt)} split_sources={split_count}")
- for order, item in enumerate(rebuilt):
- print(f" #{order} duration={item['duration_sec']}s assets={item['asset_ids']}")
-
-
-if __name__ == "__main__":
- main()
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index b2424d3..7f7b20f 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -1,4 +1,4 @@
-"""计费集成测试:内存 SQLite + 开启 billing。"""
+"""计费/管理端集成测试:PostgreSQL + 开启 billing。"""
from __future__ import annotations
import uuid
@@ -6,8 +6,7 @@ from collections.abc import AsyncIterator
import pytest
import pytest_asyncio
-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
-from sqlalchemy.pool import StaticPool
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from app.config import get_settings
from app.database import Base
@@ -25,7 +24,7 @@ def billing_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
@pytest_asyncio.fixture
async def db_session(billing_enabled: None) -> AsyncIterator[AsyncSession]:
- """每个用例独立内存库,自动建表。"""
+ """每个用例外层事务回滚;session.commit 只提交 savepoint,不落库。"""
# 注册全部 ORM 表
import app.models # noqa: F401
import app.models_agent # noqa: F401
@@ -34,17 +33,36 @@ async def db_session(billing_enabled: None) -> AsyncIterator[AsyncSession]:
import app.models_settings # noqa: F401
import app.models_tasks # noqa: F401
- engine = create_async_engine(
- "sqlite+aiosqlite:///:memory:",
- connect_args={"check_same_thread": False},
- poolclass=StaticPool,
- )
+ url = (get_settings().database_url or "").strip()
+ if not url.startswith("postgresql"):
+ raise RuntimeError("集成测试需要 PostgreSQL DATABASE_URL(postgresql+asyncpg://...)")
+
+ engine = create_async_engine(url, pool_pre_ping=True)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
+ # 增量列(与 main._apply_schema_patches 保持一致)
+ from sqlalchemy import text
+
+ result = await conn.execute(
+ text(
+ "SELECT column_name FROM information_schema.columns "
+ "WHERE table_schema = 'public' AND table_name = 'users'"
+ )
+ )
+ ucols = {row[0] for row in result.fetchall()}
+ if "billing_alert_last_milestone_fen" not in ucols:
+ await conn.execute(
+ text("ALTER TABLE users ADD COLUMN billing_alert_last_milestone_fen INTEGER DEFAULT 0")
+ )
- session_factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
- async with session_factory() as session:
- yield session
+ async with engine.connect() as conn:
+ outer = await conn.begin()
+ session = AsyncSession(bind=conn, expire_on_commit=False, join_transaction_mode="create_savepoint")
+ try:
+ yield session
+ finally:
+ await session.close()
+ await outer.rollback()
await engine.dispose()
diff --git a/backend/tests/test_admin_readonly_filters.py b/backend/tests/test_admin_readonly_filters.py
new file mode 100644
index 0000000..f1afdae
--- /dev/null
+++ b/backend/tests/test_admin_readonly_filters.py
@@ -0,0 +1,346 @@
+"""管理端只读列表筛选:users / works / usage / templates / drama-projects。"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.admin.drama_projects import list_drama_projects
+from app.api.admin.templates import list_templates
+from app.api.admin.usage import list_usage_events
+from app.api.admin.users import list_users
+from app.api.admin.works import list_works
+from app.models import Template, UsageEvent, User, Work
+from app.models_drama import DramaProject, DramaScript
+from tests.conftest import make_user
+
+
+async def _make_admin(db: AsyncSession) -> User:
+ admin = await make_user(db)
+ admin.email = f"admin-{uuid.uuid4().hex[:8]}@example.com"
+ admin.role = "admin"
+ await db.flush()
+ return admin
+
+
+async def _valid_user(db: AsyncSession, **kwargs: object) -> User:
+ user = await make_user(db)
+ user.email = f"user-{uuid.uuid4().hex[:8]}@example.com"
+ for key, value in kwargs.items():
+ setattr(user, key, value)
+ await db.flush()
+ return user
+
+
+async def test_admin_users_filter_plan_and_unlimited(db_session: AsyncSession) -> None:
+ admin = await _make_admin(db_session)
+ pro = await _valid_user(db_session, plan="pro", billing_unlimited=True)
+ await _valid_user(db_session, plan="free", billing_unlimited=False)
+ await db_session.commit()
+
+ res = await list_users(
+ plan="pro",
+ role=None,
+ billing_unlimited=True,
+ q=None,
+ page=1,
+ page_size=20,
+ _admin=admin,
+ db=db_session,
+ )
+ ids = {u.id for u in res.items}
+ assert pro.id in ids
+ assert all(u.plan == "pro" and u.billing_unlimited for u in res.items)
+
+
+async def test_admin_users_search_by_numeric_id(db_session: AsyncSession) -> None:
+ admin = await _make_admin(db_session)
+ target = await _valid_user(db_session)
+ await db_session.commit()
+
+ res = await list_users(
+ q=str(target.id),
+ plan=None,
+ role=None,
+ billing_unlimited=None,
+ page=1,
+ page_size=5,
+ _admin=admin,
+ db=db_session,
+ )
+ assert any(u.id == target.id for u in res.items)
+
+
+async def test_admin_works_filter_q_and_user_id(db_session: AsyncSession) -> None:
+ admin = await _make_admin(db_session)
+ owner = await _valid_user(db_session)
+ other = await _valid_user(db_session)
+ tpl = Template(
+ id=f"t-{uuid.uuid4().hex[:8]}",
+ name="Test Template",
+ style_prefix="test",
+ )
+ db_session.add(tpl)
+ await db_session.flush()
+ from app.models import Project
+
+ project = Project(user_id=owner.id, template_id=tpl.id, source_text="x", title="p")
+ db_session.add(project)
+ await db_session.flush()
+ db_session.add(
+ Work(
+ project_id=project.id,
+ user_id=owner.id,
+ title="UniqueWorkTitle",
+ video_url="/v.mp4",
+ )
+ )
+ other_project = Project(user_id=other.id, template_id=tpl.id, source_text="y", title="p2")
+ db_session.add(other_project)
+ await db_session.flush()
+ db_session.add(
+ Work(project_id=other_project.id, user_id=other.id, title="OtherWork", video_url="/v2.mp4")
+ )
+ await db_session.commit()
+
+ res = await list_works(
+ audit_status=None,
+ visibility=None,
+ q="UniqueWork",
+ user_id=owner.id,
+ page=1,
+ page_size=20,
+ _admin=admin,
+ db=db_session,
+ )
+ assert len(res.items) == 1
+ assert res.items[0].title == "UniqueWorkTitle"
+
+
+async def test_admin_usage_filter_project_ids(db_session: AsyncSession) -> None:
+ admin = await _make_admin(db_session)
+ user = await _valid_user(db_session)
+ tpl = Template(id=f"u-{uuid.uuid4().hex[:8]}", name="u", style_prefix="s")
+ db_session.add(tpl)
+ await db_session.flush()
+ from app.models import Project
+
+ project = Project(user_id=user.id, template_id=tpl.id, source_text="u", title="u")
+ db_session.add(project)
+ await db_session.flush()
+ ev1 = UsageEvent(
+ user_id=user.id,
+ project_id=project.id,
+ domain="kepu",
+ capability="llm",
+ billing_key="llm_chat",
+ model="m",
+ charge_fen=10,
+ cost_fen=5,
+ provider="ark",
+ )
+ ev2 = UsageEvent(
+ user_id=user.id,
+ drama_project_id=202,
+ domain="drama",
+ capability="video",
+ billing_key="seedance",
+ model="m",
+ charge_fen=20,
+ cost_fen=8,
+ )
+ db_session.add_all([ev1, ev2])
+ await db_session.commit()
+
+ by_project = await list_usage_events(
+ project_id=project.id,
+ drama_project_id=None,
+ user_id=None,
+ task_run_id=None,
+ domain=None,
+ billing_key=None,
+ capability=None,
+ estimated=None,
+ billing_basis=None,
+ created_from=None,
+ created_to=None,
+ page=1,
+ page_size=20,
+ _admin=admin,
+ db=db_session,
+ )
+ assert len(by_project.items) == 1
+ assert by_project.items[0].project_id == project.id
+ assert by_project.items[0].provider == "ark"
+
+ by_drama = await list_usage_events(
+ project_id=None,
+ drama_project_id=202,
+ user_id=None,
+ task_run_id=None,
+ domain=None,
+ billing_key=None,
+ capability=None,
+ estimated=None,
+ billing_basis=None,
+ created_from=None,
+ created_to=None,
+ page=1,
+ page_size=20,
+ _admin=admin,
+ db=db_session,
+ )
+ assert len(by_drama.items) == 1
+ assert by_drama.items[0].drama_project_id == 202
+
+
+async def test_admin_templates_filter_active_and_category(db_session: AsyncSession) -> None:
+ admin = await _make_admin(db_session)
+ db_session.add_all(
+ [
+ Template(id="tpl-a", name="Alpha", style_prefix="a", category=["science"], is_active=True),
+ Template(id="tpl-b", name="Beta", style_prefix="b", category=["drama"], is_active=False),
+ ]
+ )
+ await db_session.commit()
+
+ res = await list_templates(
+ q="Alpha",
+ is_active=True,
+ category="science",
+ page=1,
+ page_size=20,
+ _admin=admin,
+ db=db_session,
+ )
+ assert len(res.items) == 1
+ assert res.items[0].id == "tpl-a"
+
+
+async def test_admin_drama_projects_filter_status(db_session: AsyncSession) -> None:
+ admin = await _make_admin(db_session)
+ user = await _valid_user(db_session)
+ p1 = DramaProject(user_id=user.id, title="DramaA", params={"assets_seed_status": "ready"})
+ p2 = DramaProject(user_id=user.id, title="DramaB", params={"assets_seed_status": "pending"})
+ db_session.add_all([p1, p2])
+ await db_session.flush()
+ db_session.add(DramaScript(project_id=p1.id, params={"summary_status": "done"}, name="s1"))
+ db_session.add(DramaScript(project_id=p2.id, params={"summary_status": "draft"}, name="s2"))
+ await db_session.commit()
+
+ res = await list_drama_projects(
+ page=1,
+ page_size=20,
+ q=None,
+ user_id=None,
+ summary_status="done",
+ assets_seed_status="ready",
+ _admin=admin,
+ db=db_session,
+ )
+ assert len(res.items) == 1
+ assert res.items[0].title == "DramaA"
+
+
+async def test_admin_drama_assets_filter_project_and_type(db_session: AsyncSession) -> None:
+ from app.api.admin.drama_assets import list_drama_assets
+ from app.models_drama import DramaAsset
+
+ admin = await _make_admin(db_session)
+ user = await _valid_user(db_session)
+ p1 = DramaProject(user_id=user.id, title="Proj1")
+ p2 = DramaProject(user_id=user.id, title="Proj2")
+ db_session.add_all([p1, p2])
+ await db_session.flush()
+ db_session.add_all(
+ [
+ DramaAsset(project_id=p1.id, type="character", name="Hero", params={"generation": {"status": "done"}}),
+ DramaAsset(project_id=p2.id, type="prop", name="Sword"),
+ ]
+ )
+ await db_session.commit()
+
+ by_project = await list_drama_assets(
+ page=1,
+ page_size=20,
+ q=None,
+ user_id=None,
+ project_id=p1.id,
+ asset_kind=None,
+ asset_type=None,
+ generation_status=None,
+ _admin=admin,
+ db=db_session,
+ )
+ assert len(by_project.items) == 1
+ assert by_project.items[0].name == "Hero"
+
+ by_type = await list_drama_assets(
+ page=1,
+ page_size=20,
+ q=None,
+ user_id=None,
+ project_id=p2.id,
+ asset_kind="prop",
+ asset_type=None,
+ generation_status=None,
+ _admin=admin,
+ db=db_session,
+ )
+ assert len(by_type.items) == 1
+ assert by_type.items[0].name == "Sword"
+ assert by_type.meta.total == 1
+
+
+async def test_admin_drama_assets_filter_generation_status(db_session: AsyncSession) -> None:
+ from app.api.admin.drama_assets import list_drama_assets
+ from app.models_drama import DramaAsset
+
+ admin = await _make_admin(db_session)
+ user = await _valid_user(db_session)
+ project = DramaProject(user_id=user.id, title="GenFilter")
+ db_session.add(project)
+ await db_session.flush()
+ db_session.add_all(
+ [
+ DramaAsset(
+ project_id=project.id,
+ type="character",
+ name="DoneHero",
+ params={"generation": {"status": "done"}},
+ ),
+ DramaAsset(
+ project_id=project.id,
+ type="prop",
+ name="FailedProp",
+ params={"generation": {"status": "failed"}},
+ ),
+ ]
+ )
+ await db_session.commit()
+
+ done_only = await list_drama_assets(
+ page=1,
+ page_size=20,
+ q=None,
+ user_id=None,
+ project_id=project.id,
+ asset_kind=None,
+ asset_type=None,
+ generation_status="done",
+ _admin=admin,
+ db=db_session,
+ )
+ assert len(done_only.items) == 1
+ assert done_only.items[0].name == "DoneHero"
+ assert done_only.items[0].generation_status == "done"
diff --git a/backend/tests/test_admin_stats.py b/backend/tests/test_admin_stats.py
index e7e91a0..518ff91 100644
--- a/backend/tests/test_admin_stats.py
+++ b/backend/tests/test_admin_stats.py
@@ -82,7 +82,7 @@ async def test_dashboard_daily_usage_pads_seven_days(db_session: AsyncSession) -
stats = await build_admin_dashboard_stats(db_session)
daily = stats["daily_usage"]
assert len(daily) == 7
- assert all("date" in d and "calls" in d and "charge_fen" in d for d in daily)
+ assert all("date" in d and "calls" in d and "charge_fen" in d and "cost_fen" in d for d in daily)
# 日期升序且连续
dates = [d["date"] for d in daily]
assert dates == sorted(dates)
@@ -103,6 +103,140 @@ async def test_dashboard_daily_usage_pads_seven_days(db_session: AsyncSession) -
assert stats["usage_charge_today_fen"] == 50
+async def test_dashboard_filters_domain_and_capability(db_session: AsyncSession) -> None:
+ """按领域与能力筛选后,分布桶只含匹配数据。"""
+ user = await make_user(db_session)
+ await _add_usage(
+ db_session,
+ user_id=user.id,
+ charge_fen=50,
+ cost_fen=20,
+ created_at=_utc_days_ago(1),
+ capability="image",
+ domain="drama",
+ billing_key="seedream",
+ )
+ await _add_usage(
+ db_session,
+ user_id=user.id,
+ charge_fen=30,
+ cost_fen=10,
+ created_at=_utc_days_ago(1),
+ capability="video",
+ billing_key="seedance2:video0",
+ domain="kepu",
+ )
+ await db_session.commit()
+
+ drama_only = await build_admin_dashboard_stats(db_session, days=7, domain="drama")
+ assert sum(b["calls"] for b in drama_only["usage_by_capability"]) == 1
+ assert drama_only["usage_by_capability"][0]["key"] == "image"
+ assert drama_only["usage_by_capability"][0]["cost_fen"] == 20
+
+ video_only = await build_admin_dashboard_stats(db_session, days=7, capability="video")
+ assert len(video_only["usage_by_domain"]) == 1
+ assert video_only["usage_by_domain"][0]["key"] == "kepu"
+ assert video_only["daily_usage"][-1]["calls"] == 0
+
+
+async def test_dashboard_today_window(db_session: AsyncSession) -> None:
+ """days=1 时仅统计今日,趋势序列 1 行。"""
+ user = await make_user(db_session)
+ domain = "test_today_window"
+ await _add_usage(
+ db_session,
+ user_id=user.id,
+ charge_fen=40,
+ cost_fen=12,
+ created_at=_utc_days_ago(0),
+ capability="llm",
+ domain=domain,
+ )
+ await _add_usage(
+ db_session,
+ user_id=user.id,
+ charge_fen=99,
+ created_at=_utc_days_ago(1),
+ capability="llm",
+ domain=domain,
+ )
+ await db_session.commit()
+
+ stats = await build_admin_dashboard_stats(db_session, days=1, domain=domain)
+ assert len(stats["daily_usage"]) == 1
+ today_key = _utc_days_ago(0).date().isoformat()
+ assert stats["daily_usage"][0]["date"] == today_key
+ assert stats["daily_usage"][0]["calls"] == 1
+ assert stats["daily_usage"][0]["charge_fen"] == 40
+ assert sum(b["calls"] for b in stats["usage_by_capability"]) == 1
+
+
+async def test_admin_stats_route_days_one(db_session: AsyncSession) -> None:
+ """admin_stats 路由 days=1 返回单日趋势。"""
+ import uuid
+
+ from app.api.admin.dashboard import admin_stats
+
+ admin = await make_user(db_session)
+ admin.email = f"admin-{uuid.uuid4().hex[:8]}@example.com"
+ admin.role = "admin"
+ await db_session.flush()
+
+ domain = "test_stats_route_today"
+ await _add_usage(
+ db_session,
+ user_id=admin.id,
+ charge_fen=25,
+ created_at=_utc_days_ago(0),
+ capability="llm",
+ domain=domain,
+ )
+ await _add_usage(
+ db_session,
+ user_id=admin.id,
+ charge_fen=80,
+ created_at=_utc_days_ago(1),
+ capability="llm",
+ domain=domain,
+ )
+ await db_session.commit()
+
+ out = await admin_stats(
+ days=1,
+ domain=domain,
+ capability="all",
+ _admin=admin,
+ db=db_session,
+ )
+ assert len(out.daily_usage) == 1
+ assert out.daily_usage[0].calls == 1
+ assert out.daily_usage[0].charge_fen == 25
+
+
+async def test_dashboard_days_window_padding(db_session: AsyncSession) -> None:
+ """days=14 时趋势序列固定 14 行并补零。"""
+ user = await make_user(db_session)
+ await _add_usage(
+ db_session,
+ user_id=user.id,
+ charge_fen=10,
+ created_at=_utc_days_ago(10),
+ capability="llm",
+ )
+ await db_session.commit()
+
+ stats = await build_admin_dashboard_stats(db_session, days=14)
+ assert len(stats["daily_usage"]) == 14
+ ten_ago = _utc_days_ago(10).date().isoformat()
+ by_day = {d["date"]: d for d in stats["daily_usage"]}
+ assert by_day[ten_ago]["calls"] == 1
+ assert by_day[ten_ago]["charge_fen"] == 10
+
+
@pytest.mark.asyncio
async def test_dashboard_top_users_by_charge(db_session: AsyncSession) -> None:
"""近 30 日按扣费排序,最多 10 人。"""
diff --git a/backend/tests/test_admin_upstream_usage.py b/backend/tests/test_admin_upstream_usage.py
new file mode 100644
index 0000000..352f24a
--- /dev/null
+++ b/backend/tests/test_admin_upstream_usage.py
@@ -0,0 +1,50 @@
+"""官方上游用量快照与本地对照。"""
+
+from __future__ import annotations
+
+from datetime import UTC, date, datetime, timedelta
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models import UpstreamUsageDaily, UsageEvent
+from app.services.admin.upstream_usage import build_upstream_usage_compare
+from tests.conftest import make_user
+
+
+async def test_build_upstream_usage_compare_merges_local_and_snapshot(db_session: AsyncSession) -> None:
+ user = await make_user(db_session)
+ day = datetime.now(UTC).date()
+ db_session.add(
+ UsageEvent(
+ user_id=user.id,
+ billing_key="seedance2:video0",
+ model="doubao-seedance",
+ total_tokens=50_000,
+ cost_fen=2300,
+ charge_fen=3450,
+ estimated=False,
+ domain="drama",
+ created_at=datetime.combine(day, datetime.min.time(), tzinfo=UTC),
+ )
+ )
+ db_session.add(
+ UpstreamUsageDaily(
+ usage_date=day,
+ official_tokens=48_000,
+ official_cost_fen=2208,
+ local_cost_fen=2300,
+ local_tokens=50_000,
+ fetched_at=datetime.now(UTC),
+ )
+ )
+ await db_session.commit()
+
+ raw = await build_upstream_usage_compare(db_session, days=7)
+ hit = next((row for row in raw["series"] if row["date"] == day.isoformat()), None)
+ assert hit is not None
+ assert hit["local_cost_fen"] == 2300
+ assert hit["official_tokens"] == 48_000
+ assert hit["official_cost_fen"] == 2208
+ assert hit["delta_fen"] == 92
diff --git a/backend/tests/test_ark_control_usage.py b/backend/tests/test_ark_control_usage.py
new file mode 100644
index 0000000..202caea
--- /dev/null
+++ b/backend/tests/test_ark_control_usage.py
@@ -0,0 +1,47 @@
+"""方舟管控面用量响应解析。"""
+
+from __future__ import annotations
+
+from app.services.ark_control_usage import (
+ aggregate_usage_by_day,
+ build_inference_usage_request_body,
+ parse_inference_usage_rows,
+)
+
+
+def test_build_inference_usage_request_body_uses_query_interval():
+ body = build_inference_usage_request_body("2026-08-01", "2026-08-07")
+ assert body == {
+ "StartTime": "2026-08-01",
+ "EndTime": "2026-08-07",
+ "QueryInterval": "Day",
+ }
+
+
+def test_parse_inference_usage_rows_table():
+ result = {
+ "Fields": [
+ {"Name": "Day", "Type": "DATE"},
+ {"Name": "ModelName", "Type": "STRING"},
+ {"Name": "Value", "Type": "BIGINT"},
+ ],
+ "Data": [
+ ["2026-08-26", "doubao-seedance-2-0", 500000],
+ ["2026-08-27", "doubao-seedance-2-0", 800000],
+ ],
+ }
+ rows = parse_inference_usage_rows(result)
+ assert len(rows) == 2
+ assert rows[0]["Day"] == "2026-08-26"
+ daily = aggregate_usage_by_day(rows)
+ assert daily["2026-08-26"] == 500000
+ assert daily["2026-08-27"] == 800000
+
+
+def test_aggregate_usage_by_day_skips_non_video_models():
+ rows = [
+ {"Day": "2026-08-26", "ModelName": "doubao-seedream", "Value": 1000},
+ {"Day": "2026-08-26", "ModelName": "doubao-seedance-2-0", "Value": 2000},
+ ]
+ daily = aggregate_usage_by_day(rows)
+ assert daily.get("2026-08-26") == 2000
diff --git a/backend/tests/test_ark_task_usage.py b/backend/tests/test_ark_task_usage.py
new file mode 100644
index 0000000..77fd132
--- /dev/null
+++ b/backend/tests/test_ark_task_usage.py
@@ -0,0 +1,43 @@
+"""Seedance 任务查询响应 usage 解析。"""
+
+from __future__ import annotations
+
+from app.services.ark import TaskResult, _build_task_result_from_payload
+
+
+def test_build_task_result_success_with_usage():
+ data = {
+ "status": "succeeded",
+ "content": {"video_url": "https://example.com/v.mp4"},
+ "usage": {"completion_tokens": 108900, "total_tokens": 108900},
+ }
+ result = _build_task_result_from_payload(data)
+ assert result.status == "succeeded"
+ assert result.url == "https://example.com/v.mp4"
+ assert result.total_tokens == 108900
+ assert result.completion_tokens == 108900
+ assert result.raw_usage == {"completion_tokens": 108900, "total_tokens": 108900}
+
+
+def test_build_task_result_failed_with_zero_usage():
+ data = {
+ "status": "failed",
+ "error": {"message": "upstream error"},
+ "usage": {"completion_tokens": 0, "total_tokens": 0},
+ }
+ result = _build_task_result_from_payload(data)
+ assert result.status == "failed"
+ assert result.total_tokens == 0
+
+
+def test_build_task_result_running_without_usage():
+ data = {"status": "running"}
+ result = _build_task_result_from_payload(data)
+ assert result.status == "running"
+ assert result.total_tokens == 0
+
+
+def test_task_result_dataclass_defaults():
+ row = TaskResult(status="running")
+ assert row.total_tokens == 0
+ assert row.raw_usage is None
diff --git a/backend/tests/test_billing_alerts.py b/backend/tests/test_billing_alerts.py
new file mode 100644
index 0000000..25c5449
--- /dev/null
+++ b/backend/tests/test_billing_alerts.py
@@ -0,0 +1,130 @@
+"""额度告警:用户里程碑弹窗与管理员邮件。"""
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models import UsageEvent
+from app.services.billing.alerts import (
+ acknowledge_user_alert,
+ list_pending_user_alerts,
+ process_admin_cost_alert,
+ process_billing_alerts_after_charge,
+ process_user_milestone_alert,
+)
+from tests.conftest import make_user
+
+
+async def _add_settled_usage(
+ db: AsyncSession,
+ *,
+ user_id: int,
+ charge_fen: int,
+ cost_fen: int = 0,
+) -> UsageEvent:
+ ev = UsageEvent(
+ user_id=user_id,
+ domain="api",
+ capability="llm",
+ billing_key="llm_chat",
+ model="test",
+ total_tokens=100,
+ charge_fen=charge_fen,
+ cost_fen=cost_fen,
+ settled=True,
+ )
+ db.add(ev)
+ await db.flush()
+ return ev
+
+
+async def test_user_milestone_creates_popup_notification(db_session: AsyncSession, monkeypatch) -> None:
+ settings = __import__("app.config", fromlist=["get_settings"]).get_settings()
+ monkeypatch.setattr(settings, "billing_user_alert_enabled", True)
+ monkeypatch.setattr(settings, "billing_user_alert_interval_fen", 1000)
+
+ user = await make_user(db_session)
+ await _add_settled_usage(db_session, user_id=user.id, charge_fen=2500)
+ await db_session.commit()
+
+ created = await process_user_milestone_alert(db_session, user, settings=settings)
+ await db_session.commit()
+
+ assert len(created) == 2
+ assert created[0].milestone_fen == 1000
+ assert created[1].milestone_fen == 2000
+ assert int(user.billing_alert_last_milestone_fen) == 2000
+
+ pending = await list_pending_user_alerts(db_session, user.id)
+ assert len(pending) == 2
+
+ ok = await acknowledge_user_alert(db_session, user.id, pending[0].id)
+ assert ok is True
+ await db_session.commit()
+ pending_after = await list_pending_user_alerts(db_session, user.id)
+ assert len(pending_after) == 1
+
+
+async def test_user_milestone_skips_unlimited(db_session: AsyncSession, monkeypatch) -> None:
+ settings = __import__("app.config", fromlist=["get_settings"]).get_settings()
+ monkeypatch.setattr(settings, "billing_user_alert_enabled", True)
+ monkeypatch.setattr(settings, "billing_user_alert_interval_fen", 1000)
+
+ user = await make_user(db_session, billing_unlimited=True)
+ await _add_settled_usage(db_session, user_id=user.id, charge_fen=5000)
+ await db_session.commit()
+
+ created = await process_user_milestone_alert(db_session, user, settings=settings)
+ assert created == []
+
+
+async def test_admin_cost_alert_sends_email_once_per_level(db_session: AsyncSession, monkeypatch) -> None:
+ settings = __import__("app.config", fromlist=["get_settings"]).get_settings()
+ monkeypatch.setattr(settings, "billing_admin_cost_alert_enabled", True)
+ monkeypatch.setattr(settings, "billing_admin_cost_alert_threshold_fen", 1000)
+ monkeypatch.setattr(settings, "billing_admin_cost_alert_period", "all_time")
+ monkeypatch.setattr(settings, "billing_admin_cost_alert_emails", "[email protected]")
+ monkeypatch.setattr(settings, "billing_admin_cost_alert_last_period_key", "")
+ monkeypatch.setattr(settings, "billing_admin_cost_alert_last_level", 0)
+ monkeypatch.setattr(settings, "app_name", "PRINTFILM")
+
+ user = await make_user(db_session)
+ await _add_settled_usage(db_session, user_id=user.id, charge_fen=100, cost_fen=1500)
+ await db_session.commit()
+
+ with patch("app.services.billing.alerts.send_email", new_callable=AsyncMock) as send_mock:
+ send_mock.return_value = True
+ sent = await process_admin_cost_alert(db_session, settings=settings)
+ await db_session.commit()
+ assert sent is True
+ send_mock.assert_called_once()
+
+ send_mock.reset_mock()
+ sent_again = await process_admin_cost_alert(db_session, settings=settings)
+ assert sent_again is False
+ send_mock.assert_not_called()
+
+
+async def test_process_after_charge_triggers_user_alert(db_session: AsyncSession, monkeypatch) -> None:
+ settings = __import__("app.config", fromlist=["get_settings"]).get_settings()
+ monkeypatch.setattr(settings, "billing_user_alert_enabled", True)
+ monkeypatch.setattr(settings, "billing_user_alert_interval_fen", 1000)
+ monkeypatch.setattr(settings, "billing_admin_cost_alert_enabled", False)
+
+ user = await make_user(db_session)
+ await _add_settled_usage(db_session, user_id=user.id, charge_fen=900)
+ await _add_settled_usage(db_session, user_id=user.id, charge_fen=200)
+ await db_session.commit()
+
+ await process_billing_alerts_after_charge(db_session, user, charged_fen=200, settings=settings)
+ await db_session.commit()
+
+ pending = await list_pending_user_alerts(db_session, user.id)
+ assert len(pending) == 1
+ assert pending[0].milestone_fen == 1000
diff --git a/backend/tests/test_billing_display.py b/backend/tests/test_billing_display.py
new file mode 100644
index 0000000..b026718
--- /dev/null
+++ b/backend/tests/test_billing_display.py
@@ -0,0 +1,126 @@
+"""计费依据展示与筛选。"""
+
+from __future__ import annotations
+
+import json
+import uuid
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models import UsageEvent
+from app.services.billing.display import (
+ billing_basis_label,
+ billing_basis_sql_filter,
+ resolve_billing_basis,
+)
+from tests.conftest import make_user
+
+
+def test_resolve_billing_basis_estimate():
+ assert resolve_billing_basis(estimated=True, raw_usage_json=None) == "estimate"
+ assert billing_basis_label("estimate") == "估算"
+
+
+def test_resolve_billing_basis_upstream_tokens():
+ raw = '{"usage": {"total_tokens": 120000}}'
+ assert resolve_billing_basis(estimated=False, raw_usage_json=raw) == "upstream_usage"
+ assert billing_basis_label("upstream_usage") == "实测(token)"
+
+
+def test_resolve_billing_basis_upstream_cost():
+ raw = '{"usage": {"cost_fen": 500}}'
+ assert resolve_billing_basis(estimated=False, raw_usage_json=raw) == "upstream_cost"
+ assert billing_basis_label("upstream_cost") == "实测(费用)"
+
+
+def test_resolve_billing_basis_unknown_without_usage():
+ assert resolve_billing_basis(estimated=False, raw_usage_json=None) == "unknown"
+ assert billing_basis_label("unknown") == "实测(未分类)"
+
+
+async def test_billing_basis_sql_filter_cost(db_session: AsyncSession) -> None:
+ from app.api.admin.usage import list_usage_events
+
+ user = await make_user(db_session)
+ user.email = f"basis-{uuid.uuid4().hex[:8]}@example.com"
+ user.role = "admin"
+ await db_session.flush()
+
+ db_session.add_all(
+ [
+ UsageEvent(
+ user_id=user.id,
+ domain="drama",
+ capability="video",
+ billing_key="seedance",
+ model="m",
+ charge_fen=10,
+ estimated=False,
+ raw_usage_json=json.dumps({"usage": {"cost_fen": 88}}),
+ ),
+ UsageEvent(
+ user_id=user.id,
+ domain="drama",
+ capability="video",
+ billing_key="seedance",
+ model="m",
+ charge_fen=5,
+ estimated=False,
+ raw_usage_json=json.dumps({"usage": {"total_tokens": 1000}}),
+ ),
+ UsageEvent(
+ user_id=user.id,
+ domain="drama",
+ capability="llm",
+ billing_key="llm_chat",
+ model="m",
+ charge_fen=1,
+ estimated=True,
+ ),
+ ]
+ )
+ await db_session.commit()
+
+ cost_only = await list_usage_events(
+ user_id=user.id,
+ task_run_id=None,
+ project_id=None,
+ drama_project_id=None,
+ domain=None,
+ billing_key=None,
+ capability=None,
+ estimated=None,
+ billing_basis="upstream_cost",
+ created_from=None,
+ created_to=None,
+ page=1,
+ page_size=20,
+ _admin=user,
+ db=db_session,
+ )
+ assert len(cost_only.items) == 1
+ assert cost_only.items[0].billing_basis == "upstream_cost"
+
+ token_only = await list_usage_events(
+ user_id=user.id,
+ task_run_id=None,
+ project_id=None,
+ drama_project_id=None,
+ domain=None,
+ billing_key=None,
+ capability=None,
+ estimated=None,
+ billing_basis="upstream_usage",
+ created_from=None,
+ created_to=None,
+ page=1,
+ page_size=20,
+ _admin=user,
+ db=db_session,
+ )
+ assert len(token_only.items) == 1
+ assert token_only.items[0].billing_basis == "upstream_usage"
+
+ assert billing_basis_sql_filter("invalid") is None
diff --git a/backend/tests/test_billing_integration.py b/backend/tests/test_billing_integration.py
index b36f1ee..dce51ce 100644
--- a/backend/tests/test_billing_integration.py
+++ b/backend/tests/test_billing_integration.py
@@ -1,4 +1,4 @@
-"""TaskRun 计费链路集成测试(内存 SQLite)。"""
+"""TaskRun 计费链路集成测试(PostgreSQL)。"""
from __future__ import annotations
import pytest
@@ -224,15 +224,20 @@ async def test_settle_deferred_video_poll_idempotent_on_success(db_session: Asyn
provider_task_id="upstream-ok-1",
poll_status="succeeded",
billing_task_id=task.id,
+ usage_tokens=120_000,
+ completion_tokens=120_000,
)
await db_session.commit()
assert task.billing_status == "settled"
assert task.status == "succeeded"
- first_count = len(
- (await db_session.execute(select(UsageEvent).where(UsageEvent.task_run_id == task.id))).scalars().all()
- )
+ usage_rows = (
+ await db_session.execute(select(UsageEvent).where(UsageEvent.task_run_id == task.id))
+ ).scalars().all()
+ first_count = len(usage_rows)
assert first_count == 1
+ assert usage_rows[0].total_tokens == 120_000
+ assert usage_rows[0].estimated is False
charged = int(task.billing_charged_fen or 0)
balance_after = user.balance_fen
diff --git a/backend/tests/test_record_seedream_image_usage.py b/backend/tests/test_record_seedream_image_usage.py
new file mode 100644
index 0000000..d529939
--- /dev/null
+++ b/backend/tests/test_record_seedream_image_usage.py
@@ -0,0 +1,56 @@
+"""record_seedream_image_usage 集成。"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.services.ark import ImageResult
+from app.services.drama.billing_util import record_seedream_image_usage
+from tests.conftest import make_user
+
+
+async def test_record_seedream_with_upstream_tokens(db_session: AsyncSession) -> None:
+ user = await make_user(db_session)
+ image = ImageResult(
+ local_url="/static/x.png",
+ total_tokens=120000,
+ completion_tokens=120000,
+ raw_usage={"total_tokens": 120000},
+ )
+ ev = await record_seedream_image_usage(
+ db_session,
+ user_id=user.id,
+ model="seedream-test",
+ domain="api",
+ image_result=image,
+ )
+ await db_session.commit()
+ assert ev.estimated is False
+ assert ev.total_tokens == 120000
+ assert ev.charge_fen >= 1
+
+
+async def test_record_seedream_with_upstream_cost_fen(db_session: AsyncSession, monkeypatch) -> None:
+ settings = __import__("app.config", fromlist=["get_settings"]).get_settings()
+ monkeypatch.setattr(settings, "billing_markup", 2.0)
+
+ user = await make_user(db_session)
+ image = ImageResult(
+ local_url="/static/x.png",
+ upstream_cost_fen=500,
+ raw_usage={"cost_fen": 500},
+ )
+ ev = await record_seedream_image_usage(
+ db_session,
+ user_id=user.id,
+ model="seedream-test",
+ domain="studio",
+ image_result=image,
+ )
+ await db_session.commit()
+ assert ev.estimated is False
+ assert ev.cost_fen == 500
+ assert ev.charge_fen == 1000
diff --git a/backend/tests/test_seedance_billing_usage.py b/backend/tests/test_seedance_billing_usage.py
new file mode 100644
index 0000000..9d0c6c9
--- /dev/null
+++ b/backend/tests/test_seedance_billing_usage.py
@@ -0,0 +1,57 @@
+"""Seedance 真实 usage 与估算 fallback 计费。"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models import UsageEvent
+from app.services.ark import TaskResult
+from app.services.drama.billing_util import record_seedance_video_usage
+from tests.conftest import make_user
+
+
+async def test_record_seedance_video_usage_real_tokens(db_session: AsyncSession) -> None:
+ user = await make_user(db_session)
+ task_result = TaskResult(
+ status="succeeded",
+ total_tokens=100_000,
+ completion_tokens=100_000,
+ raw_usage={"total_tokens": 100_000},
+ )
+ await record_seedance_video_usage(
+ db_session,
+ user_id=user.id,
+ billing_key="seedance2:video0",
+ model="doubao-seedance-2-0",
+ domain="drama",
+ task_result=task_result,
+ fallback_duration_sec=8,
+ drama_project_id=1,
+ )
+ await db_session.commit()
+ row = (await db_session.execute(select(UsageEvent).where(UsageEvent.user_id == user.id))).scalar_one()
+ assert row.total_tokens == 100_000
+ assert row.estimated is False
+ assert row.cost_fen > 0
+
+
+async def test_record_seedance_video_usage_fallback_estimate(db_session: AsyncSession) -> None:
+ user = await make_user(db_session)
+ await record_seedance_video_usage(
+ db_session,
+ user_id=user.id,
+ billing_key="seedance2:video0",
+ model="doubao-seedance-2-0",
+ domain="kepu",
+ task_result=None,
+ fallback_duration_sec=5,
+ project_id=9,
+ )
+ await db_session.commit()
+ row = (await db_session.execute(select(UsageEvent).where(UsageEvent.user_id == user.id))).scalar_one()
+ assert row.estimated is True
+ assert row.total_tokens > 0
diff --git a/backend/tests/test_seedream_billing_usage.py b/backend/tests/test_seedream_billing_usage.py
new file mode 100644
index 0000000..956ade4
--- /dev/null
+++ b/backend/tests/test_seedream_billing_usage.py
@@ -0,0 +1,54 @@
+"""Seedream / Seedance 上游 usage 与扣费换算。"""
+
+from __future__ import annotations
+
+from app.config import get_settings
+from app.services.billing.pricing import charge_fen_for_usage, parse_upstream_cost_fen
+from app.services.billing.usage import record_line
+
+
+def test_parse_upstream_cost_fen_from_yuan():
+ assert parse_upstream_cost_fen({"usage": {"cost": 1.23}}) == 123
+ assert parse_upstream_cost_fen({"usage": {"cost_fen": 456}}) == 456
+
+
+def test_charge_fen_for_usage_prefers_upstream_cost():
+ settings = get_settings()
+ settings.billing_markup = 1.5
+ cost, charge, used = charge_fen_for_usage(
+ 0,
+ "seedream",
+ raw_usage={"usage": {"cost_fen": 1000}},
+ settings=settings,
+ )
+ assert used is True
+ assert cost == 1000
+ assert charge == 1500
+
+
+def test_charge_fen_for_usage_falls_back_to_tokens():
+ settings = get_settings()
+ settings.billing_markup = 1.5
+ settings.billing_seedream_per_m = 8.0
+ cost, charge, used = charge_fen_for_usage(
+ 1_000_000,
+ "seedream",
+ raw_usage={"usage": {"total_tokens": 1_000_000}},
+ settings=settings,
+ )
+ assert used is False
+ assert cost == 800
+ assert charge == 1200
+
+
+def test_build_task_result_includes_usage():
+ from app.services.ark import _build_task_result_from_payload
+
+ data = {
+ "status": "succeeded",
+ "content": {"video_url": "https://example.com/v.mp4"},
+ "usage": {"total_tokens": 50000, "cost": 2.5},
+ }
+ result = _build_task_result_from_payload(data)
+ assert result.total_tokens == 50000
+ assert parse_upstream_cost_fen({"usage": result.raw_usage or {}}) == 250
diff --git a/deploy/scripts/import_drama_sqlite_to_postgres.py b/deploy/scripts/import_drama_sqlite_to_postgres.py
deleted file mode 100644
index 80ed9f2..0000000
--- a/deploy/scripts/import_drama_sqlite_to_postgres.py
+++ /dev/null
@@ -1,551 +0,0 @@
-#!/usr/bin/env python3
-"""
-从 sqlite(本地 backend/ai_movie.db)导入漫剧模块数据到 Postgres。
-
-导入范围:drama_projects / drama_scripts / drama_assets / drama_episodes /
-drama_episode_fragments / drama_fragment_asset_refs / drama_asset_episodes
-(含 project.content 里的 canvas_nodes / canvas_edges)。
-
-用户映射:按 owner email 对齐目标 users.id;缺失用户默认跳过该项目。
-
---replace:先清空目标库全部漫剧表,再按源表主键原样写入(画布 assetId 才能对上)。
-"""
-
-from __future__ import annotations
-
-import argparse
-import asyncio
-import json
-import re
-import sqlite3
-from datetime import datetime
-from typing import Any, Optional
-
-from sqlalchemy import select, text
-
-from app.database import AsyncSessionLocal
-from app.models import User
-from app.models_drama import (
- DramaAsset,
- DramaAssetEpisode,
- DramaEpisode,
- DramaEpisodeFragment,
- DramaFragmentAssetRef,
- DramaProject,
- DramaScript,
-)
-
-# 清空 / 重置序号时的表顺序(子表在前)
-DRAMA_TABLES = (
- "drama_fragment_asset_refs",
- "drama_asset_episodes",
- "drama_episode_fragments",
- "drama_assets",
- "drama_scripts",
- "drama_episodes",
- "drama_projects",
-)
-
-_ASSET_MENTION = re.compile(r"@asset:(\d+)")
-_ASSET_NODE = re.compile(r"^asset-(\d+)$")
-
-
-def _parse_dt(raw: Any) -> Optional[datetime]:
- # 把 sqlite 时间字段转成 datetime
- if raw is None:
- return None
- if isinstance(raw, datetime):
- return raw
- if isinstance(raw, (int, float)):
- return datetime.fromtimestamp(raw)
- s = str(raw).strip()
- if not s:
- return None
- try:
- return datetime.fromisoformat(s)
- except ValueError:
- pass
- try:
- return datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
- except ValueError:
- return None
-
-
-def _jload(raw: Any) -> Any:
- # sqlite JSON 文本 → dict/list
- if raw is None:
- return None
- if isinstance(raw, (dict, list)):
- return raw
- if isinstance(raw, str):
- s = raw.strip()
- if not s:
- return None
- try:
- return json.loads(s)
- except json.JSONDecodeError:
- return None
- return None
-
-
-def _rewrite_json(
- obj: Any,
- asset_map: dict[int, int],
- episode_map: dict[int, int],
- project_map: dict[int, int],
-) -> Any:
- """把嵌套 JSON 里的资产/分集/项目 id(含画布 assetId、@asset:n)改成目标库 id。"""
- if isinstance(obj, list):
- return [_rewrite_json(x, asset_map, episode_map, project_map) for x in obj]
- if isinstance(obj, dict):
- out: dict[str, Any] = {}
- for key, val in obj.items():
- if key in {"assetId", "asset_id"} and isinstance(val, int):
- out[key] = asset_map.get(val, val)
- elif key in {"episodeId", "episode_id"} and isinstance(val, int):
- out[key] = episode_map.get(val, val)
- elif key in {"projectId", "project_id"} and isinstance(val, int):
- out[key] = project_map.get(val, val)
- elif key in {"id", "canvas_node_id"} and isinstance(val, str):
- matched = _ASSET_NODE.match(val)
- if matched:
- new_id = asset_map.get(int(matched.group(1)))
- out[key] = f"asset-{new_id}" if new_id else val
- else:
- out[key] = _rewrite_json(val, asset_map, episode_map, project_map)
- else:
- out[key] = _rewrite_json(val, asset_map, episode_map, project_map)
- return out
- if isinstance(obj, str):
-
- def _sub(match: re.Match[str]) -> str:
- old = int(match.group(1))
- return f"@asset:{asset_map.get(old, old)}"
-
- return _ASSET_MENTION.sub(_sub, obj)
- return obj
-
-
-async def _wipe_drama_tables(session: Any) -> None:
- # 清空漫剧表;用量记录只断开关联,不删账本
- await session.execute(
- text("UPDATE usage_events SET drama_project_id = NULL WHERE drama_project_id IS NOT NULL")
- )
- await session.execute(
- text(
- "TRUNCATE TABLE "
- + ", ".join(DRAMA_TABLES)
- + " RESTART IDENTITY CASCADE"
- )
- )
-
-
-async def _reset_id_sequences(session: Any) -> None:
- # 显式写入主键后,把 serial 拨到当前 MAX(id)
- for table in DRAMA_TABLES:
- await session.execute(
- text(
- f"SELECT setval(pg_get_serial_sequence('{table}', 'id'), "
- f"COALESCE((SELECT MAX(id) FROM {table}), 1))"
- )
- )
-
-
-async def import_one(
- source_sqlite: str,
- dry_run: bool,
- project_ids: list[int] | None,
- import_missing_users: bool,
- replace: bool,
-) -> None:
- con = sqlite3.connect(source_sqlite)
- con.row_factory = sqlite3.Row
- cur = con.cursor()
-
- cur.execute("select id as user_id, email from users")
- src_users = cur.fetchall()
- user_email_by_id = {int(r["user_id"]): r["email"] for r in src_users if r["email"]}
-
- cur.execute(
- "select id, user_id, title, description, content, params, created_at, updated_at "
- "from drama_projects order by id"
- )
- src_projects_all = cur.fetchall()
- src_projects = src_projects_all
- if project_ids:
- project_id_set = set(project_ids)
- src_projects = [r for r in src_projects_all if int(r["id"]) in project_id_set]
- if not src_projects:
- print("No drama_projects found in source sqlite.")
- return
-
- src_owner_emails = sorted({user_email_by_id.get(int(r["user_id"])) for r in src_projects})
- src_owner_emails = [e for e in src_owner_emails if e]
-
- async with AsyncSessionLocal() as session:
- dest_users = await session.execute(
- select(User).where(User.email.in_(src_owner_emails)) if src_owner_emails else select(User).where(False)
- )
- dest_users_list = dest_users.scalars().all()
- dest_user_id_by_email = {u.email: u.id for u in dest_users_list}
-
- print(f"[users] source owners: {src_owner_emails}")
- print(f"[users] destination found: {len(dest_user_id_by_email)}")
-
- missing_emails = [e for e in src_owner_emails if e not in dest_user_id_by_email]
- if missing_emails:
- print(f"[users] missing in destination: {missing_emails}")
- if import_missing_users and not dry_run:
- cur.execute(
- "select id, email, nickname, hashed_password, quota_left, balance_fen, frozen_fen, plan, billing_unlimited, role, created_at "
- "from users"
- )
- src_users_full = cur.fetchall()
- src_user_rows_by_email = {r["email"]: r for r in src_users_full if r["email"]}
-
- for email in missing_emails:
- row = src_user_rows_by_email.get(email)
- if not row:
- continue
- u = User(
- email=email,
- nickname=row["nickname"] or "创作者",
- hashed_password=row["hashed_password"] or "",
- quota_left=int(row["quota_left"] or 0),
- balance_fen=int(row["balance_fen"] or 0),
- frozen_fen=int(row["frozen_fen"] or 0),
- plan=row["plan"] or "free",
- billing_unlimited=bool(row["billing_unlimited"] or False),
- role=row["role"] or "user",
- created_at=_parse_dt(row["created_at"]),
- )
- session.add(u)
- await session.flush()
- dest_user_id_by_email[email] = int(u.id)
- print(f"[users] inserted missing users: {len(missing_emails)}")
- else:
- print("[users] import-missing-users disabled or dry-run; projects for these owners will be skipped.")
-
- project_id_map: dict[int, int] = {}
- asset_id_map: dict[int, int] = {}
- episode_id_map: dict[int, int] = {}
- fragment_id_map: dict[int, int] = {}
- preserve_ids = bool(replace)
-
- try:
- if replace:
- print("[replace] wipe all drama_* tables on destination")
- if not dry_run:
- await _wipe_drama_tables(session)
- await session.flush()
-
- inserted_projects = 0
- skipped_projects = 0
- pending_project_json: list[tuple[int, Any, Any]] = []
- for r in src_projects:
- old_pid = int(r["id"])
- old_uid = int(r["user_id"])
- email = user_email_by_id.get(old_uid)
- new_uid = dest_user_id_by_email.get(email or "")
- if new_uid is None:
- skipped_projects += 1
- print(f"[skip] project old_id={old_pid} owner_email={email!r} not found in destination users")
- continue
-
- if dry_run:
- project_id_map[old_pid] = old_pid if preserve_ids else -1
- inserted_projects += 1
- continue
-
- content = _jload(r["content"])
- params = _jload(r["params"])
- proj = DramaProject(
- user_id=new_uid,
- title=r["title"] or "未命名漫剧",
- description=r["description"],
- content=content,
- params=params,
- created_at=_parse_dt(r["created_at"]),
- updated_at=_parse_dt(r["updated_at"]),
- )
- if preserve_ids:
- proj.id = old_pid
- session.add(proj)
- await session.flush()
- project_id_map[old_pid] = int(proj.id)
- pending_project_json.append((int(proj.id), content, params))
- inserted_projects += 1
-
- print(f"[projects] inserted={inserted_projects} skipped={skipped_projects}")
-
- cur.execute(
- "select id, project_id, episode_id, name, source, summary, episode_content, params, created_at, updated_at "
- "from drama_scripts order by id"
- )
- src_scripts = cur.fetchall()
- inserted_scripts = 0
- pending_script_rows: list[tuple[DramaScript, Any, Any, Any]] = []
- for r in src_scripts:
- old_pid = int(r["project_id"])
- new_pid = project_id_map.get(old_pid)
- if new_pid is None:
- continue
- if dry_run:
- inserted_scripts += 1
- continue
-
- summary = _jload(r["summary"])
- episode_content = _jload(r["episode_content"])
- params = _jload(r["params"])
- scr = DramaScript(
- project_id=new_pid,
- episode_id=int(r["episode_id"]) if r["episode_id"] is not None else None,
- name=r["name"] or "剧本",
- source=r["source"],
- summary=summary,
- episode_content=episode_content,
- params=params,
- created_at=_parse_dt(r["created_at"]),
- updated_at=_parse_dt(r["updated_at"]),
- )
- if preserve_ids:
- scr.id = int(r["id"])
- session.add(scr)
- await session.flush()
- pending_script_rows.append((scr, summary, episode_content, params))
- inserted_scripts += 1
- print(f"[scripts] inserted={inserted_scripts}")
-
- cur.execute(
- "select id, project_id, name, params, created_at, updated_at "
- "from drama_episodes order by id"
- )
- src_episodes = cur.fetchall()
- pending_episode_json: list[tuple[DramaEpisode, Any]] = []
- for r in src_episodes:
- old_eid = int(r["id"])
- old_pid = int(r["project_id"])
- new_pid = project_id_map.get(old_pid)
- if new_pid is None:
- continue
-
- if dry_run:
- episode_id_map[old_eid] = old_eid if preserve_ids else -1
- continue
-
- params = _jload(r["params"])
- ep = DramaEpisode(
- project_id=new_pid,
- name=r["name"] or "",
- params=params,
- created_at=_parse_dt(r["created_at"]),
- updated_at=_parse_dt(r["updated_at"]),
- )
- if preserve_ids:
- ep.id = old_eid
- session.add(ep)
- await session.flush()
- episode_id_map[old_eid] = int(ep.id)
- pending_episode_json.append((ep, params))
-
- print(f"[episodes] mapped={len(episode_id_map)}")
-
- if not dry_run:
- for scr, _summary, _ec, _params in pending_script_rows:
- if scr.episode_id is not None:
- scr.episode_id = episode_id_map.get(int(scr.episode_id), scr.episode_id)
-
- cur.execute(
- "select id, project_id, type, asset_type, name, cover, url, params, derive_id, created_at, updated_at "
- "from drama_assets order by id"
- )
- src_assets = cur.fetchall()
- pending_assets: list[tuple[DramaAsset, Any]] = []
- for r in src_assets:
- old_aid = int(r["id"])
- old_pid = int(r["project_id"])
- new_pid = project_id_map.get(old_pid)
- if new_pid is None:
- continue
-
- if dry_run:
- asset_id_map[old_aid] = old_aid if preserve_ids else -1
- continue
-
- params = _jload(r["params"])
- asset = DramaAsset(
- project_id=new_pid,
- type=r["type"] or "none",
- asset_type=r["asset_type"] or "image",
- name=r["name"],
- cover=r["cover"],
- url=r["url"],
- params=params,
- derive_id=r["derive_id"],
- created_at=_parse_dt(r["created_at"]),
- updated_at=_parse_dt(r["updated_at"]),
- )
- if preserve_ids:
- asset.id = old_aid
- session.add(asset)
- await session.flush()
- asset_id_map[old_aid] = int(asset.id)
- pending_assets.append((asset, params))
-
- print(f"[assets] mapped={len(asset_id_map)}")
-
- cur.execute(
- "select id, episode_id, sort_order, content, cover, video, duration_sec, params, created_at, updated_at "
- "from drama_episode_fragments order by id"
- )
- src_fragments = cur.fetchall()
- pending_frags: list[tuple[DramaEpisodeFragment, Any]] = []
- for r in src_fragments:
- old_fid = int(r["id"])
- old_eid = int(r["episode_id"])
- new_eid = episode_id_map.get(old_eid)
- if new_eid is None:
- continue
-
- if dry_run:
- fragment_id_map[old_fid] = old_fid if preserve_ids else -1
- continue
-
- params = _jload(r["params"])
- frag = DramaEpisodeFragment(
- episode_id=new_eid,
- sort_order=int(r["sort_order"] or 0),
- content=r["content"] or "",
- cover=r["cover"] or "",
- video=r["video"] or "",
- duration_sec=r["duration_sec"],
- params=params,
- created_at=_parse_dt(r["created_at"]),
- updated_at=_parse_dt(r["updated_at"]),
- )
- if preserve_ids:
- frag.id = old_fid
- session.add(frag)
- await session.flush()
- fragment_id_map[old_fid] = int(frag.id)
- pending_frags.append((frag, params))
-
- print(f"[fragments] mapped={len(fragment_id_map)}")
-
- if not dry_run:
- for pid, content, params in pending_project_json:
- proj = await session.get(DramaProject, pid)
- if proj is None:
- continue
- proj.content = _rewrite_json(content, asset_id_map, episode_id_map, project_id_map)
- proj.params = _rewrite_json(params, asset_id_map, episode_id_map, project_id_map)
- for scr, summary, episode_content, params in pending_script_rows:
- scr.summary = _rewrite_json(summary, asset_id_map, episode_id_map, project_id_map)
- scr.episode_content = _rewrite_json(
- episode_content, asset_id_map, episode_id_map, project_id_map
- )
- scr.params = _rewrite_json(params, asset_id_map, episode_id_map, project_id_map)
- for ep, params in pending_episode_json:
- ep.params = _rewrite_json(params, asset_id_map, episode_id_map, project_id_map)
- for asset, params in pending_assets:
- asset.params = _rewrite_json(params, asset_id_map, episode_id_map, project_id_map)
- for frag, params in pending_frags:
- frag.params = _rewrite_json(params, asset_id_map, episode_id_map, project_id_map)
-
- cur.execute("select id, asset_id, episode_id, created_at from drama_asset_episodes order by id")
- src_asset_episodes = cur.fetchall()
- inserted_asset_episodes = 0
- for r in src_asset_episodes:
- old_aid = int(r["asset_id"])
- old_eid = int(r["episode_id"])
- new_aid = asset_id_map.get(old_aid)
- new_eid = episode_id_map.get(old_eid)
- if new_aid is None or new_eid is None:
- continue
- if dry_run:
- inserted_asset_episodes += 1
- continue
- row = DramaAssetEpisode(
- asset_id=new_aid,
- episode_id=new_eid,
- created_at=_parse_dt(r["created_at"]),
- )
- if preserve_ids:
- row.id = int(r["id"])
- session.add(row)
- inserted_asset_episodes += 1
- print(f"[drama_asset_episodes] inserted={inserted_asset_episodes}")
-
- cur.execute("select id, fragment_id, asset_id from drama_fragment_asset_refs order by id")
- src_frag_refs = cur.fetchall()
- inserted_frag_refs = 0
- for r in src_frag_refs:
- old_fid = int(r["fragment_id"])
- old_aid = int(r["asset_id"])
- new_fid = fragment_id_map.get(old_fid)
- new_aid = asset_id_map.get(old_aid)
- if new_fid is None or new_aid is None:
- continue
- if dry_run:
- inserted_frag_refs += 1
- continue
- row = DramaFragmentAssetRef(fragment_id=new_fid, asset_id=new_aid)
- if preserve_ids:
- row.id = int(r["id"])
- session.add(row)
- inserted_frag_refs += 1
- print(f"[drama_fragment_asset_refs] inserted={inserted_frag_refs}")
-
- if not dry_run:
- await session.flush()
- await _reset_id_sequences(session)
- await session.commit()
- print("Import done.")
- except Exception:
- if not dry_run:
- await session.rollback()
- raise
-
- con.close()
-
-
-def _parse_args() -> argparse.Namespace:
- p = argparse.ArgumentParser()
- p.add_argument("--source-sqlite", required=True, help="Path to source sqlite file (drama data).")
- p.add_argument("--dry-run", action="store_true", help="Only calculate mapping, do not insert.")
- p.add_argument(
- "--project-ids",
- default="",
- help="仅导入指定 drama_projects 的 id(逗号分隔),例如:--project-ids 7,8",
- )
- p.add_argument(
- "--import-missing-users",
- action="store_true",
- help="目标库 users 表中缺失的 owner email:从源 sqlite 插入(会同步 hashed_password)",
- )
- p.add_argument(
- "--replace",
- action="store_true",
- help="先清空目标 drama_* 表,再按源主键原样写入(含画布节点 assetId)",
- )
- return p.parse_args()
-
-
-def main() -> None:
- args = _parse_args()
- project_ids = None
- if args.project_ids:
- project_ids = [int(x.strip()) for x in args.project_ids.split(",") if x.strip()]
- asyncio.run(
- import_one(
- source_sqlite=args.source_sqlite,
- dry_run=bool(args.dry_run),
- project_ids=project_ids,
- import_missing_users=bool(args.import_missing_users),
- replace=bool(args.replace),
- )
- )
-
-
-if __name__ == "__main__":
- main()
diff --git a/docs/BILLING.md b/docs/BILLING.md
index f0118c3..b7700ba 100644
--- a/docs/BILLING.md
+++ b/docs/BILLING.md
@@ -24,6 +24,10 @@ charge_fen = ceil(tokens / 1e6 * provider_yuan_per_m * markup * 100)
| seedream | 8(按次折合约;有 usage 则用 usage) |
| tts | 2(按次估价) |
+Seedance 视频任务成功后,优先读取官方「查询视频生成任务」响应中的 `usage.total_tokens` 写入 `usage_events`(`estimated=false`);仅在上游未返回 usage 时回退到时长估算。
+
+管理端「官方用量对照」需配置 `VOLC_ACCESS_KEY_ID` / `VOLC_SECRET_ACCESS_KEY`,通过方舟管控面 `GetInferenceUsage` 拉取账号日用量并与本地 seedance 成本对照。
+
## TaskRun 计费流程
每个 `TaskRun` 独立走「预扣 → 记录用量 → 结算」:
@@ -134,12 +138,15 @@ EPAY_RETURN_URL=https://your-site.example.com/pricing?paid=1
| POST | `/api/billing/epay/notify` | 易支付回调 |
| GET | `/api/admin/usage-events` | 管理端用量明细分页 |
| GET | `/api/admin/tasks/{id}` | 任务详情含 `usage_lines` 与计费字段 |
+| GET | `/api/admin/stats/upstream-usage` | 近 N 日官方/本地 seedance 成本对照 |
+| POST | `/api/admin/stats/upstream-usage/sync` | 手动刷新官方用量快照 |
## 管理端
- **订单与流水** → 「用量明细」Tab:按用户/任务/领域筛选 `usage_events`。
- **任务队列** → 列表「费用」列显示 `billing_charged_fen`(冻结中显示预扣)。
- **任务详情** → 「计费」Tab:预扣/实扣/退回 + 用量行列表。
+- **仪表盘** → 「Seedance 官方用量对照」:本地成本 vs 方舟 `GetInferenceUsage`(需 `VOLC_ACCESS_KEY_ID` / `VOLC_SECRET_ACCESS_KEY`)。
## 验收清单
@@ -147,5 +154,7 @@ EPAY_RETURN_URL=https://your-site.example.com/pricing?paid=1
2. 漫剧分镜视频/资产生成:有 `task_run_id` 的用量行,任务结束扣费。
3. 漫剧聊天 / 选题扩写 / Skill 优化 / 音色描述 / 开放 API / 工作室工具:响应含 `task_id`(轻量 TaskRun),余额变化正确。
4. 管理端可按 `task_run_id` 或 `billing_key=llm_chat` 查到每条 LLM/图/视频/TTS 费用。
+5. Seedance 视频成功后 `usage_events.estimated=false` 且 `total_tokens` 与官方任务查询一致。
+6. 配置火山 AK/SK 后,管理端可刷新并查看近 30 日官方/本地成本对照。
Demo 账号可设 `billing_unlimited=true` 跳过扣费。
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 6b11ed1..ace8f83 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,5 +1,6 @@
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
import DialogHost from './components/ui/DialogHost'
+import BillingAlertHost from './components/billing/BillingAlertHost'
import { DramaGenQueuePanel } from './components/drama/DramaGenQueuePanel'
import AuthPage from './pages/AuthPage'
import HistoryPage from './pages/HistoryPage'
@@ -62,6 +63,7 @@ export default function App() {
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
<DramaGenQueuePanel />
+ <BillingAlertHost />
<DialogHost />
</BrowserRouter>
)
diff --git a/frontend/src/api.ts b/frontend/src/api.ts
index d05512a..1ad4132 100644
--- a/frontend/src/api.ts
+++ b/frontend/src/api.ts
@@ -556,6 +556,22 @@ export const api = {
`/api/billing/usage/events?page=${page}&page_size=${pageSize}`,
)
},
+ billingAlertsPending() {
+ return request<{
+ items: Array<{
+ id: number
+ kind: string
+ title: string
+ message: string
+ milestone_fen: number
+ milestone_yuan: number
+ created_at?: string | null
+ }>
+ }>('/api/billing/alerts/pending')
+ },
+ billingAlertAck(alertId: number) {
+ return request<{ ok: boolean }>(`/api/billing/alerts/${alertId}/ack`, { method: 'POST' })
+ },
billingPreflight(params: { domain: string; task_type: string; count?: number }) {
const q = new URLSearchParams({
domain: params.domain,
diff --git a/frontend/src/components/billing/BillingAlertHost.tsx b/frontend/src/components/billing/BillingAlertHost.tsx
new file mode 100644
index 0000000..445dcdc
--- /dev/null
+++ b/frontend/src/components/billing/BillingAlertHost.tsx
@@ -0,0 +1,53 @@
+import { useCallback, useEffect, useRef } from 'react'
+import { api } from '../api'
+import { dialog } from '../lib/dialog'
+
+type BillingAlertItem = {
+ id: number
+ kind: string
+ title: string
+ message: string
+ milestone_fen: number
+ milestone_yuan: number
+ created_at?: string | null
+}
+
+/** 轮询待展示的用户额度告警并弹窗提示。 */
+export default function BillingAlertHost() {
+ const showingRef = useRef(false)
+
+ const checkAlerts = useCallback(async () => {
+ if (!localStorage.getItem('token') || showingRef.current) return
+ try {
+ const res = await api.billingAlertsPending()
+ const items = (res.items ?? []) as BillingAlertItem[]
+ if (!items.length) return
+ showingRef.current = true
+ for (const item of items) {
+ await dialog.alert({
+ title: item.title || '消费提醒',
+ message: item.message,
+ confirmText: '知道了',
+ })
+ await api.billingAlertAck(item.id)
+ }
+ } catch {
+ // 未登录或网络异常时静默跳过
+ } finally {
+ showingRef.current = false
+ }
+ }, [])
+
+ useEffect(() => {
+ void checkAlerts()
+ const timer = window.setInterval(() => void checkAlerts(), 30_000)
+ const onFocus = () => void checkAlerts()
+ window.addEventListener('focus', onFocus)
+ return () => {
+ window.clearInterval(timer)
+ window.removeEventListener('focus', onFocus)
+ }
+ }, [checkAlerts])
+
+ return null
+}