Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7120d4b5ea | |||
| b45fcabbf3 | |||
| 363f9169ba | |||
| d0183cb636 | |||
| eca1aa635e | |||
| f8317e8312 | |||
| a4d46f2b1e | |||
| 4c33f210da |
@@ -19,3 +19,16 @@ bash scripts/check-release-ready.sh
|
|||||||
- `memind_adm` 可以独立开发,但共享用户、权限、策略、技能、计费体系必须继续复用 `Memind` 主实现。
|
- `memind_adm` 可以独立开发,但共享用户、权限、策略、技能、计费体系必须继续复用 `Memind` 主实现。
|
||||||
- 发版须 Git commit,禁止本机直 `rsync` 到 `103/105`。
|
- 发版须 Git commit,禁止本机直 `rsync` 到 `103/105`。
|
||||||
- 共享用户、计费、空间额度、策略同步相关改动必须保留业务验收记录。
|
- 共享用户、计费、空间额度、策略同步相关改动必须保留业务验收记录。
|
||||||
|
|
||||||
|
## 必读:本仓库是唯一合法的管理后台 UI(5174)
|
||||||
|
|
||||||
|
**所有平台管理后台的前端功能只能在本仓库(memind_adm)开发,本地端口 5174,生产 gadm。禁止在 Memind 仓库的 `ops/`(约 3002)新增任何管理页面、导航或 API 客户端。**
|
||||||
|
|
||||||
|
| 组件 | 端口 | 职责 |
|
||||||
|
|------|------|------|
|
||||||
|
| **memind_adm 前端(本仓库 `src/`)** | **5174** | 管理后台 UI:用户、计费、图片额度、策略、模型中心等 |
|
||||||
|
| memind_adm API(`server/`) | 8085 | 挂载 `/admin-api/*`,复用 Memind 共享模块 |
|
||||||
|
| Memind `ops/` | ~3002 | Plaza 运营 + 遗留 admin;**只读维护,禁止扩展** |
|
||||||
|
| Memind 后端 | 8081 / 8082 | 业务逻辑与 Portal;UI 不在此仓库 |
|
||||||
|
|
||||||
|
新增管理功能时:在本仓库添加 `src/admin/pages/*`、更新 `AdminNav.tsx` 与 `App.tsx`;若需新 API,在 `server/app.mjs` 挂载并复用 Memind 模块。Memind 侧仅实现共享业务,不在 `ops/` 做 UI。
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Local smoke test for image-quota admin API (memind_adm 8085).
|
||||||
|
* Usage: node scripts/verify-image-quota-local.mjs
|
||||||
|
*/
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const base = process.env.ADM_DEV_BACKEND ?? 'http://127.0.0.1:8085';
|
||||||
|
|
||||||
|
function loadEnvFile(filePath) {
|
||||||
|
if (!fs.existsSync(filePath)) return;
|
||||||
|
for (const line of fs.readFileSync(filePath, 'utf8').split('\n')) {
|
||||||
|
const trimmed = line.trim();
|
||||||
|
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||||
|
const eq = trimmed.indexOf('=');
|
||||||
|
if (eq <= 0) continue;
|
||||||
|
const key = trimmed.slice(0, eq).trim();
|
||||||
|
let value = trimmed.slice(eq + 1).trim();
|
||||||
|
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||||
|
value = value.slice(1, -1);
|
||||||
|
}
|
||||||
|
if (!(key in process.env)) process.env[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadEnvFile(path.join(root, '.env'));
|
||||||
|
|
||||||
|
const username = process.env.H5_ADMIN_USERNAME?.trim() || 'admin';
|
||||||
|
const password = process.env.H5_ADMIN_PASSWORD?.trim() || process.env.ADMIN_PASSWORD?.trim() || '';
|
||||||
|
|
||||||
|
async function request(method, urlPath, { body, cookie } = {}) {
|
||||||
|
const res = await fetch(`${base}${urlPath}`, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||||
|
...(cookie ? { Cookie: cookie } : {}),
|
||||||
|
},
|
||||||
|
body: body ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
const text = await res.text();
|
||||||
|
let json = null;
|
||||||
|
try {
|
||||||
|
json = text ? JSON.parse(text) : null;
|
||||||
|
} catch {
|
||||||
|
json = { raw: text.slice(0, 200) };
|
||||||
|
}
|
||||||
|
return { status: res.status, json, setCookie: res.headers.getSetCookie?.() ?? [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
function cookieFromSetCookie(setCookie) {
|
||||||
|
return setCookie.map((c) => c.split(';')[0]).join('; ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertOk(cond, msg) {
|
||||||
|
if (!cond) throw new Error(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log(`==> Admin API base: ${base}`);
|
||||||
|
|
||||||
|
if (!password) {
|
||||||
|
console.error('缺少 H5_ADMIN_PASSWORD(请在 memind_adm/.env 配置)');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const login = await request('POST', '/auth/login', {
|
||||||
|
body: { username, password },
|
||||||
|
});
|
||||||
|
assertOk(login.status === 200, `登录失败 HTTP ${login.status}: ${JSON.stringify(login.json)}`);
|
||||||
|
const cookie = cookieFromSetCookie(login.setCookie);
|
||||||
|
assertOk(cookie, '登录未返回 session cookie');
|
||||||
|
console.log(`✓ 管理员登录 (${username})`);
|
||||||
|
|
||||||
|
const config = await request('GET', '/admin-api/image-quota/config', { cookie });
|
||||||
|
assertOk(config.status === 200, `config HTTP ${config.status}`);
|
||||||
|
assertOk(Array.isArray(config.json?.plans), 'config.plans 应为数组');
|
||||||
|
assertOk(config.json.plans.length > 0, 'config.plans 不应为空');
|
||||||
|
console.log(`✓ GET /admin-api/image-quota/config (${config.json.plans.length} 套餐)`);
|
||||||
|
|
||||||
|
const users = await request('GET', '/admin-api/users?page=1&pageSize=5&role=user', { cookie });
|
||||||
|
assertOk(users.status === 200, `users HTTP ${users.status}`);
|
||||||
|
const sampleUser = users.json?.users?.[0];
|
||||||
|
assertOk(sampleUser?.id, '需要至少一个 user 账号做用户级测试');
|
||||||
|
console.log(`✓ 样本用户: ${sampleUser.username} (${sampleUser.id})`);
|
||||||
|
|
||||||
|
const userQuota = await request('GET', `/admin-api/users/${sampleUser.id}/image-quota`, { cookie });
|
||||||
|
assertOk(userQuota.status === 200, `user image-quota HTTP ${userQuota.status}`);
|
||||||
|
assertOk(userQuota.json?.quota, '应返回 quota 对象');
|
||||||
|
console.log(
|
||||||
|
`✓ GET user image-quota: remaining=${userQuota.json.quota.remaining ?? '∞'} unlimited=${userQuota.json.quota.unlimited}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const ledger = await request('GET', '/admin-api/image-quota/ledger?page=1&pageSize=5', { cookie });
|
||||||
|
assertOk(ledger.status === 200, `ledger HTTP ${ledger.status}`);
|
||||||
|
assertOk(Array.isArray(ledger.json?.entries), 'ledger.entries 应为数组');
|
||||||
|
console.log(`✓ GET /admin-api/image-quota/ledger (${ledger.json.total} 条)`);
|
||||||
|
|
||||||
|
const grant = await request('POST', `/admin-api/users/${sampleUser.id}/image-quota/grant`, {
|
||||||
|
cookie,
|
||||||
|
body: { delta: 1, note: 'local-verify-image-quota' },
|
||||||
|
});
|
||||||
|
assertOk(grant.status === 200, `grant HTTP ${grant.status}: ${JSON.stringify(grant.json)}`);
|
||||||
|
assertOk(grant.json?.quota, 'grant 应返回更新后的 quota');
|
||||||
|
console.log(`✓ POST grant +1 → remaining=${grant.json.quota.remaining ?? '∞'}`);
|
||||||
|
|
||||||
|
const revoke = await request('POST', `/admin-api/users/${sampleUser.id}/image-quota/grant`, {
|
||||||
|
cookie,
|
||||||
|
body: { delta: -1, note: 'local-verify-image-quota-rollback' },
|
||||||
|
});
|
||||||
|
assertOk(revoke.status === 200, `rollback grant HTTP ${revoke.status}`);
|
||||||
|
console.log('✓ POST grant -1 回滚测试额度');
|
||||||
|
|
||||||
|
console.log('\n全部 image-quota Admin API 联调通过。');
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error('\n联调失败:', err.message);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/** Portal smoke: /auth/me subscription includes image quota fields */
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const memindRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), '../..', 'Memind');
|
||||||
|
const portalBase = process.env.PORTAL_BASE ?? 'http://127.0.0.1:8081';
|
||||||
|
|
||||||
|
function loadEnvFile(filePath) {
|
||||||
|
if (!fs.existsSync(filePath)) return;
|
||||||
|
for (const line of fs.readFileSync(filePath, 'utf8').split('\n')) {
|
||||||
|
const trimmed = line.trim();
|
||||||
|
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||||
|
const eq = trimmed.indexOf('=');
|
||||||
|
if (eq <= 0) continue;
|
||||||
|
const key = trimmed.slice(0, eq).trim();
|
||||||
|
let value = trimmed.slice(eq + 1).trim();
|
||||||
|
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||||
|
value = value.slice(1, -1);
|
||||||
|
}
|
||||||
|
if (!(key in process.env)) process.env[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadEnvFile(path.join(memindRoot, '.env'));
|
||||||
|
|
||||||
|
const username = process.env.H5_TEST_USERNAME?.trim() || process.env.H5_ADMIN_USERNAME?.trim() || 'admin';
|
||||||
|
const password = process.env.H5_TEST_PASSWORD?.trim() || process.env.H5_ADMIN_PASSWORD?.trim() || '';
|
||||||
|
|
||||||
|
async function request(method, urlPath, { body, cookie } = {}) {
|
||||||
|
const res = await fetch(`${portalBase}${urlPath}`, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||||
|
...(cookie ? { Cookie: cookie } : {}),
|
||||||
|
},
|
||||||
|
body: body ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
const text = await res.text();
|
||||||
|
let json = null;
|
||||||
|
try { json = text ? JSON.parse(text) : null; } catch { json = { raw: text.slice(0, 200) }; }
|
||||||
|
return { status: res.status, json, setCookie: res.headers.getSetCookie?.() ?? [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
function cookieFromSetCookie(setCookie) {
|
||||||
|
return setCookie.map((c) => c.split(';')[0]).join('; ');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log(`==> Portal base: ${portalBase}`);
|
||||||
|
if (!password) {
|
||||||
|
console.error('缺少登录密码(Memind/.env 中 H5_ADMIN_PASSWORD 或 H5_TEST_PASSWORD)');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const login = await request('POST', '/auth/login', { body: { username, password } });
|
||||||
|
if (login.status !== 200) {
|
||||||
|
console.error(`登录失败 HTTP ${login.status}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const cookie = cookieFromSetCookie(login.setCookie);
|
||||||
|
console.log(`✓ Portal 登录 (${username})`);
|
||||||
|
|
||||||
|
const me = await request('GET', '/auth/me', { cookie });
|
||||||
|
if (me.status !== 200) {
|
||||||
|
console.error(`/auth/me HTTP ${me.status}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const sub = me.json?.user?.subscription;
|
||||||
|
if (!sub) {
|
||||||
|
console.log('⚠ 当前用户无 active subscription(免费用户可能无订阅记录)');
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const fields = ['periodImagesLimit', 'periodImagesUsed', 'periodImagesBonus'];
|
||||||
|
for (const f of fields) {
|
||||||
|
if (!(f in sub)) {
|
||||||
|
console.error(`subscription 缺少字段: ${f}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
`✓ /auth/me subscription 图片额度: limit=${sub.periodImagesLimit} bonus=${sub.periodImagesBonus ?? 0} used=${sub.periodImagesUsed}`,
|
||||||
|
);
|
||||||
|
console.log('\nPortal 用户侧 subscription 字段联调通过。');
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error('联调失败:', err.message);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
+134
@@ -104,6 +104,7 @@ export function createAdminApp(services) {
|
|||||||
orchestratorObservabilityService,
|
orchestratorObservabilityService,
|
||||||
personalMemoryCandidateStore,
|
personalMemoryCandidateStore,
|
||||||
skillRuntimeConfigService,
|
skillRuntimeConfigService,
|
||||||
|
billingConfigService,
|
||||||
wechatScheduleLlmConfigService,
|
wechatScheduleLlmConfigService,
|
||||||
adminSystemTestService,
|
adminSystemTestService,
|
||||||
systemTestAccountService,
|
systemTestAccountService,
|
||||||
@@ -628,6 +629,40 @@ export function createAdminApp(services) {
|
|||||||
res.json(await skillRuntimeConfigService.getPublicRuntimeConfig());
|
res.json(await skillRuntimeConfigService.getPublicRuntimeConfig());
|
||||||
});
|
});
|
||||||
|
|
||||||
|
adminApi.get('/billing/config', requireAdmin, async (_req, res) => {
|
||||||
|
if (!billingConfigService?.getAdminConfig) {
|
||||||
|
return res.status(503).json({ message: '计费公式配置服务未启用' });
|
||||||
|
}
|
||||||
|
return res.json(await billingConfigService.getAdminConfig());
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateBillingConfig = async (req, res) => {
|
||||||
|
if (!billingConfigService?.updateAdminConfig) {
|
||||||
|
return res.status(503).json({ message: '计费公式配置服务未启用' });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return res.json(await billingConfigService.updateAdminConfig(
|
||||||
|
req.body?.config ?? req.body ?? {},
|
||||||
|
{ updatedBy: req.currentUser.id },
|
||||||
|
));
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === 'BILLING_CONFIG_ENV_LOCKED') {
|
||||||
|
return res.status(409).json({ message: error.message, code: error.code });
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
adminApi.put('/billing/config', requireAdmin, updateBillingConfig);
|
||||||
|
adminApi.patch('/billing/config', requireAdmin, updateBillingConfig);
|
||||||
|
|
||||||
|
adminApi.get('/billing/runtime', requireAdmin, async (_req, res) => {
|
||||||
|
if (!billingConfigService?.getRuntimeState) {
|
||||||
|
return res.status(503).json({ message: '计费公式配置服务未启用' });
|
||||||
|
}
|
||||||
|
return res.json(await billingConfigService.getRuntimeState());
|
||||||
|
});
|
||||||
|
|
||||||
adminApi.get('/system-tests/accounts', requireAdmin, async (_req, res) => {
|
adminApi.get('/system-tests/accounts', requireAdmin, async (_req, res) => {
|
||||||
if (!systemTestAccountService) {
|
if (!systemTestAccountService) {
|
||||||
return res.status(503).json({ message: '系统测试账号服务未启用' });
|
return res.status(503).json({ message: '系统测试账号服务未启用' });
|
||||||
@@ -1183,6 +1218,105 @@ export function createAdminApp(services) {
|
|||||||
res.json(result);
|
res.json(result);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── Image generation quota ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
adminApi.get('/image-quota/config', requireAdmin, async (_req, res) => {
|
||||||
|
const catalogService = subscriptionService?._planCatalogService ?? planCatalogService;
|
||||||
|
if (!catalogService?.listPlans) {
|
||||||
|
return res.status(503).json({ message: '套餐目录服务未启用' });
|
||||||
|
}
|
||||||
|
const plans = await catalogService.listPlans();
|
||||||
|
res.json({ plans });
|
||||||
|
});
|
||||||
|
|
||||||
|
adminApi.patch('/image-quota/config/:planType', requireAdmin, async (req, res) => {
|
||||||
|
const catalogService = subscriptionService?._planCatalogService ?? planCatalogService;
|
||||||
|
if (!catalogService?.upsertPlan) {
|
||||||
|
return res.status(503).json({ message: '套餐目录服务未启用' });
|
||||||
|
}
|
||||||
|
const periodImages = Number(req.body?.periodImages);
|
||||||
|
if (!Number.isFinite(periodImages) || periodImages < 0) {
|
||||||
|
return res.status(400).json({ message: 'periodImages 必须是非负整数;0 表示无限' });
|
||||||
|
}
|
||||||
|
const current = await catalogService.getPlan(req.params.planType);
|
||||||
|
if (!current) return res.status(404).json({ message: '套餐不存在' });
|
||||||
|
const result = await catalogService.upsertPlan(req.params.planType, {
|
||||||
|
...current,
|
||||||
|
periodImages: Math.floor(periodImages),
|
||||||
|
});
|
||||||
|
if (!result.ok) return res.status(400).json({ message: result.message });
|
||||||
|
res.json(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
adminApi.get('/users/:userId/image-quota', requireAdmin, async (req, res) => {
|
||||||
|
if (!subscriptionService?.getImageQuota) {
|
||||||
|
return res.status(503).json({ message: '图片额度服务未启用' });
|
||||||
|
}
|
||||||
|
const quotaResult = await subscriptionService.getImageQuota(req.params.userId);
|
||||||
|
if (!quotaResult.ok) return res.status(404).json({ message: quotaResult.message });
|
||||||
|
const ledger = subscriptionService.listImageQuotaLedger
|
||||||
|
? await subscriptionService.listImageQuotaLedger({
|
||||||
|
userId: req.params.userId,
|
||||||
|
page: 1,
|
||||||
|
pageSize: 20,
|
||||||
|
})
|
||||||
|
: { entries: [] };
|
||||||
|
res.json({
|
||||||
|
subscription: quotaResult.subscription,
|
||||||
|
quota: quotaResult.quota,
|
||||||
|
ledger: ledger.entries,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
adminApi.put('/users/:userId/image-quota', requireAdmin, async (req, res) => {
|
||||||
|
if (!subscriptionService?.setImageQuota) {
|
||||||
|
return res.status(503).json({ message: '图片额度服务未启用' });
|
||||||
|
}
|
||||||
|
const remaining = req.body?.remaining;
|
||||||
|
const total = req.body?.total;
|
||||||
|
const note = String(req.body?.note ?? '').trim();
|
||||||
|
const result = await subscriptionService.setImageQuota(
|
||||||
|
req.params.userId,
|
||||||
|
{
|
||||||
|
remaining: remaining === undefined || remaining === null ? null : Math.floor(Number(remaining)),
|
||||||
|
total: total === undefined || total === null ? null : Math.floor(Number(total)),
|
||||||
|
},
|
||||||
|
{ operatorId: req.currentUser.id, note },
|
||||||
|
);
|
||||||
|
if (!result.ok) return res.status(400).json({ message: result.message });
|
||||||
|
res.json(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
adminApi.post('/users/:userId/image-quota/grant', requireAdmin, async (req, res) => {
|
||||||
|
if (!subscriptionService?.grantImageQuota) {
|
||||||
|
return res.status(503).json({ message: '图片额度服务未启用' });
|
||||||
|
}
|
||||||
|
const delta = Number(req.body?.delta);
|
||||||
|
if (!Number.isFinite(delta) || delta === 0) {
|
||||||
|
return res.status(400).json({ message: 'delta 必须是非零整数' });
|
||||||
|
}
|
||||||
|
const note = String(req.body?.note ?? '').trim();
|
||||||
|
const result = await subscriptionService.grantImageQuota(
|
||||||
|
req.params.userId,
|
||||||
|
Math.floor(delta),
|
||||||
|
{ operatorId: req.currentUser.id, note },
|
||||||
|
);
|
||||||
|
if (!result.ok) return res.status(400).json({ message: result.message });
|
||||||
|
res.json(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
adminApi.get('/image-quota/ledger', requireAdmin, async (req, res) => {
|
||||||
|
if (!subscriptionService?.listImageQuotaLedger) {
|
||||||
|
return res.status(503).json({ message: '图片额度服务未启用' });
|
||||||
|
}
|
||||||
|
const result = await subscriptionService.listImageQuotaLedger({
|
||||||
|
userId: req.query.userId ? String(req.query.userId) : null,
|
||||||
|
page: req.query.page,
|
||||||
|
pageSize: req.query.pageSize,
|
||||||
|
});
|
||||||
|
res.json(result);
|
||||||
|
});
|
||||||
|
|
||||||
app.use('/admin-api', adminApi);
|
app.use('/admin-api', adminApi);
|
||||||
|
|
||||||
if (services.createOpsApi) {
|
if (services.createOpsApi) {
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { once } from 'node:events';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { createAdminApp } from './app.mjs';
|
||||||
|
|
||||||
|
function createServices({ role = 'admin' } = {}) {
|
||||||
|
let stored = {
|
||||||
|
useBackendCost: true,
|
||||||
|
usdCnyRate: 7.2,
|
||||||
|
marginMultiplier: 1.2,
|
||||||
|
inputCentsPer1k: 2,
|
||||||
|
outputCentsPer1k: 6,
|
||||||
|
minBillCents: 1,
|
||||||
|
costEstimateFromTokens: true,
|
||||||
|
costEstimateInputUsdPer1M: 0.27,
|
||||||
|
costEstimateOutputUsdPer1M: 1.1,
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
services: {
|
||||||
|
ready: Promise.resolve(),
|
||||||
|
parseCookies: () => ({ test_session: 'token' }),
|
||||||
|
USER_COOKIE: 'test_session',
|
||||||
|
userLoginCookies: () => [],
|
||||||
|
clearUserSessionCookie: () => {},
|
||||||
|
resolveCookieDomainForRequest: () => undefined,
|
||||||
|
userAuth: {
|
||||||
|
getMe: async () => ({ id: 'admin-id', username: 'admin', role }),
|
||||||
|
},
|
||||||
|
billingConfigService: {
|
||||||
|
getAdminConfig: async () => ({
|
||||||
|
config: stored,
|
||||||
|
source: 'env',
|
||||||
|
updatedAt: null,
|
||||||
|
updatedBy: null,
|
||||||
|
formula: '最终扣费 = 上游成本(USD) × 汇率 × 毛利倍数',
|
||||||
|
}),
|
||||||
|
updateAdminConfig: async (patch, context) => {
|
||||||
|
stored = { ...stored, ...(patch.config ?? patch) };
|
||||||
|
return {
|
||||||
|
config: stored,
|
||||||
|
source: 'admin-db',
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
updatedBy: context?.updatedBy ?? null,
|
||||||
|
formula: '最终扣费 = 上游成本(USD) × 汇率 × 毛利倍数',
|
||||||
|
};
|
||||||
|
},
|
||||||
|
getRuntimeState: async () => ({
|
||||||
|
source: 'admin-db',
|
||||||
|
config: stored,
|
||||||
|
compute: stored,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startApp(options) {
|
||||||
|
const harness = createServices(options);
|
||||||
|
const server = createAdminApp(harness.services).listen(0, '127.0.0.1');
|
||||||
|
await once(server, 'listening');
|
||||||
|
const address = server.address();
|
||||||
|
assert.ok(address && typeof address === 'object');
|
||||||
|
return {
|
||||||
|
...harness,
|
||||||
|
request: (path, init = {}) => fetch(`http://127.0.0.1:${address.port}${path}`, {
|
||||||
|
...init,
|
||||||
|
headers: {
|
||||||
|
Cookie: 'test_session=token',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...init.headers,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
async close() {
|
||||||
|
server.close();
|
||||||
|
await once(server, 'close');
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('admin can read and update billing formula config', async (t) => {
|
||||||
|
const app = await startApp();
|
||||||
|
t.after(() => app.close());
|
||||||
|
|
||||||
|
const read = await app.request('/admin-api/billing/config');
|
||||||
|
assert.equal(read.status, 200);
|
||||||
|
const body = await read.json();
|
||||||
|
assert.equal(body.config.marginMultiplier, 1.2);
|
||||||
|
|
||||||
|
const update = await app.request('/admin-api/billing/config', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({
|
||||||
|
config: {
|
||||||
|
...body.config,
|
||||||
|
marginMultiplier: 1.5,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(update.status, 200);
|
||||||
|
const updated = await update.json();
|
||||||
|
assert.equal(updated.config.marginMultiplier, 1.5);
|
||||||
|
assert.equal(updated.source, 'admin-db');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ordinary users cannot access billing formula config', async (t) => {
|
||||||
|
const app = await startApp({ role: 'user' });
|
||||||
|
t.after(() => app.close());
|
||||||
|
|
||||||
|
const read = await app.request('/admin-api/billing/config');
|
||||||
|
assert.equal(read.status, 403);
|
||||||
|
});
|
||||||
@@ -39,6 +39,7 @@ export async function bootstrapAdminServices() {
|
|||||||
);
|
);
|
||||||
const { createPersonalMemoryCandidateStore } = await importMemind('memory-v2-personal-store.mjs');
|
const { createPersonalMemoryCandidateStore } = await importMemind('memory-v2-personal-store.mjs');
|
||||||
const { createSkillRuntimeAdminConfigService } = await importMemind('skill-runtime-admin-config.mjs');
|
const { createSkillRuntimeAdminConfigService } = await importMemind('skill-runtime-admin-config.mjs');
|
||||||
|
const { createBillingAdminConfigService } = await importMemind('billing-admin-config.mjs');
|
||||||
const { createAssetGatewayConfigService } = await importMemind('asset-gateway.mjs');
|
const { createAssetGatewayConfigService } = await importMemind('asset-gateway.mjs');
|
||||||
const { ensureAssetGatewaySchema } = await importMemind('db.mjs');
|
const { ensureAssetGatewaySchema } = await importMemind('db.mjs');
|
||||||
const { createWechatScheduleLlmConfigService } = await importMemind('wechat-schedule-llm-config.mjs');
|
const { createWechatScheduleLlmConfigService } = await importMemind('wechat-schedule-llm-config.mjs');
|
||||||
@@ -118,6 +119,10 @@ export async function bootstrapAdminServices() {
|
|||||||
env: process.env,
|
env: process.env,
|
||||||
h5Root,
|
h5Root,
|
||||||
});
|
});
|
||||||
|
const billingConfigService = createBillingAdminConfigService(pool, {
|
||||||
|
env: process.env,
|
||||||
|
});
|
||||||
|
await billingConfigService.ensureSchema();
|
||||||
const wechatScheduleLlmConfigService = createWechatScheduleLlmConfigService(pool, {
|
const wechatScheduleLlmConfigService = createWechatScheduleLlmConfigService(pool, {
|
||||||
env: process.env,
|
env: process.env,
|
||||||
});
|
});
|
||||||
@@ -159,6 +164,7 @@ export async function bootstrapAdminServices() {
|
|||||||
const subscriptionService = createSubscriptionService(pool, {
|
const subscriptionService = createSubscriptionService(pool, {
|
||||||
getPlanAsync: (planType) => planCatalogService.getPlan(planType),
|
getPlanAsync: (planType) => planCatalogService.getPlan(planType),
|
||||||
});
|
});
|
||||||
|
subscriptionService._planCatalogService = planCatalogService;
|
||||||
await ensureSystemTestAccountSchema(pool);
|
await ensureSystemTestAccountSchema(pool);
|
||||||
const systemTestAccountService = createSystemTestAccountService(pool);
|
const systemTestAccountService = createSystemTestAccountService(pool);
|
||||||
|
|
||||||
@@ -183,6 +189,7 @@ export async function bootstrapAdminServices() {
|
|||||||
orchestratorObservabilityService,
|
orchestratorObservabilityService,
|
||||||
personalMemoryCandidateStore,
|
personalMemoryCandidateStore,
|
||||||
skillRuntimeConfigService,
|
skillRuntimeConfigService,
|
||||||
|
billingConfigService,
|
||||||
wechatScheduleLlmConfigService,
|
wechatScheduleLlmConfigService,
|
||||||
adminSystemTestService,
|
adminSystemTestService,
|
||||||
systemTestAccountService,
|
systemTestAccountService,
|
||||||
|
|||||||
@@ -110,6 +110,7 @@ ready
|
|||||||
orchestratorObservabilityService,
|
orchestratorObservabilityService,
|
||||||
personalMemoryCandidateStore,
|
personalMemoryCandidateStore,
|
||||||
skillRuntimeConfigService,
|
skillRuntimeConfigService,
|
||||||
|
billingConfigService,
|
||||||
wechatScheduleLlmConfigService,
|
wechatScheduleLlmConfigService,
|
||||||
adminSystemTestService,
|
adminSystemTestService,
|
||||||
systemTestAccountService,
|
systemTestAccountService,
|
||||||
@@ -138,6 +139,7 @@ ready
|
|||||||
orchestratorObservabilityService,
|
orchestratorObservabilityService,
|
||||||
personalMemoryCandidateStore,
|
personalMemoryCandidateStore,
|
||||||
skillRuntimeConfigService,
|
skillRuntimeConfigService,
|
||||||
|
billingConfigService,
|
||||||
wechatScheduleLlmConfigService,
|
wechatScheduleLlmConfigService,
|
||||||
adminSystemTestService,
|
adminSystemTestService,
|
||||||
systemTestAccountService,
|
systemTestAccountService,
|
||||||
|
|||||||
@@ -156,7 +156,7 @@ export async function listUsagePaged(pool, query) {
|
|||||||
);
|
);
|
||||||
const [rows] = await pool.query(
|
const [rows] = await pool.query(
|
||||||
`SELECT r.id, r.user_id, u.username, u.display_name, r.agent_session_id, r.request_id,
|
`SELECT r.id, r.user_id, u.username, u.display_name, r.agent_session_id, r.request_id,
|
||||||
r.input_tokens, r.output_tokens, r.cost_cents, r.balance_after_cents, r.created_at
|
r.input_tokens, r.output_tokens, r.cost_cents, r.balance_after_cents, r.billing_source, r.created_at
|
||||||
FROM h5_usage_records r
|
FROM h5_usage_records r
|
||||||
JOIN h5_users u ON u.id = r.user_id
|
JOIN h5_users u ON u.id = r.user_id
|
||||||
${where}
|
${where}
|
||||||
@@ -176,6 +176,7 @@ export async function listUsagePaged(pool, query) {
|
|||||||
outputTokens: Number(row.output_tokens),
|
outputTokens: Number(row.output_tokens),
|
||||||
costCents: Number(row.cost_cents),
|
costCents: Number(row.cost_cents),
|
||||||
balanceAfterCents: Number(row.balance_after_cents),
|
balanceAfterCents: Number(row.balance_after_cents),
|
||||||
|
billingSource: row.billing_source ?? 'wallet',
|
||||||
createdAt: Number(row.created_at),
|
createdAt: Number(row.created_at),
|
||||||
})),
|
})),
|
||||||
total: Number(total),
|
total: Number(total),
|
||||||
@@ -200,7 +201,7 @@ export async function listLedgerPaged(pool, query) {
|
|||||||
params,
|
params,
|
||||||
);
|
);
|
||||||
const [rows] = await pool.query(
|
const [rows] = await pool.query(
|
||||||
`SELECT l.id, l.user_id, u.username, l.type, l.amount_cents, l.tokens,
|
`SELECT l.id, l.user_id, u.username, u.display_name, l.type, l.amount_cents, l.tokens,
|
||||||
l.session_id, l.note, l.created_at
|
l.session_id, l.note, l.created_at
|
||||||
FROM h5_billing_ledger l
|
FROM h5_billing_ledger l
|
||||||
JOIN h5_users u ON u.id = l.user_id
|
JOIN h5_users u ON u.id = l.user_id
|
||||||
@@ -214,6 +215,7 @@ export async function listLedgerPaged(pool, query) {
|
|||||||
id: Number(row.id),
|
id: Number(row.id),
|
||||||
userId: row.user_id,
|
userId: row.user_id,
|
||||||
username: row.username,
|
username: row.username,
|
||||||
|
displayName: row.display_name,
|
||||||
type: row.type,
|
type: row.type,
|
||||||
amountCents: Number(row.amount_cents),
|
amountCents: Number(row.amount_cents),
|
||||||
tokens: Number(row.tokens),
|
tokens: Number(row.tokens),
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { AdminLayout } from './admin/AdminLayout';
|
|||||||
import { BillingPage } from './admin/pages/BillingPage';
|
import { BillingPage } from './admin/pages/BillingPage';
|
||||||
import { CapabilitiesPage } from './admin/pages/CapabilitiesPage';
|
import { CapabilitiesPage } from './admin/pages/CapabilitiesPage';
|
||||||
import { DashboardPage } from './admin/pages/DashboardPage';
|
import { DashboardPage } from './admin/pages/DashboardPage';
|
||||||
|
import { ImageQuotaPage } from './admin/pages/ImageQuotaPage';
|
||||||
import { PoliciesPage } from './admin/pages/PoliciesPage';
|
import { PoliciesPage } from './admin/pages/PoliciesPage';
|
||||||
import { MindSpacePage } from './admin/pages/MindSpacePage';
|
import { MindSpacePage } from './admin/pages/MindSpacePage';
|
||||||
import { MemoryV2Page } from './admin/pages/MemoryV2Page';
|
import { MemoryV2Page } from './admin/pages/MemoryV2Page';
|
||||||
@@ -119,6 +120,7 @@ function AdminApp({ user, onLogout }: { user: PortalUser; onLogout: () => void }
|
|||||||
<Route path="users" element={<UsersPage />} />
|
<Route path="users" element={<UsersPage />} />
|
||||||
<Route path="users/:userId" element={<UserDetailPage />} />
|
<Route path="users/:userId" element={<UserDetailPage />} />
|
||||||
<Route path="billing/*" element={<BillingPage />} />
|
<Route path="billing/*" element={<BillingPage />} />
|
||||||
|
<Route path="image-quota" element={<ImageQuotaPage />} />
|
||||||
<Route path="capabilities" element={<CapabilitiesPage />} />
|
<Route path="capabilities" element={<CapabilitiesPage />} />
|
||||||
<Route path="skills" element={<SkillsPage />} />
|
<Route path="skills" element={<SkillsPage />} />
|
||||||
<Route path="system-tests" element={<SystemTestsPage />} />
|
<Route path="system-tests" element={<SystemTestsPage />} />
|
||||||
@@ -170,6 +172,7 @@ function loginRedirectPath(pathname: string, role: string | undefined) {
|
|||||||
if (
|
if (
|
||||||
pathname.startsWith('/users')
|
pathname.startsWith('/users')
|
||||||
|| pathname.startsWith('/billing')
|
|| pathname.startsWith('/billing')
|
||||||
|
|| pathname.startsWith('/image-quota')
|
||||||
|| pathname.startsWith('/capabilities')
|
|| pathname.startsWith('/capabilities')
|
||||||
|| pathname.startsWith('/skills')
|
|| pathname.startsWith('/skills')
|
||||||
|| pathname.startsWith('/system-tests')
|
|| pathname.startsWith('/system-tests')
|
||||||
|
|||||||
@@ -21,7 +21,10 @@ const NAV_SECTIONS: NavSection[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: '计费',
|
label: '计费',
|
||||||
items: [{ to: '/billing', label: '计费中心', end: false }],
|
items: [
|
||||||
|
{ to: '/billing', label: '计费中心', end: false },
|
||||||
|
{ to: '/image-quota', label: '图片额度' },
|
||||||
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: '平台配置',
|
label: '平台配置',
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
deleteSubscriptionPlan,
|
deleteSubscriptionPlan,
|
||||||
getAdminUsageStats,
|
getAdminUsageStats,
|
||||||
getAdminUsageSummary,
|
getAdminUsageSummary,
|
||||||
|
getBillingConfig,
|
||||||
grantUserSubscription,
|
grantUserSubscription,
|
||||||
listAdminLedger,
|
listAdminLedger,
|
||||||
listAdminSubscriptions,
|
listAdminSubscriptions,
|
||||||
@@ -13,10 +14,21 @@ import {
|
|||||||
listSubscriptionPlans,
|
listSubscriptionPlans,
|
||||||
rechargeUser,
|
rechargeUser,
|
||||||
syncSubscriptionPlansToProduction,
|
syncSubscriptionPlansToProduction,
|
||||||
|
updateBillingConfig,
|
||||||
updateSubscriptionPlan,
|
updateSubscriptionPlan,
|
||||||
} from '../../api/client';
|
} from '../../api/client';
|
||||||
import type { PagedResult } from '../../api/client';
|
import type { PagedResult } from '../../api/client';
|
||||||
import type { AdminSubscription, AdminUserRow, LedgerEntry, PlanDefinition, UsageRecord, UsageStatsResult, UsageSummaryResult, UsageTotals } from '../../types';
|
import type {
|
||||||
|
AdminSubscription,
|
||||||
|
AdminUserRow,
|
||||||
|
BillingAdminConfig,
|
||||||
|
LedgerEntry,
|
||||||
|
PlanDefinition,
|
||||||
|
UsageRecord,
|
||||||
|
UsageStatsResult,
|
||||||
|
UsageSummaryResult,
|
||||||
|
UsageTotals,
|
||||||
|
} from '../../types';
|
||||||
import { Pagination } from '../../components/Pagination';
|
import { Pagination } from '../../components/Pagination';
|
||||||
import {
|
import {
|
||||||
dateRangeToUnix,
|
dateRangeToUnix,
|
||||||
@@ -116,13 +128,14 @@ function UserCombobox({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
type TabKey = 'recharge' | 'usage' | 'ledger' | 'subscriptions';
|
type TabKey = 'recharge' | 'usage' | 'ledger' | 'subscriptions' | 'formula';
|
||||||
|
|
||||||
const TABS: { key: TabKey; label: string }[] = [
|
const TABS: { key: TabKey; label: string }[] = [
|
||||||
{ key: 'subscriptions', label: '订阅记录' },
|
{ key: 'subscriptions', label: '订阅记录' },
|
||||||
{ key: 'recharge', label: '充值' },
|
{ key: 'recharge', label: '充值' },
|
||||||
{ key: 'usage', label: '用量记录' },
|
{ key: 'usage', label: '用量记录' },
|
||||||
{ key: 'ledger', label: '资金流水' },
|
{ key: 'ledger', label: '资金流水' },
|
||||||
|
{ key: 'formula', label: '计量公式' },
|
||||||
];
|
];
|
||||||
|
|
||||||
const TAB_PATHS: Record<TabKey, string> = {
|
const TAB_PATHS: Record<TabKey, string> = {
|
||||||
@@ -130,6 +143,14 @@ const TAB_PATHS: Record<TabKey, string> = {
|
|||||||
recharge: '/billing/recharge',
|
recharge: '/billing/recharge',
|
||||||
usage: '/billing/usage',
|
usage: '/billing/usage',
|
||||||
ledger: '/billing/ledger',
|
ledger: '/billing/ledger',
|
||||||
|
formula: '/billing/formula',
|
||||||
|
};
|
||||||
|
|
||||||
|
const SOURCE_LABELS: Record<string, string> = {
|
||||||
|
'admin-db': '后台配置',
|
||||||
|
env: '环境变量',
|
||||||
|
'env-override': '环境变量锁定',
|
||||||
|
default: '默认值',
|
||||||
};
|
};
|
||||||
|
|
||||||
function tabFromPath(pathname: string): TabKey {
|
function tabFromPath(pathname: string): TabKey {
|
||||||
@@ -137,10 +158,241 @@ function tabFromPath(pathname: string): TabKey {
|
|||||||
if (suffix === 'usage' || suffix.startsWith('usage/')) return 'usage';
|
if (suffix === 'usage' || suffix.startsWith('usage/')) return 'usage';
|
||||||
if (suffix === 'recharge') return 'recharge';
|
if (suffix === 'recharge') return 'recharge';
|
||||||
if (suffix === 'ledger') return 'ledger';
|
if (suffix === 'ledger') return 'ledger';
|
||||||
|
if (suffix === 'formula') return 'formula';
|
||||||
if (suffix === 'subscriptions') return 'subscriptions';
|
if (suffix === 'subscriptions') return 'subscriptions';
|
||||||
return 'subscriptions';
|
return 'subscriptions';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DEFAULT_BILLING_FORMULA: BillingAdminConfig = {
|
||||||
|
useBackendCost: true,
|
||||||
|
usdCnyRate: 7.2,
|
||||||
|
marginMultiplier: 1.2,
|
||||||
|
inputCentsPer1k: 2,
|
||||||
|
outputCentsPer1k: 6,
|
||||||
|
minBillCents: 1,
|
||||||
|
costEstimateFromTokens: true,
|
||||||
|
costEstimateInputUsdPer1M: 0.27,
|
||||||
|
costEstimateOutputUsdPer1M: 1.1,
|
||||||
|
};
|
||||||
|
|
||||||
|
function FormulaTab() {
|
||||||
|
const [draft, setDraft] = useState<BillingAdminConfig>(DEFAULT_BILLING_FORMULA);
|
||||||
|
const [source, setSource] = useState('default');
|
||||||
|
const [updatedAt, setUpdatedAt] = useState<number | null>(null);
|
||||||
|
const [formula, setFormula] = useState<string>('');
|
||||||
|
const [envLocked, setEnvLocked] = useState(false);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [message, setMessage] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const result = await getBillingConfig();
|
||||||
|
setDraft(result.config);
|
||||||
|
setSource(result.source ?? 'default');
|
||||||
|
setUpdatedAt(result.updatedAt ?? null);
|
||||||
|
setFormula(result.formula ?? '');
|
||||||
|
setEnvLocked(Boolean(result.envOverrideActive));
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : '加载计量公式失败');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
const patchNumber = (key: keyof BillingAdminConfig, value: string) => {
|
||||||
|
const num = Number(value);
|
||||||
|
setDraft((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[key]: Number.isFinite(num) ? num : prev[key],
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (envLocked) {
|
||||||
|
setError('当前环境已锁定为仅读 env(H5_BILLING_CONFIG_SOURCE=env),无法保存。');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (draft.marginMultiplier <= 0 || draft.usdCnyRate <= 0) {
|
||||||
|
setError('汇率与毛利倍数必须大于 0。');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
draft.useBackendCost
|
||||||
|
&& !window.confirm(
|
||||||
|
`确认保存成本模式扣费?\n最终扣费 = 上游成本(USD) × ${draft.usdCnyRate} × ${draft.marginMultiplier}`,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSaving(true);
|
||||||
|
setError(null);
|
||||||
|
setMessage(null);
|
||||||
|
try {
|
||||||
|
const result = await updateBillingConfig(draft);
|
||||||
|
setDraft(result.config);
|
||||||
|
setSource(result.source ?? 'admin-db');
|
||||||
|
setUpdatedAt(result.updatedAt ?? null);
|
||||||
|
setFormula(result.formula ?? '');
|
||||||
|
setEnvLocked(Boolean(result.envOverrideActive));
|
||||||
|
setMessage('计量公式已保存。Portal 扣费会在数秒内读取新配置,无需重启。');
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : '保存失败');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="admin-card">
|
||||||
|
<h2>计量公式</h2>
|
||||||
|
<p className="muted">
|
||||||
|
成本模式:最终扣费 = 上游成本(USD) × 汇率 × 毛利倍数。无上游成本时回退 Token 单价。
|
||||||
|
</p>
|
||||||
|
{loading ? <p className="muted">加载中…</p> : null}
|
||||||
|
{error && <p className="banner banner-error">{error}</p>}
|
||||||
|
{message && <p className="banner banner-info">{message}</p>}
|
||||||
|
{!loading ? (
|
||||||
|
<form className="admin-form" onSubmit={handleSave}>
|
||||||
|
<p className="muted">
|
||||||
|
当前来源:{SOURCE_LABELS[source] ?? source}
|
||||||
|
{updatedAt
|
||||||
|
? ` · 更新于 ${new Date(updatedAt).toLocaleString('zh-CN', { hour12: false })}`
|
||||||
|
: ''}
|
||||||
|
</p>
|
||||||
|
{formula ? <p className="muted">{formula}</p> : null}
|
||||||
|
|
||||||
|
<label className="inline-check">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={draft.useBackendCost}
|
||||||
|
disabled={envLocked}
|
||||||
|
onChange={(event) => setDraft((prev) => ({ ...prev, useBackendCost: event.target.checked }))}
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
<strong>启用成本模式</strong>
|
||||||
|
<span className="muted"> 按上游真实 USD 成本扣费(推荐)</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label>
|
||||||
|
<span>汇率(USD→CNY)</span>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0.01"
|
||||||
|
step="0.01"
|
||||||
|
disabled={envLocked}
|
||||||
|
value={draft.usdCnyRate}
|
||||||
|
onChange={(e) => patchNumber('usdCnyRate', e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>毛利倍数</span>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0.01"
|
||||||
|
step="0.01"
|
||||||
|
disabled={envLocked}
|
||||||
|
value={draft.marginMultiplier}
|
||||||
|
onChange={(e) => patchNumber('marginMultiplier', e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>最低扣费(分)</span>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
step="1"
|
||||||
|
disabled={envLocked}
|
||||||
|
value={draft.minBillCents}
|
||||||
|
onChange={(e) => patchNumber('minBillCents', e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<h3>Token 回退单价(成本缺失时)</h3>
|
||||||
|
<label>
|
||||||
|
<span>输入(分 / 1k tokens)</span>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
disabled={envLocked}
|
||||||
|
value={draft.inputCentsPer1k}
|
||||||
|
onChange={(e) => patchNumber('inputCentsPer1k', e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>输出(分 / 1k tokens)</span>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
disabled={envLocked}
|
||||||
|
value={draft.outputCentsPer1k}
|
||||||
|
onChange={(e) => patchNumber('outputCentsPer1k', e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<h3>上游成本估算(Finish 无 cost 时)</h3>
|
||||||
|
<label className="inline-check">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={draft.costEstimateFromTokens}
|
||||||
|
disabled={envLocked || !draft.useBackendCost}
|
||||||
|
onChange={(event) => setDraft((prev) => ({
|
||||||
|
...prev,
|
||||||
|
costEstimateFromTokens: event.target.checked,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
<strong>按 Token 估算上游成本</strong>
|
||||||
|
<span className="muted"> 仅成本模式生效</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>估算输入(USD / 1M)</span>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
disabled={envLocked || !draft.useBackendCost}
|
||||||
|
value={draft.costEstimateInputUsdPer1M}
|
||||||
|
onChange={(e) => patchNumber('costEstimateInputUsdPer1M', e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>估算输出(USD / 1M)</span>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
disabled={envLocked || !draft.useBackendCost}
|
||||||
|
value={draft.costEstimateOutputUsdPer1M}
|
||||||
|
onChange={(e) => patchNumber('costEstimateOutputUsdPer1M', e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<p className="muted">
|
||||||
|
预览:成本模式扣费 ≈ 上游 USD × {draft.usdCnyRate} × {draft.marginMultiplier}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<button type="submit" className="send-btn" disabled={saving || envLocked}>
|
||||||
|
{saving ? '保存中…' : '保存计量公式'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const PAGE_SIZE = 20;
|
const PAGE_SIZE = 20;
|
||||||
|
|
||||||
function RechargeTab() {
|
function RechargeTab() {
|
||||||
@@ -198,6 +450,11 @@ function UsageRecordsTable({
|
|||||||
result: PagedResult<UsageRecord>;
|
result: PagedResult<UsageRecord>;
|
||||||
onPage: (page: number) => void;
|
onPage: (page: number) => void;
|
||||||
}) {
|
}) {
|
||||||
|
const formatBillingSource = (row: UsageRecord) => {
|
||||||
|
if (row.billingSource === 'subscription') return '套餐额度';
|
||||||
|
return `¥${formatYuan(row.costCents)}`;
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="admin-table-wrap">
|
<div className="admin-table-wrap">
|
||||||
@@ -222,8 +479,10 @@ function UsageRecordsTable({
|
|||||||
</td>
|
</td>
|
||||||
<td className="billing-num">{row.inputTokens.toLocaleString()}</td>
|
<td className="billing-num">{row.inputTokens.toLocaleString()}</td>
|
||||||
<td className="billing-num">{row.outputTokens.toLocaleString()}</td>
|
<td className="billing-num">{row.outputTokens.toLocaleString()}</td>
|
||||||
<td className="billing-num">¥{formatYuan(row.costCents)}</td>
|
<td className="billing-num">{formatBillingSource(row)}</td>
|
||||||
<td className="billing-num">¥{formatYuan(row.balanceAfterCents)}</td>
|
<td className="billing-num">
|
||||||
|
{row.billingSource === 'subscription' ? '—' : `¥${formatYuan(row.balanceAfterCents)}`}
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -839,7 +1098,10 @@ function LedgerTab() {
|
|||||||
{result.items.map((row) => (
|
{result.items.map((row) => (
|
||||||
<tr key={row.id}>
|
<tr key={row.id}>
|
||||||
<td className="billing-time">{formatTime(row.createdAt)}</td>
|
<td className="billing-time">{formatTime(row.createdAt)}</td>
|
||||||
<td>@{row.username}</td>
|
<td>
|
||||||
|
<span>{row.displayName || row.username}</span>
|
||||||
|
<span className="muted"> @{row.username}</span>
|
||||||
|
</td>
|
||||||
<td><span className={`ledger-type-tag ledger-type-${row.type}`}>{TYPE_LABEL[row.type] ?? row.type}</span></td>
|
<td><span className={`ledger-type-tag ledger-type-${row.type}`}>{TYPE_LABEL[row.type] ?? row.type}</span></td>
|
||||||
<td className={`billing-num ${row.amountCents < 0 ? 'text-error' : 'text-income'}`}>
|
<td className={`billing-num ${row.amountCents < 0 ? 'text-error' : 'text-income'}`}>
|
||||||
{row.amountCents >= 0 ? '+' : ''}¥{formatYuan(Math.abs(row.amountCents))}
|
{row.amountCents >= 0 ? '+' : ''}¥{formatYuan(Math.abs(row.amountCents))}
|
||||||
@@ -1450,7 +1712,7 @@ export function BillingPage() {
|
|||||||
<div className="admin-page">
|
<div className="admin-page">
|
||||||
<div className="admin-page-head">
|
<div className="admin-page-head">
|
||||||
<h2>计费中心</h2>
|
<h2>计费中心</h2>
|
||||||
<p className="muted">充值、用量与资金流水</p>
|
<p className="muted">充值、用量、资金流水与计量公式</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-tabs" role="tablist">
|
<div className="admin-tabs" role="tablist">
|
||||||
{TABS.map((tab) => (
|
{TABS.map((tab) => (
|
||||||
@@ -1466,6 +1728,7 @@ export function BillingPage() {
|
|||||||
{activeTab === 'usage' && <UsageTab />}
|
{activeTab === 'usage' && <UsageTab />}
|
||||||
{activeTab === 'ledger' && <LedgerTab />}
|
{activeTab === 'ledger' && <LedgerTab />}
|
||||||
{activeTab === 'subscriptions' && <SubscriptionsTab />}
|
{activeTab === 'subscriptions' && <SubscriptionsTab />}
|
||||||
|
{activeTab === 'formula' && <FormulaTab />}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -238,7 +238,9 @@ export function DashboardPage() {
|
|||||||
<td>
|
<td>
|
||||||
in {row.inputTokens} / out {row.outputTokens}
|
in {row.inputTokens} / out {row.outputTokens}
|
||||||
</td>
|
</td>
|
||||||
<td>¥{formatYuan(row.costCents)}</td>
|
<td>
|
||||||
|
{row.billingSource === 'subscription' ? '套餐额度' : `¥${formatYuan(row.costCents)}`}
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,285 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import {
|
||||||
|
fetchImageQuotaConfig,
|
||||||
|
fetchImageQuotaLedger,
|
||||||
|
patchImageQuotaPlan,
|
||||||
|
} from '../../api/client';
|
||||||
|
import type { ImageQuotaLedgerEntry, PlanDefinition } from '../../types';
|
||||||
|
import { Pagination } from '../../components/Pagination';
|
||||||
|
import { formatTime } from '../utils/format';
|
||||||
|
|
||||||
|
type Tab = 'plans' | 'ledger';
|
||||||
|
|
||||||
|
function fmtQuota(value: number | null | undefined, unlimited = false) {
|
||||||
|
if (unlimited || value == null) return '无限';
|
||||||
|
return String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const REASON_LABELS: Record<string, string> = {
|
||||||
|
admin_grant: '管理员充值',
|
||||||
|
admin_adjust: '管理员调整',
|
||||||
|
consume: '生图消费',
|
||||||
|
period_reset: '周期重置',
|
||||||
|
plan_change: '套餐变更',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ImageQuotaPage() {
|
||||||
|
const [tab, setTab] = useState<Tab>('plans');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="admin-page">
|
||||||
|
<div className="admin-page-head">
|
||||||
|
<h2>图片生成额度</h2>
|
||||||
|
<p className="muted">
|
||||||
|
用户有剩余额度时才能调用 image_make 生图;套餐默认额度中 0 表示无限。用户级充值请在「用户管理 → 用户详情」中操作。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="admin-card" style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={tab === 'plans' ? 'send-btn' : 'ghost-btn'}
|
||||||
|
onClick={() => setTab('plans')}
|
||||||
|
>
|
||||||
|
套餐默认额度
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={tab === 'ledger' ? 'send-btn' : 'ghost-btn'}
|
||||||
|
onClick={() => setTab('ledger')}
|
||||||
|
>
|
||||||
|
额度流水
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{tab === 'plans' ? <PlansTab /> : <LedgerTab />}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PlansTab() {
|
||||||
|
const [plans, setPlans] = useState<PlanDefinition[]>([]);
|
||||||
|
const [drafts, setDrafts] = useState<Record<string, string>>({});
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [busyPlan, setBusyPlan] = useState<string | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [message, setMessage] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const result = await fetchImageQuotaConfig();
|
||||||
|
setPlans(result.plans);
|
||||||
|
setDrafts(Object.fromEntries(result.plans.map((plan) => [plan.planType, String(plan.periodImages)])));
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : '加载失败');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const savePlan = async (planType: string) => {
|
||||||
|
const raw = drafts[planType];
|
||||||
|
const periodImages = Math.floor(Number(raw));
|
||||||
|
if (!Number.isFinite(periodImages) || periodImages < 0) {
|
||||||
|
setError('额度必须是非负整数');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusyPlan(planType);
|
||||||
|
setError(null);
|
||||||
|
setMessage(null);
|
||||||
|
try {
|
||||||
|
await patchImageQuotaPlan(planType, periodImages);
|
||||||
|
setMessage(`已更新 ${planType} 默认图片额度`);
|
||||||
|
await load();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : '保存失败');
|
||||||
|
} finally {
|
||||||
|
setBusyPlan(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{error && <p className="banner banner-error">{error}</p>}
|
||||||
|
{message && <p className="banner banner-info">{message}</p>}
|
||||||
|
|
||||||
|
<section className="admin-card">
|
||||||
|
{loading && plans.length === 0 ? (
|
||||||
|
<p className="muted">加载中…</p>
|
||||||
|
) : (
|
||||||
|
<div className="admin-table-wrap">
|
||||||
|
<table className="admin-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>套餐</th>
|
||||||
|
<th>标识</th>
|
||||||
|
<th>月图片额度</th>
|
||||||
|
<th>月 Token</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{plans.map((plan) => (
|
||||||
|
<tr key={plan.planType}>
|
||||||
|
<td>{plan.name}</td>
|
||||||
|
<td>
|
||||||
|
<code className="mono">{plan.planType}</code>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="1"
|
||||||
|
value={drafts[plan.planType] ?? String(plan.periodImages)}
|
||||||
|
onChange={(e) => setDrafts((prev) => ({ ...prev, [plan.planType]: e.target.value }))}
|
||||||
|
style={{ width: 120 }}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="muted">
|
||||||
|
{plan.periodTokens === 0 ? '无限' : plan.periodTokens.toLocaleString('zh-CN')}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="ghost-btn"
|
||||||
|
disabled={loading || busyPlan === plan.planType}
|
||||||
|
onClick={() => void savePlan(plan.planType)}
|
||||||
|
>
|
||||||
|
{busyPlan === plan.planType ? '保存中…' : '保存'}
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{plans.length === 0 && !loading ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={5} className="muted" style={{ textAlign: 'center', padding: 24 }}>
|
||||||
|
暂无套餐配置
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LedgerTab() {
|
||||||
|
const [entries, setEntries] = useState<ImageQuotaLedgerEntry[]>([]);
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [totalPages, setTotalPages] = useState(1);
|
||||||
|
const [total, setTotal] = useState(0);
|
||||||
|
const [userId, setUserId] = useState('');
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const load = async (p = 1) => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const result = await fetchImageQuotaLedger({
|
||||||
|
page: p,
|
||||||
|
pageSize: 30,
|
||||||
|
userId: userId.trim() || undefined,
|
||||||
|
});
|
||||||
|
setEntries(result.entries);
|
||||||
|
setTotal(result.total);
|
||||||
|
setTotalPages(result.totalPages);
|
||||||
|
setPage(p);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : '加载失败');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load(1);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<section className="admin-card">
|
||||||
|
<form
|
||||||
|
className="admin-form"
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
void load(1);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
placeholder="按 userId 过滤"
|
||||||
|
value={userId}
|
||||||
|
onChange={(e) => setUserId(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button type="submit" className="send-btn" disabled={loading}>
|
||||||
|
搜索
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{error && <p className="banner banner-error">{error}</p>}
|
||||||
|
|
||||||
|
<section className="admin-card">
|
||||||
|
{loading && entries.length === 0 ? (
|
||||||
|
<p className="muted">加载中…</p>
|
||||||
|
) : (
|
||||||
|
<div className="admin-table-wrap">
|
||||||
|
<table className="admin-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>时间</th>
|
||||||
|
<th>用户</th>
|
||||||
|
<th>变动</th>
|
||||||
|
<th>剩余</th>
|
||||||
|
<th>原因</th>
|
||||||
|
<th>备注</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{entries.map((entry) => (
|
||||||
|
<tr key={entry.id}>
|
||||||
|
<td className="muted">{formatTime(entry.createdAt)}</td>
|
||||||
|
<td>
|
||||||
|
<div>{entry.displayName || entry.username || '—'}</div>
|
||||||
|
<code className="mono muted">{entry.userId}</code>
|
||||||
|
</td>
|
||||||
|
<td style={{ color: entry.delta >= 0 ? 'var(--ok)' : 'var(--danger)' }}>
|
||||||
|
{entry.delta >= 0 ? `+${entry.delta}` : entry.delta}
|
||||||
|
</td>
|
||||||
|
<td>{fmtQuota(entry.balanceAfter)}</td>
|
||||||
|
<td>{REASON_LABELS[entry.reason] ?? entry.reason}</td>
|
||||||
|
<td className="muted">{entry.note || entry.refId || '—'}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{entries.length === 0 && !loading ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={6} className="muted" style={{ textAlign: 'center', padding: 24 }}>
|
||||||
|
暂无流水
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<Pagination
|
||||||
|
page={page}
|
||||||
|
totalPages={totalPages}
|
||||||
|
total={total}
|
||||||
|
pageSize={30}
|
||||||
|
onChange={(p) => void load(p)}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ import type {
|
|||||||
MemoryV2RuntimeStatusResponse,
|
MemoryV2RuntimeStatusResponse,
|
||||||
PersonalMemoryCandidateListResponse,
|
PersonalMemoryCandidateListResponse,
|
||||||
} from '../../types';
|
} from '../../types';
|
||||||
|
import { isMemoryV2SectionEnabled } from './memory-v2-config';
|
||||||
|
|
||||||
type BackendKey =
|
type BackendKey =
|
||||||
| 'pgvector'
|
| 'pgvector'
|
||||||
@@ -923,7 +924,8 @@ export function MemoryV2Page() {
|
|||||||
{CAPABILITIES.map((capability, index) => {
|
{CAPABILITIES.map((capability, index) => {
|
||||||
const section = draft[capability.key];
|
const section = draft[capability.key];
|
||||||
const currentSection = current[capability.key];
|
const currentSection = current[capability.key];
|
||||||
const enabled = Boolean(section.enabled);
|
const enabled = isMemoryV2SectionEnabled(capability.key, section);
|
||||||
|
const savedEnabled = isMemoryV2SectionEnabled(capability.key, currentSection);
|
||||||
const accent = BACKEND_ACCENTS[index % BACKEND_ACCENTS.length];
|
const accent = BACKEND_ACCENTS[index % BACKEND_ACCENTS.length];
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
@@ -1015,8 +1017,8 @@ export function MemoryV2Page() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<span className={`asset-status ${Boolean(currentSection.enabled) ? 'is-on' : ''}`}>
|
<span className={`asset-status ${savedEnabled ? 'is-on' : ''}`}>
|
||||||
当前保存:{Boolean(currentSection.enabled) ? '启用' : '关闭'}
|
当前保存:{savedEnabled ? '启用' : '关闭'}
|
||||||
</span>
|
</span>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { Link, Navigate, useParams } from 'react-router-dom';
|
import { Link, Navigate, useParams } from 'react-router-dom';
|
||||||
import { getAdminUser, rechargeUser, updateAdminUser } from '../../api/client';
|
import { getAdminUser, rechargeUser, updateAdminUser, fetchUserImageQuota, setUserImageQuota } from '../../api/client';
|
||||||
import { CapabilitySettings } from '../../components/CapabilitySettings';
|
import { CapabilitySettings } from '../../components/CapabilitySettings';
|
||||||
import { PolicySettings } from '../../components/PolicySettings';
|
import { PolicySettings } from '../../components/PolicySettings';
|
||||||
import { SkillSettings } from '../../components/SkillSettings';
|
import { SkillSettings } from '../../components/SkillSettings';
|
||||||
import { useAdminUsers } from '../hooks/useAdminUsers';
|
import { useAdminUsers } from '../hooks/useAdminUsers';
|
||||||
import { formatYuan } from '../utils/format';
|
import { formatYuan } from '../utils/format';
|
||||||
import type { PortalUser } from '../../types';
|
import type { ImageQuotaView, PortalUser } from '../../types';
|
||||||
|
|
||||||
function formatBytes(bytes: number) {
|
function formatBytes(bytes: number) {
|
||||||
if (bytes < 1024) return `${bytes} B`;
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
@@ -23,6 +23,10 @@ export function UserDetailPage() {
|
|||||||
const [message, setMessage] = useState<string | null>(null);
|
const [message, setMessage] = useState<string | null>(null);
|
||||||
const [recharge, setRecharge] = useState({ amountYuan: '10', note: '' });
|
const [recharge, setRecharge] = useState({ amountYuan: '10', note: '' });
|
||||||
const [spaceQuotaMb, setSpaceQuotaMb] = useState('5');
|
const [spaceQuotaMb, setSpaceQuotaMb] = useState('5');
|
||||||
|
const [imageQuota, setImageQuota] = useState<ImageQuotaView | null>(null);
|
||||||
|
const [imageQuotaLoading, setImageQuotaLoading] = useState(false);
|
||||||
|
const [imageRemaining, setImageRemaining] = useState('');
|
||||||
|
const [imageGrantNote, setImageGrantNote] = useState('');
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!user?.spaceQuotaBytes) return;
|
if (!user?.spaceQuotaBytes) return;
|
||||||
@@ -57,6 +61,36 @@ export function UserDetailPage() {
|
|||||||
};
|
};
|
||||||
}, [userId, users]);
|
}, [userId, users]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!user || user.role !== 'user') {
|
||||||
|
setImageQuota(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cancelled = false;
|
||||||
|
setImageQuotaLoading(true);
|
||||||
|
void fetchUserImageQuota(user.id)
|
||||||
|
.then((result) => {
|
||||||
|
if (!cancelled) setImageQuota(result.quota);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!cancelled) setImageQuota(null);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (!cancelled) setImageQuotaLoading(false);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [user?.id, user?.role]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!imageQuota || imageQuota.unlimited || imageQuota.remaining == null) {
|
||||||
|
setImageRemaining('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setImageRemaining(String(imageQuota.remaining));
|
||||||
|
}, [imageQuota?.remaining, imageQuota?.unlimited]);
|
||||||
|
|
||||||
const handleRecharge = async (e: React.FormEvent) => {
|
const handleRecharge = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!user) return;
|
if (!user) return;
|
||||||
@@ -75,6 +109,45 @@ export function UserDetailPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleImageQuotaSave = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!user) return;
|
||||||
|
setMessage(null);
|
||||||
|
setLocalError(null);
|
||||||
|
setError(null);
|
||||||
|
if (!imageQuota) {
|
||||||
|
setLocalError('暂无额度信息,用户可能尚无有效订阅');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (imageQuota.unlimited) {
|
||||||
|
setLocalError('当前为无限额度套餐,无法在此调整');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const targetRemaining = Math.floor(Number(imageRemaining));
|
||||||
|
if (!Number.isFinite(targetRemaining) || targetRemaining < 0) {
|
||||||
|
setLocalError('请输入非负整数剩余额度');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (targetRemaining === imageQuota.remaining) {
|
||||||
|
setMessage('额度未变化');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const result = await setUserImageQuota(user.id, { remaining: targetRemaining }, imageGrantNote.trim());
|
||||||
|
setImageQuota(result.quota);
|
||||||
|
setMessage(result.unchanged ? '额度未变化' : '图片额度已更新');
|
||||||
|
setImageGrantNote('');
|
||||||
|
} catch (err) {
|
||||||
|
setLocalError(err instanceof Error ? err.message : '图片额度设置失败');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const imageQuotaSummary = imageQuota
|
||||||
|
? imageQuota.unlimited
|
||||||
|
? '无限'
|
||||||
|
: `剩余 ${imageQuota.remaining ?? 0} / 总计 ${imageQuota.total ?? 0}(套餐 ${imageQuota.limit} + 充值 ${imageQuota.bonus},已用 ${imageQuota.used})`
|
||||||
|
: '';
|
||||||
|
|
||||||
if (!loading && !user && !error) {
|
if (!loading && !user && !error) {
|
||||||
return <Navigate to="/users" replace />;
|
return <Navigate to="/users" replace />;
|
||||||
}
|
}
|
||||||
@@ -186,6 +259,42 @@ export function UserDetailPage() {
|
|||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section className="admin-card">
|
||||||
|
<h2>图片生成额度</h2>
|
||||||
|
{imageQuotaLoading ? (
|
||||||
|
<p className="muted">加载中…</p>
|
||||||
|
) : (
|
||||||
|
<p className="muted">{imageQuotaSummary || '暂无额度信息(用户可能尚无订阅)'}</p>
|
||||||
|
)}
|
||||||
|
<p className="muted">
|
||||||
|
直接设置本周期剩余可用张数。若目标低于当前套餐额度,会自动下调该用户的周期额度上限。
|
||||||
|
</p>
|
||||||
|
<form className="admin-form" onSubmit={handleImageQuotaSave}>
|
||||||
|
<input
|
||||||
|
placeholder="剩余额度(张)"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="1"
|
||||||
|
value={imageRemaining}
|
||||||
|
onChange={(e) => setImageRemaining(e.target.value)}
|
||||||
|
disabled={!imageQuota || imageQuota.unlimited}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
placeholder="备注"
|
||||||
|
value={imageGrantNote}
|
||||||
|
onChange={(e) => setImageGrantNote(e.target.value)}
|
||||||
|
disabled={!imageQuota || imageQuota.unlimited}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="send-btn"
|
||||||
|
disabled={!imageQuota || imageQuota.unlimited}
|
||||||
|
>
|
||||||
|
保存额度
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section className="admin-card">
|
<section className="admin-card">
|
||||||
<h2>调整空间</h2>
|
<h2>调整空间</h2>
|
||||||
<p className="muted">
|
<p className="muted">
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import type { MemoryV2AdminSection } from '../../types';
|
||||||
|
|
||||||
|
type CapabilityKey =
|
||||||
|
| 'candidateMemory'
|
||||||
|
| 'runtimeControl'
|
||||||
|
| 'policy'
|
||||||
|
| 'retriever'
|
||||||
|
| 'lifecycle'
|
||||||
|
| 'persona'
|
||||||
|
| 'graph'
|
||||||
|
| 'userMemory'
|
||||||
|
| 'pluginHealth';
|
||||||
|
|
||||||
|
function modeEnabled(value: unknown) {
|
||||||
|
const mode = String(value ?? 'off').trim().toLowerCase();
|
||||||
|
return mode !== '' && mode !== 'off';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isMemoryV2SectionEnabled(
|
||||||
|
sectionKey: CapabilityKey,
|
||||||
|
section: MemoryV2AdminSection | undefined,
|
||||||
|
): boolean {
|
||||||
|
const config = section ?? {};
|
||||||
|
if (sectionKey === 'runtimeControl') {
|
||||||
|
return Boolean(config.agentResolveEnabled)
|
||||||
|
|| modeEnabled(config.agentInjectionMode)
|
||||||
|
|| Boolean(config.promotionEnabled)
|
||||||
|
|| Boolean(config.compactionV2Enabled)
|
||||||
|
|| Boolean(config.reflectionEnabled)
|
||||||
|
|| Boolean(config.lifecycleWorkerEnabled)
|
||||||
|
|| modeEnabled(config.lifecycleRolloutMode);
|
||||||
|
}
|
||||||
|
return Boolean(config.enabled);
|
||||||
|
}
|
||||||
@@ -8,10 +8,14 @@ import type {
|
|||||||
AdminSubscription,
|
AdminSubscription,
|
||||||
AdminUserRow,
|
AdminUserRow,
|
||||||
AuthStatus,
|
AuthStatus,
|
||||||
|
BillingAdminConfig,
|
||||||
|
BillingAdminConfigResponse,
|
||||||
BlockedWord,
|
BlockedWord,
|
||||||
CapabilityDefinition,
|
CapabilityDefinition,
|
||||||
CapabilityMap,
|
CapabilityMap,
|
||||||
InsufficientBalanceDetails,
|
InsufficientBalanceDetails,
|
||||||
|
ImageQuotaLedgerEntry,
|
||||||
|
ImageQuotaView,
|
||||||
LedgerEntry,
|
LedgerEntry,
|
||||||
LlmConnectionTestResult,
|
LlmConnectionTestResult,
|
||||||
LlmExecutorBinding,
|
LlmExecutorBinding,
|
||||||
@@ -1302,6 +1306,19 @@ export async function syncSubscriptionPlansToProduction(): Promise<PlanSyncResul
|
|||||||
return result.sync;
|
return result.sync;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getBillingConfig(): Promise<BillingAdminConfigResponse> {
|
||||||
|
return portalFetch('/admin-api/billing/config');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateBillingConfig(
|
||||||
|
config: BillingAdminConfig,
|
||||||
|
): Promise<BillingAdminConfigResponse> {
|
||||||
|
return portalFetch('/admin-api/billing/config', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ config }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function listAdminSubscriptions(opts?: {
|
export async function listAdminSubscriptions(opts?: {
|
||||||
userId?: string;
|
userId?: string;
|
||||||
status?: string;
|
status?: string;
|
||||||
@@ -1351,3 +1368,67 @@ export async function getUserSubscription(userId: string): Promise<AdminSubscrip
|
|||||||
);
|
);
|
||||||
return result.subscription;
|
return result.subscription;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function fetchImageQuotaConfig() {
|
||||||
|
return portalFetch<{ plans: PlanDefinition[] }>('/admin-api/image-quota/config');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function patchImageQuotaPlan(planType: string, periodImages: number) {
|
||||||
|
return portalFetch<{ ok: boolean; plan: PlanDefinition }>(`/admin-api/image-quota/config/${planType}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: JSON.stringify({ periodImages }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchUserImageQuota(userId: string) {
|
||||||
|
return portalFetch<{
|
||||||
|
subscription: AdminSubscription;
|
||||||
|
quota: ImageQuotaView;
|
||||||
|
ledger: ImageQuotaLedgerEntry[];
|
||||||
|
}>(`/admin-api/users/${userId}/image-quota`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setUserImageQuota(
|
||||||
|
userId: string,
|
||||||
|
payload: { remaining?: number; total?: number },
|
||||||
|
note = '',
|
||||||
|
) {
|
||||||
|
return portalFetch<{
|
||||||
|
ok: boolean;
|
||||||
|
unchanged?: boolean;
|
||||||
|
subscription: AdminSubscription;
|
||||||
|
quota: ImageQuotaView;
|
||||||
|
}>(`/admin-api/users/${userId}/image-quota`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ ...payload, note }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function grantUserImageQuota(userId: string, delta: number, note = '') {
|
||||||
|
return portalFetch<{
|
||||||
|
ok: boolean;
|
||||||
|
subscription: AdminSubscription;
|
||||||
|
quota: ImageQuotaView;
|
||||||
|
}>(`/admin-api/users/${userId}/image-quota/grant`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ delta, note }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchImageQuotaLedger(params: {
|
||||||
|
userId?: string;
|
||||||
|
page?: number;
|
||||||
|
pageSize?: number;
|
||||||
|
} = {}) {
|
||||||
|
const q = new URLSearchParams();
|
||||||
|
if (params.userId) q.set('userId', params.userId);
|
||||||
|
if (params.page) q.set('page', String(params.page));
|
||||||
|
if (params.pageSize) q.set('pageSize', String(params.pageSize));
|
||||||
|
return portalFetch<{
|
||||||
|
entries: ImageQuotaLedgerEntry[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
totalPages: number;
|
||||||
|
}>(`/admin-api/image-quota/ledger${q.toString() ? `?${q}` : ''}`);
|
||||||
|
}
|
||||||
|
|||||||
@@ -244,6 +244,7 @@ export type UsageRecord = {
|
|||||||
outputTokens: number;
|
outputTokens: number;
|
||||||
costCents: number;
|
costCents: number;
|
||||||
balanceAfterCents: number;
|
balanceAfterCents: number;
|
||||||
|
billingSource: 'wallet' | 'subscription';
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -282,6 +283,7 @@ export type LedgerEntry = {
|
|||||||
id: number;
|
id: number;
|
||||||
userId: string;
|
userId: string;
|
||||||
username: string;
|
username: string;
|
||||||
|
displayName: string;
|
||||||
type: 'recharge' | 'deduct' | 'refund' | 'adjust';
|
type: 'recharge' | 'deduct' | 'refund' | 'adjust';
|
||||||
amountCents: number;
|
amountCents: number;
|
||||||
tokens: number;
|
tokens: number;
|
||||||
@@ -645,6 +647,27 @@ export type BlockedWord = {
|
|||||||
updated_at: number;
|
updated_at: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type BillingAdminConfig = {
|
||||||
|
useBackendCost: boolean;
|
||||||
|
usdCnyRate: number;
|
||||||
|
marginMultiplier: number;
|
||||||
|
inputCentsPer1k: number;
|
||||||
|
outputCentsPer1k: number;
|
||||||
|
minBillCents: number;
|
||||||
|
costEstimateFromTokens: boolean;
|
||||||
|
costEstimateInputUsdPer1M: number;
|
||||||
|
costEstimateOutputUsdPer1M: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type BillingAdminConfigResponse = {
|
||||||
|
config: BillingAdminConfig;
|
||||||
|
updatedAt: number | null;
|
||||||
|
updatedBy: string | null;
|
||||||
|
source?: string;
|
||||||
|
envOverrideActive?: boolean;
|
||||||
|
formula?: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type PlanDefinition = {
|
export type PlanDefinition = {
|
||||||
planType: string;
|
planType: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -681,6 +704,32 @@ export type AdminSubscription = {
|
|||||||
periodTokensUsed: number;
|
periodTokensUsed: number;
|
||||||
periodImagesLimit: number;
|
periodImagesLimit: number;
|
||||||
periodImagesUsed: number;
|
periodImagesUsed: number;
|
||||||
|
periodImagesBonus?: number;
|
||||||
|
note: string | null;
|
||||||
|
createdAt: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ImageQuotaView = {
|
||||||
|
limit: number;
|
||||||
|
bonus: number;
|
||||||
|
used: number;
|
||||||
|
total: number | null;
|
||||||
|
remaining: number | null;
|
||||||
|
unlimited: boolean;
|
||||||
|
periodEnd: number | null;
|
||||||
|
planType: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ImageQuotaLedgerEntry = {
|
||||||
|
id: string;
|
||||||
|
userId: string;
|
||||||
|
username?: string;
|
||||||
|
displayName?: string;
|
||||||
|
delta: number;
|
||||||
|
balanceAfter: number | null;
|
||||||
|
reason: string;
|
||||||
|
refId: string | null;
|
||||||
|
operatorId: string | null;
|
||||||
note: string | null;
|
note: string | null;
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user