Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d0183cb636 | |||
| eca1aa635e | |||
| f8317e8312 | |||
| a4d46f2b1e |
@@ -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);
|
||||||
|
});
|
||||||
@@ -1183,6 +1183,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) {
|
||||||
|
|||||||
@@ -159,6 +159,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);
|
||||||
|
|
||||||
|
|||||||
@@ -200,7 +200,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 +214,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: '平台配置',
|
||||||
|
|||||||
@@ -839,7 +839,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))}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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">
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import type {
|
|||||||
CapabilityDefinition,
|
CapabilityDefinition,
|
||||||
CapabilityMap,
|
CapabilityMap,
|
||||||
InsufficientBalanceDetails,
|
InsufficientBalanceDetails,
|
||||||
|
ImageQuotaLedgerEntry,
|
||||||
|
ImageQuotaView,
|
||||||
LedgerEntry,
|
LedgerEntry,
|
||||||
LlmConnectionTestResult,
|
LlmConnectionTestResult,
|
||||||
LlmExecutorBinding,
|
LlmExecutorBinding,
|
||||||
@@ -1351,3 +1353,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}` : ''}`);
|
||||||
|
}
|
||||||
|
|||||||
@@ -282,6 +282,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;
|
||||||
@@ -681,6 +682,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