Skip to content

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

feat(admin): 完善设置表单、金额输入和模板校验

yidd5abf4e775f
diff --git a/admin/src/components/settings/MediaPriceSettings.tsx b/admin/src/components/settings/MediaPriceSettings.tsx
index fd1f1de..9c44a11 100644
--- a/admin/src/components/settings/MediaPriceSettings.tsx
+++ b/admin/src/components/settings/MediaPriceSettings.tsx
@@ -1,56 +1,90 @@
-import { useEffect, useState } from 'react'
-import { api } from '@/api/client'
-import { Button } from '@/components/ui/button'
+import { useEffect, useRef, useState } from "react";
+import { api } from "@/api/client";
+import { AdminField } from "@/components/admin/AdminField";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { SettingsPanel } from "./SettingsPanel";
-type PriceData = { active_version: number | null; enabled: boolean; prices: Record<string, Record<string, string>>;
- strategies: Array<{ id: string; capability: string; allowed_resolutions: string[]; duration_min?: number; duration_max?: number }> }
+type PriceData = {
+ active_version: number | null; enabled: boolean; prices: Record<string, Record<string, string>>;
+ strategies: Array<{ id: string; capability: string; allowed_resolutions: string[]; duration_min?: number; duration_max?: number }>;
+};
+function priceError(value: string) {
+ if (!value.trim()) return "";
+ if (!/^\d+(?:\.\d{1,4})?$/.test(value.trim())) return "请输入金额,最多保留 4 位小数";
+ return Number(value) < 0.0001 || Number(value) > 10000 ? "单价范围为 0.0001–10000 元" : "";
+}
+/** Price publishing is independent from the surrounding payment settings save. */
export function MediaPriceSettings() {
- const [data, setData] = useState<PriceData | null>(null)
- const [error, setError] = useState('')
- const [notice, setNotice] = useState('')
- const [busy, setBusy] = useState(false)
+ const [data, setData] = useState<PriceData | null>(null);
+ const [error, setError] = useState("");
+ const [notice, setNotice] = useState("");
+ const [operation, setOperation] = useState<"" | "load" | "publish" | "toggle">("");
+ const baseline = useRef("");
+ const busy = Boolean(operation);
+ const dirty = Boolean(data && baseline.current !== JSON.stringify(data.prices));
+ const invalidPrices = data ? Object.values(data.prices).some(rows => Object.values(rows).some(price => priceError(price))) : false;
async function load() {
- try { setData(await api<PriceData>('/api/admin/settings/billing/media-prices')); setError('') }
- catch (cause) { setError(cause instanceof Error ? cause.message : '价格加载失败') }
+ try {
+ const loaded = await api<PriceData>("/api/admin/settings/billing/media-prices");
+ baseline.current = JSON.stringify(loaded.prices); setData(loaded); setError(""); return true;
+ } catch (cause) { setError(cause instanceof Error ? cause.message : "价格加载失败"); return false; }
+ }
+ useEffect(() => { void load(); }, []);
+ async function reload() {
+ if (busy) return;
+ setOperation("load"); setNotice("");
+ try { await load(); } finally { setOperation(""); }
}
- useEffect(() => { void load() }, [])
async function toggle() {
- if (!data?.active_version) return
- setBusy(true)
+ if (!data?.active_version || busy) return;
+ setOperation("toggle"); setNotice(""); setError("");
try {
- await api('/api/admin/settings/billing/media-prices/activation', { method: 'PATCH', body: JSON.stringify({ enabled: !data.enabled, expected_version: data.active_version }) })
- await load(); setNotice('计费模式已切换,仅影响新任务,在途任务保持原规则。')
- } catch (cause) { setError(cause instanceof Error ? cause.message : '切换失败') }
- finally { setBusy(false) }
+ await api("/api/admin/settings/billing/media-prices/activation", { method: "PATCH", body: JSON.stringify({ enabled: !data.enabled, expected_version: data.active_version }) });
+ setData(current => current ? { ...current, enabled: !data.enabled } : current);
+ setNotice("计费模式已切换,仅影响新任务,在途任务保持原规则。");
+ } catch (cause) { setError(cause instanceof Error ? cause.message : "切换失败"); }
+ finally { setOperation(""); }
}
async function publish() {
- if (!data) return
- setBusy(true); setError(''); setNotice('')
+ if (!data || busy || invalidPrices) return;
+ setOperation("publish"); setError(""); setNotice("");
try {
- const prices = Object.fromEntries(Object.entries(data.prices).map(([model, rows]) =>
- [model, Object.fromEntries(Object.entries(rows).filter(([, value]) => value.trim() !== ''))]))
- await api('/api/admin/settings/billing/media-prices', { method: 'POST', body: JSON.stringify({ prices, expected_version: data.active_version }) })
- await load(); setNotice('价格已发布,新任务立即生效,在途任务保持原价格。')
- } catch (cause) { setError(cause instanceof Error ? cause.message : '发布失败') }
- finally { setBusy(false) }
+ const prices = Object.fromEntries(Object.entries(data.prices).map(([model, rows]) => [model,
+ Object.fromEntries(Object.entries(rows).filter(([, value]) => value.trim() !== "").map(([resolution, value]) => [resolution, value.trim()])),
+ ]));
+ await api("/api/admin/settings/billing/media-prices", { method: "POST", body: JSON.stringify({ prices, expected_version: data.active_version }) });
+ const refreshed = await load();
+ setNotice(refreshed ? "价格已发布,新任务立即生效,在途任务保持原价格。" : "价格已发布,最新版本读取失败,请重新加载后继续编辑。");
+ } catch (cause) { setError(cause instanceof Error ? cause.message : "发布失败"); }
+ finally { setOperation(""); }
}
- return <section className="settings-panel">
- <h3>图片与视频价格</h3>
- <p className="text-sm text-[var(--admin-muted)]">{data?.active_version ? `价格版本 #${data.active_version} · ${data.enabled ? '已启用' : '已停用,新任务沿用原计费'}` : '尚未发布:下方为现有规则换算的价格草稿。'} 图片按张、视频按提交秒数收费;空白档位不可生成。失败不自动切换路由。</p>
- {error && <p role="alert" className="text-red-600">{error}</p>}
- {notice && <p role="status">{notice}</p>}
- {data && ['image', 'video'].map(kind => <div key={kind} className="admin-table-wrap mt-4">
- <h4>{kind === 'image' ? '图片 · 元/张' : '视频 · 元/秒'}</h4>
- <table><thead><tr><th>模型</th><th>支持参数</th><th>分辨率与单价</th></tr></thead>
- <tbody>{data.strategies.filter(strategy => strategy.capability === kind).map(strategy => <tr key={strategy.id}>
- <td>{strategy.id}</td><td>{strategy.duration_max ? `${strategy.duration_min}–${strategy.duration_max} 秒` : '按成功交付张数'}</td>
- <td><div className="flex flex-wrap gap-3">{strategy.allowed_resolutions.map(resolution => <label key={resolution} className="flex items-center gap-2 text-sm">
- {resolution}<input type="number" min="0.0001" max="10000" step="0.0001" aria-label={`${strategy.id} ${resolution} 单价`} placeholder="未配置" className="w-28 rounded border p-2"
- value={data.prices[strategy.id]?.[resolution] ?? ''} onChange={event => setData({ ...data, prices: { ...data.prices, [strategy.id]: { ...data.prices[strategy.id], [resolution]: event.target.value } } })} />
- </label>)}</div></td>
- </tr>)}</tbody></table>
- </div>)}
- <div className="mt-4 flex gap-3"><Button type="button" disabled={!data || busy} onClick={() => void publish()}>{busy ? '发布中…' : '发布价格版本'}</Button><Button type="button" variant="outline" disabled={busy} onClick={() => void load()}>重新加载</Button>{data?.active_version && <Button type="button" variant="outline" disabled={busy} onClick={() => void toggle()}>{data.enabled ? '停用新任务固定计费' : '启用固定计费'}</Button>}</div>
- </section>
+ return <SettingsPanel title="图片与视频价格" description="图片按张收费,视频按提交秒数收费。本区独立发布,修改支付配置不会发布价格。">
+ <div className="admin-form-notice">{data?.active_version ? `当前价格版本 #${data.active_version} · ${data.enabled ? "固定计费已启用" : "固定计费已停用"}` : "尚未发布价格版本"}{dirty ? " · 有未发布修改" : ""}</div>
+ <p className="settings-price-note">单价使用人民币,最多 4 位小数。留空表示该档位不可生成;视频总价 = 单价 × 提交秒数。</p>
+ {error ? <p role="alert" className="admin-field-error">{error}</p> : null}
+ {notice ? <p role="status" className="settings-price-note">{notice}</p> : null}
+ {!data && !error ? <p className="settings-price-note" role="status">正在加载价格…</p> : null}
+ {data && ["image", "video"].map(kind => <details key={kind} className="settings-advanced mt-4" open={kind === "image" ? true : undefined}>
+ <summary>{kind === "image" ? "图片价格 · 元 / 张" : "视频价格 · 元 / 秒"}</summary>
+ <div className="settings-price-table admin-table-wrap"><table><thead><tr><th>模型 / 支持范围</th><th>分辨率与单价</th></tr></thead><tbody>
+ {data.strategies.filter(strategy => strategy.capability === kind).map(strategy => <tr key={strategy.id}>
+ <td><strong className="text-xs">{strategy.id}</strong><p className="settings-price-note">{strategy.duration_max ? `${strategy.duration_min}–${strategy.duration_max} 秒` : "按成功交付张数计费"}</p></td>
+ <td><div className="settings-price-cell">{strategy.allowed_resolutions.map(resolution => {
+ const value = data.prices[strategy.id]?.[resolution] ?? "";
+ return <AdminField key={resolution} label={resolution} error={priceError(value)} hint={value ? `元 / ${kind === "image" ? "张" : "秒"}` : "未配置,不可生成"}>
+ <Input type="text" inputMode="decimal" disabled={busy} aria-label={`${strategy.id} ${resolution} 单价`} placeholder="未配置" value={value}
+ onChange={event => { setNotice(""); setData({ ...data, prices: { ...data.prices, [strategy.id]: { ...data.prices[strategy.id], [resolution]: event.target.value } } }); }} />
+ </AdminField>;
+ })}</div></td>
+ </tr>)}
+ </tbody></table></div>
+ </details>)}
+ <div className="settings-price-actions">
+ <Button disabled={!data || busy || invalidPrices} onClick={() => void publish()}>{operation === "publish" ? "发布中…" : "发布价格版本"}</Button>
+ <Button variant="outline" disabled={busy} onClick={() => void reload()}>{operation === "load" ? "加载中…" : dirty ? "放弃修改并重载" : "重新加载"}</Button>
+ {data?.active_version ? <Button variant="outline" disabled={busy} onClick={() => void toggle()}>{operation === "toggle" ? "切换中…" : data.enabled ? "停用固定计费" : "启用固定计费"}</Button> : null}
+ </div>
+ </SettingsPanel>;
}
diff --git a/admin/src/components/settings/OssSettingsPanel.tsx b/admin/src/components/settings/OssSettingsPanel.tsx
index 80678c5..394269a 100644
--- a/admin/src/components/settings/OssSettingsPanel.tsx
+++ b/admin/src/components/settings/OssSettingsPanel.tsx
@@ -1,16 +1,9 @@
-import { useMemo, useState } from "react";
-import {
- LabeledControl,
- SettingsLoading,
- SettingsPanel,
- SettingsStatusBar,
- SettingsTabShell,
-} from "@/components/settings/SettingsPanel";
+import { useState } from "react";
+import { LabeledControl, SettingsLoading, SettingsPanel, SettingsStatusBar, SettingsTabShell } from "@/components/settings/SettingsPanel";
import { SecretField } from "@/components/settings/SecretField";
import { Switch } from "@/components/ui/switch";
import { useAdminModelSettings } from "@/hooks/useAdminModelSettings";
-// 阿里云 OSS 存储配置
export function OssSettingsPanel() {
const { form, loading, saving, patchField, save } = useAdminModelSettings();
const [ossKeyIdInput, setOssKeyIdInput] = useState("");
@@ -18,165 +11,118 @@ export function OssSettingsPanel() {
const [clearOssId, setClearOssId] = useState(false);
const [clearOssSecret, setClearOssSecret] = useState(false);
- const ossReady = useMemo(() => {
- if (!form?.oss_enabled) return false;
- const hasCreds =
- (form.has_oss_access_key_id && !clearOssId) || ossKeyIdInput.trim().length > 0;
- const hasSecret =
- (form.has_oss_access_key_secret && !clearOssSecret) || ossKeySecretInput.trim().length > 0;
- return Boolean(form.oss_bucket && hasCreds && hasSecret);
- }, [form, clearOssId, clearOssSecret, ossKeyIdInput, ossKeySecretInput]);
-
async function handleSave() {
if (!form) return;
- await save(
- {
- oss_enabled: form.oss_enabled,
- oss_endpoint: form.oss_endpoint,
- oss_region: form.oss_region,
- oss_bucket: form.oss_bucket,
- oss_folder: form.oss_folder,
- oss_public_base: form.oss_public_base,
- oss_upload_async: form.oss_upload_async,
- oss_upload_queue: form.oss_upload_queue,
- oss_access_key_id: ossKeyIdInput.trim() || undefined,
- oss_access_key_secret: ossKeySecretInput.trim() || undefined,
- clear_oss_access_key_id: clearOssId,
- clear_oss_access_key_secret: clearOssSecret,
- },
- "存储配置已保存",
- );
+ const saved = await save({
+ oss_enabled: form.oss_enabled,
+ oss_endpoint: form.oss_endpoint.trim(),
+ oss_region: form.oss_region.trim(),
+ oss_bucket: form.oss_bucket.trim(),
+ oss_folder: form.oss_folder.trim(),
+ oss_public_base: form.oss_public_base.trim(),
+ oss_upload_async: form.oss_upload_async,
+ oss_upload_queue: form.oss_upload_queue.trim(),
+ oss_access_key_id: clearOssId ? undefined : ossKeyIdInput.trim() || undefined,
+ oss_access_key_secret: clearOssSecret ? undefined : ossKeySecretInput.trim() || undefined,
+ clear_oss_access_key_id: clearOssId,
+ clear_oss_access_key_secret: clearOssSecret,
+ }, "存储配置已保存");
+ if (!saved) return;
setOssKeyIdInput("");
setOssKeySecretInput("");
setClearOssId(false);
setClearOssSecret(false);
}
- if (loading || !form) {
- return <SettingsLoading />;
+ if (loading || !form) return <SettingsLoading />;
+
+ const endpoint = form.oss_endpoint.trim().replace(/^https?:\/\//i, "").replace(/\/$/, "");
+ const endpointError = form.oss_endpoint.trim() && !/^[a-z\d.-]+(?::\d+)?$/i.test(endpoint)
+ ? "填写 OSS 服务域名,不包含 Bucket 名称或文件路径。" : undefined;
+ const bucketError = form.oss_bucket.trim() && !/^[a-z\d-]+$/.test(form.oss_bucket.trim())
+ ? "仅使用小写字母、数字和短横线;填写名称,不填写网址。" : undefined;
+ const publicBase = form.oss_public_base.trim();
+ let publicBaseError: string | undefined;
+ if (publicBase) {
+ try {
+ const url = new URL(publicBase);
+ if (!["https:", "http:"].includes(url.protocol) || url.search || url.hash) {
+ publicBaseError = "使用 http:// 或 https:// 公网地址,不附带查询参数或锚点。";
+ }
+ } catch { publicBaseError = "填写完整访问地址,例如 https://cdn.example.com。"; }
}
+ const hasId = !clearOssId && (form.has_oss_access_key_id || Boolean(ossKeyIdInput.trim()));
+ const hasSecret = !clearOssSecret && (form.has_oss_access_key_secret || Boolean(ossKeySecretInput.trim()));
+ const ossReady = form.oss_enabled && Boolean(endpoint && !endpointError && form.oss_bucket.trim() && !bucketError && hasId && hasSecret);
+ const publicEndpoint = endpoint.replace("-internal.aliyuncs.com", ".aliyuncs.com").replace("-internal-accelerate.aliyuncs.com", ".aliyuncs.com");
+ const generatedBase = form.oss_bucket.trim() && endpoint && !endpointError && !bucketError ? `https://${form.oss_bucket.trim()}.${publicEndpoint}` : "";
+ const accessPreview = publicBase || generatedBase;
+ const folder = form.oss_folder.trim().replace(/^\/+|\/+$/g, "") || "kepu";
+
+ return <SettingsTabShell onSave={handleSave} saving={saving} saveLabel="保存存储设置">
+ <SettingsStatusBar title="存储配置状态" items={[
+ { id: "oss", label: "阿里云 OSS", ready: ossReady, readyText: "配置完整", pendingText: form.oss_enabled ? "请补全连接与凭证" : "未启用" },
+ { id: "public", label: "公网访问", ready: Boolean(accessPreview && !publicBaseError), readyText: publicBase ? "自定义地址" : "Bucket 默认地址", pendingText: "待配置" },
+ { id: "async", label: "上传方式", ready: form.oss_enabled && form.oss_upload_async, readyText: "异步上传", pendingText: form.oss_enabled ? "同步上传" : "依赖 OSS 启用" },
+ ]} extra={<span className="settings-status-extra">配置来源:{form.source === "db" ? "管理端" : "环境变量"}</span>} />
- return (
- <SettingsTabShell onSave={() => void handleSave()} saving={saving}>
- <SettingsStatusBar
- title="存储就绪状态"
- items={[
- {
- id: "oss",
- label: "阿里云 OSS",
- ready: ossReady,
- readyText: "已就绪",
- pendingText: form.oss_enabled ? "凭证不完整" : "未启用",
- },
- {
- id: "async",
- label: "异步上传",
- ready: form.oss_upload_async,
- readyText: "已开启",
- pendingText: "已关闭",
- },
- ]}
- extra={
- <span className="settings-status-extra">
- 配置来源:{form.source === "db" ? "管理端" : "环境变量"}
- </span>
- }
- />
+ <SettingsPanel title="存储连接" description="Endpoint 决定上传到哪里,Bucket 是存储空间名称。未启用时也可提前保存连接信息。">
+ <div className="settings-toggle-row">
+ <div><strong>启用阿里云 OSS</strong><span>开启后上传生成文件;关闭后使用本地静态目录。</span></div>
+ <Switch aria-label="启用阿里云 OSS" checked={form.oss_enabled} onCheckedChange={(value) => patchField("oss_enabled", value)} />
+ </div>
+ <div className="settings-field-grid mt-5">
+ <LabeledControl label="服务域名 Endpoint" required={form.oss_enabled} error={endpointError} hint="如 oss-cn-beijing.aliyuncs.com;不要填写 Bucket 访问地址。">
+ <input className="settings-input" placeholder="oss-cn-beijing.aliyuncs.com" value={form.oss_endpoint} onChange={(event) => patchField("oss_endpoint", event.target.value)} autoCapitalize="none" spellCheck={false} />
+ </LabeledControl>
+ <LabeledControl label="存储空间 Bucket" required={form.oss_enabled} error={bucketError} hint="与 OSS 控制台名称一致,例如 printfilm-media。">
+ <input className="settings-input" placeholder="printfilm-media" value={form.oss_bucket} onChange={(event) => patchField("oss_bucket", event.target.value)} autoCapitalize="none" spellCheck={false} maxLength={63} />
+ </LabeledControl>
+ <LabeledControl label="地域 Region" optional hint="如 cn-beijing,应与 Endpoint 所属地域一致。">
+ <input className="settings-input" placeholder="cn-beijing" value={form.oss_region} onChange={(event) => patchField("oss_region", event.target.value)} autoCapitalize="none" spellCheck={false} />
+ </LabeledControl>
+ <LabeledControl label="文件目录前缀" optional hint="不含域名;例如 kepu。留空使用默认目录 kepu。">
+ <input className="settings-input" placeholder="kepu" value={form.oss_folder} onChange={(event) => patchField("oss_folder", event.target.value)} spellCheck={false} />
+ </LabeledControl>
+ </div>
+ </SettingsPanel>
+
+ <SettingsPanel title="访问凭证" description="只接收新凭证,不显示已有密钥。启用 OSS 时需要完整的 AccessKey ID 和 Secret。">
+ <div className="settings-field-grid">
+ <SecretField label="AccessKey ID" placeholder="输入 AccessKey ID" value={ossKeyIdInput} configured={form.has_oss_access_key_id} required={form.oss_enabled}
+ clearPending={clearOssId} onUndoClear={() => setClearOssId(false)}
+ error={form.oss_enabled && clearOssId ? "请先关闭 OSS 再清除凭证,或撤销清除。" : undefined}
+ onChange={(value) => { setOssKeyIdInput(value); setClearOssId(false); }} onClear={() => setClearOssId(true)} />
+ <SecretField label="AccessKey Secret" placeholder="输入 AccessKey Secret" value={ossKeySecretInput} configured={form.has_oss_access_key_secret} required={form.oss_enabled}
+ clearPending={clearOssSecret} onUndoClear={() => setClearOssSecret(false)}
+ error={form.oss_enabled && clearOssSecret ? "请先关闭 OSS 再清除凭证,或撤销清除。" : undefined}
+ onChange={(value) => { setOssKeySecretInput(value); setClearOssSecret(false); }} onClear={() => setClearOssSecret(true)} />
+ </div>
+ </SettingsPanel>
+
+ <SettingsPanel title="公网访问与 CDN" description="浏览器通过这个地址预览和下载媒体;它与上传使用的 Endpoint 分开配置。">
+ <LabeledControl label="自定义访问地址" optional error={publicBaseError} hint="绑定 CDN 或自定义域名时填写完整 https:// 地址;留空使用 Bucket 的公网地址。">
+ <input className="settings-input" type="url" placeholder="https://cdn.example.com" value={form.oss_public_base} onChange={(event) => patchField("oss_public_base", event.target.value)} autoCapitalize="none" spellCheck={false} />
+ </LabeledControl>
+ <div className="admin-form-preview mt-4" aria-live="polite">
+ <strong>媒体访问路径预览</strong>
+ <div className="mt-1 break-all font-mono">{accessPreview && !publicBaseError ? `${accessPreview.replace(/\/$/, "")}/${folder}/generated/…` : "填写 Endpoint 与 Bucket 后显示默认访问路径。"}</div>
+ </div>
+ </SettingsPanel>
- <div className="settings-routing-grid">
- <SettingsPanel
- className="settings-panel--compact"
- title="1. 阿里云 OSS"
- description="生成文件先落本地,再异步上传 OSS"
- >
- <div className="settings-toggle-row">
- <div>
- <strong>启用 OSS</strong>
- <span>关闭后仅使用本地静态目录</span>
- </div>
- <Switch checked={form.oss_enabled} onCheckedChange={(v) => patchField("oss_enabled", v)} />
- </div>
- <div className="settings-field-grid mt-3">
- <LabeledControl label="Endpoint">
- <input
- className="settings-input"
- placeholder="oss-cn-beijing.aliyuncs.com"
- value={form.oss_endpoint}
- onChange={(e) => patchField("oss_endpoint", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="Region">
- <input
- className="settings-input"
- placeholder="cn-hangzhou"
- value={form.oss_region}
- onChange={(e) => patchField("oss_region", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="Bucket">
- <input
- className="settings-input"
- value={form.oss_bucket}
- onChange={(e) => patchField("oss_bucket", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="目录前缀">
- <input
- className="settings-input"
- placeholder="kepu"
- value={form.oss_folder}
- onChange={(e) => patchField("oss_folder", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl
- label="公网访问基址"
- hint="留空则自动拼 https://{bucket}.{endpoint}"
- className="settings-field-span-full"
- >
- <input
- className="settings-input"
- placeholder="https://cdn.example.com"
- value={form.oss_public_base}
- onChange={(e) => patchField("oss_public_base", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="上传队列名">
- <input
- className="settings-input"
- value={form.oss_upload_queue}
- onChange={(e) => patchField("oss_upload_queue", e.target.value)}
- />
- </LabeledControl>
- <SecretField
- label="AccessKey ID"
- value={ossKeyIdInput}
- configured={form.has_oss_access_key_id && !clearOssId}
- onChange={setOssKeyIdInput}
- onClear={() => {
- setOssKeyIdInput("");
- setClearOssId(true);
- }}
- />
- <SecretField
- label="AccessKey Secret"
- value={ossKeySecretInput}
- configured={form.has_oss_access_key_secret && !clearOssSecret}
- onChange={setOssKeySecretInput}
- onClear={() => {
- setOssKeySecretInput("");
- setClearOssSecret(true);
- }}
- />
- </div>
- <div className="settings-toggle-row mt-3">
- <div>
- <strong>异步上传</strong>
- <span>先返回本地 URL,后台队列上传 OSS</span>
- </div>
- <Switch checked={form.oss_upload_async} onCheckedChange={(v) => patchField("oss_upload_async", v)} />
- </div>
- </SettingsPanel>
+ <details className="settings-advanced">
+ <summary>高级上传选项 · 上传方式与队列</summary>
+ <div>
+ <div className="settings-toggle-row">
+ <div><strong>异步上传</strong><span>{form.oss_enabled ? "先返回本地 URL,再由后台队列上传;关闭时同步上传。" : "先启用 OSS 后可调整上传方式。"}</span></div>
+ <Switch aria-label="启用异步上传" checked={form.oss_upload_async} disabled={!form.oss_enabled} onCheckedChange={(value) => patchField("oss_upload_async", value)} />
+ </div>
+ <div className="settings-field-grid mt-5">
+ <LabeledControl label="上传队列名称" required={form.oss_enabled && form.oss_upload_async} hint="仅异步上传使用;保留与本地 Worker 配置一致的队列名称。">
+ <input className="settings-input" placeholder="例如 oss_upload" value={form.oss_upload_queue} disabled={!form.oss_enabled || !form.oss_upload_async} onChange={(event) => patchField("oss_upload_queue", event.target.value)} spellCheck={false} />
+ </LabeledControl>
+ </div>
</div>
- </SettingsTabShell>
- );
+ </details>
+ </SettingsTabShell>;
}
diff --git a/admin/src/components/settings/PaymentSettingsPanel.tsx b/admin/src/components/settings/PaymentSettingsPanel.tsx
index d34794e..734ec92 100644
--- a/admin/src/components/settings/PaymentSettingsPanel.tsx
+++ b/admin/src/components/settings/PaymentSettingsPanel.tsx
@@ -1,372 +1,217 @@
-import { useMemo, useState } from "react";
-import {
- LabeledControl,
- SettingsLoading,
- SettingsPanel,
- SettingsStatusBar,
- SettingsTabShell,
-} from "@/components/settings/SettingsPanel";
+import { useState, type ChangeEvent } from "react";
+import { LabeledControl, SettingsLoading, SettingsPanel, SettingsStatusBar, SettingsTabShell } from "@/components/settings/SettingsPanel";
import { SecretField } from "@/components/settings/SecretField";
import { Switch } from "@/components/ui/switch";
import { useAdminModelSettings } from "@/hooks/useAdminModelSettings";
import { MediaPriceSettings } from "./MediaPriceSettings";
-// 易支付与 Token 计费配置
+const RATE_FIELDS = [
+ { key: "billing_llm_per_m", label: "文字 LLM", unit: "元 / 百万 Token" },
+ { key: "billing_tts_per_m", label: "TTS 语音", unit: "元 / 百万 Token" },
+ { key: "billing_seedream_per_m", label: "Seedream 生图(兼容规则)", unit: "元 / 百万 Token" },
+ { key: "billing_seedance_video0", label: "Seedance video0(兼容规则)", unit: "元 / 百万 Token" },
+ { key: "billing_seedance_video1", label: "Seedance video1(兼容规则)", unit: "元 / 百万 Token" },
+ { key: "billing_kie_fen_per_credit", label: "KIE 积分换算", unit: "分 / Credit" },
+] as const;
+const ESTIMATE_FIELDS = [
+ { key: "billing_est_llm_tokens", label: "文字 LLM", unit: "Token / 次" },
+ { key: "billing_est_seedream_tokens", label: "Seedream 生图", unit: "Token / 次" },
+ { key: "billing_est_tts_tokens", label: "TTS 语音", unit: "Token / 次" },
+ { key: "billing_est_seedance_tokens_per_sec", label: "Seedance 视频", unit: "Token / 秒" },
+] as const;
+type NumericKey = typeof RATE_FIELDS[number]["key"] | typeof ESTIMATE_FIELDS[number]["key"]
+ | "billing_estimate_buffer" | "billing_signup_grant_fen" | "billing_user_alert_interval_fen"
+ | "smtp_port";
+
export function PaymentSettingsPanel() {
const { form, loading, saving, patchField, save } = useAdminModelSettings();
const [epayKeyInput, setEpayKeyInput] = useState("");
const [clearEpayKey, setClearEpayKey] = useState(false);
const [smtpPasswordInput, setSmtpPasswordInput] = useState("");
const [clearSmtpPassword, setClearSmtpPassword] = useState(false);
-
- const epayReady = useMemo(() => {
- if (!form) return false;
- const hasKey = (form.has_epay_key && !clearEpayKey) || epayKeyInput.trim().length > 0;
- return Boolean(form.epay_pid && form.epay_api_url && hasKey);
- }, [form, clearEpayKey, epayKeyInput]);
-
-
- const smtpReady = useMemo(() => {
- if (!form?.smtp_enabled) return false;
- const hasPass = (form.has_smtp_password && !clearSmtpPassword) || smtpPasswordInput.trim().length > 0;
- return Boolean(form.smtp_host && form.smtp_from && hasPass);
- }, [form, clearSmtpPassword, smtpPasswordInput]);
+ const [numericDrafts, setNumericDrafts] = useState<Partial<Record<NumericKey, string>>>({});
+
+ function numericControl(key: NumericKey) {
+ return {
+ value: numericDrafts[key] ?? String(form?.[key] ?? ""),
+ onChange: (event: ChangeEvent<HTMLInputElement>) => {
+ const raw = event.target.value;
+ setNumericDrafts((previous) => ({ ...previous, [key]: raw }));
+ if (raw.trim() && Number.isFinite(Number(raw))) patchField(key, Number(raw));
+ },
+ };
+ }
async function handleSave() {
if (!form) return;
- await save(
- {
- epay_api_url: form.epay_api_url,
- epay_pid: form.epay_pid,
- epay_key: epayKeyInput.trim() || undefined,
- clear_epay_key: clearEpayKey,
- epay_notify_url: form.epay_notify_url,
- epay_return_url: form.epay_return_url,
- billing_enabled: form.billing_enabled,
- billing_markup: 1.0,
- billing_estimate_buffer: form.billing_estimate_buffer,
- billing_seedance_video0: form.billing_seedance_video0,
- billing_seedance_video1: form.billing_seedance_video1,
- billing_llm_per_m: form.billing_llm_per_m,
- billing_seedream_per_m: form.billing_seedream_per_m,
- billing_tts_per_m: form.billing_tts_per_m,
- billing_kie_fen_per_credit: form.billing_kie_fen_per_credit,
- billing_est_llm_tokens: form.billing_est_llm_tokens,
- billing_est_seedream_tokens: form.billing_est_seedream_tokens,
- billing_est_tts_tokens: form.billing_est_tts_tokens,
- billing_est_seedance_tokens_per_sec: form.billing_est_seedance_tokens_per_sec,
- billing_signup_grant_fen: form.billing_signup_grant_fen,
- billing_user_alert_enabled: form.billing_user_alert_enabled,
- billing_user_alert_interval_fen: form.billing_user_alert_interval_fen,
- smtp_enabled: form.smtp_enabled,
- smtp_host: form.smtp_host,
- smtp_port: form.smtp_port,
- smtp_user: form.smtp_user,
- smtp_password: smtpPasswordInput.trim() || undefined,
- clear_smtp_password: clearSmtpPassword,
- smtp_from: form.smtp_from,
- smtp_use_tls: form.smtp_use_tls,
- },
- "支付与计费已保存",
- );
+ const saved = await save({
+ epay_api_url: form.epay_api_url.trim(),
+ epay_pid: form.epay_pid.trim(),
+ epay_key: clearEpayKey ? undefined : epayKeyInput.trim() || undefined,
+ clear_epay_key: clearEpayKey,
+ epay_notify_url: form.epay_notify_url.trim(),
+ epay_return_url: form.epay_return_url.trim(),
+ billing_enabled: form.billing_enabled,
+ billing_markup: 1.0,
+ billing_estimate_buffer: form.billing_estimate_buffer,
+ billing_seedance_video0: form.billing_seedance_video0,
+ billing_seedance_video1: form.billing_seedance_video1,
+ billing_llm_per_m: form.billing_llm_per_m,
+ billing_seedream_per_m: form.billing_seedream_per_m,
+ billing_tts_per_m: form.billing_tts_per_m,
+ billing_kie_fen_per_credit: form.billing_kie_fen_per_credit,
+ billing_est_llm_tokens: form.billing_est_llm_tokens,
+ billing_est_seedream_tokens: form.billing_est_seedream_tokens,
+ billing_est_tts_tokens: form.billing_est_tts_tokens,
+ billing_est_seedance_tokens_per_sec: form.billing_est_seedance_tokens_per_sec,
+ billing_signup_grant_fen: form.billing_signup_grant_fen,
+ billing_user_alert_enabled: form.billing_user_alert_enabled,
+ billing_user_alert_interval_fen: form.billing_user_alert_interval_fen,
+ smtp_enabled: form.smtp_enabled,
+ smtp_host: form.smtp_host.trim(),
+ smtp_port: form.smtp_port,
+ smtp_user: form.smtp_user.trim(),
+ smtp_password: clearSmtpPassword ? undefined : smtpPasswordInput.trim() || undefined,
+ clear_smtp_password: clearSmtpPassword,
+ smtp_from: form.smtp_from.trim(),
+ smtp_use_tls: form.smtp_use_tls,
+ }, "支付、计费与通知设置已保存");
+ if (!saved) return;
setEpayKeyInput("");
setClearEpayKey(false);
setSmtpPasswordInput("");
setClearSmtpPassword(false);
+ setNumericDrafts({});
}
-
- if (loading || !form) {
- return <SettingsLoading />;
- }
-
- return (
- <SettingsTabShell onSave={() => void handleSave()} saving={saving}>
- <MediaPriceSettings />
- <SettingsStatusBar
- title="支付就绪状态"
- items={[
- {
- id: "epay",
- label: "易支付",
- ready: epayReady,
- readyText: "已配置",
- pendingText: "未完整",
- },
- {
- id: "billing",
- label: "Token 计费",
- ready: form.billing_enabled,
- readyText: "已开启",
- pendingText: "已关闭",
- },
- {
- id: "smtp",
- label: "SMTP",
- ready: smtpReady,
- readyText: "已配置",
- pendingText: form.smtp_enabled ? "不完整" : "未启用",
- },
- ]}
- />
-
- <div className="settings-routing-grid">
- <SettingsPanel
- className="settings-panel--compact"
- title="1. 易支付 Epay"
- description="生产回调请用 /epay/notify,勿含 /api/"
- >
- <div className="settings-field-grid">
- <LabeledControl label="网关地址">
- <input
- className="settings-input"
- placeholder="https://pay.gitcc.com"
- value={form.epay_api_url}
- onChange={(e) => patchField("epay_api_url", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="商户 PID">
- <input
- className="settings-input"
- value={form.epay_pid}
- onChange={(e) => patchField("epay_pid", e.target.value)}
- />
- </LabeledControl>
- <SecretField
- label="商户密钥"
- value={epayKeyInput}
- configured={form.has_epay_key && !clearEpayKey}
- onChange={setEpayKeyInput}
- onClear={() => {
- setEpayKeyInput("");
- setClearEpayKey(true);
- }}
- />
- <LabeledControl label="异步通知 URL" hint="生产:{域名}/epay/notify" className="settings-field-span-full">
- <input
- className="settings-input"
- value={form.epay_notify_url}
- onChange={(e) => patchField("epay_notify_url", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="同步跳转 URL" className="settings-field-span-full">
- <input
- className="settings-input"
- value={form.epay_return_url}
- onChange={(e) => patchField("epay_return_url", e.target.value)}
- />
- </LabeledControl>
- </div>
- </SettingsPanel>
-
- <SettingsPanel
- className="settings-panel--compact"
- title="2. Token 计费"
- description="图视频发布价格后按站内价格收费;LLM、TTS 沿用现有规则。"
- >
- <div className="settings-toggle-row">
- <div>
- <strong>启用 Token 计费</strong>
- <span>关闭后生成不扣余额</span>
- </div>
- <Switch checked={form.billing_enabled} onCheckedChange={(v) => patchField("billing_enabled", v)} />
- </div>
- <div className="settings-field-grid mt-3">
- <LabeledControl label="预估缓冲系数">
- <input
- className="settings-input"
- type="number"
- step="0.1"
- min={1}
- value={form.billing_estimate_buffer}
- onChange={(e) => patchField("billing_estimate_buffer", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="注册赠送(分)">
- <input
- className="settings-input"
- type="number"
- min={0}
- value={form.billing_signup_grant_fen}
- onChange={(e) => patchField("billing_signup_grant_fen", Number(e.target.value))}
- />
- </LabeledControl>
- </div>
-
- <div className="settings-subsection-title">单价(元 / 百万 token)</div>
+ if (loading || !form) return <SettingsLoading />;
+
+ const hasEpayKey = !clearEpayKey && (form.has_epay_key || Boolean(epayKeyInput.trim()));
+ const epayInUse = Boolean(form.epay_pid.trim() || hasEpayKey);
+ const epayReady = Boolean(form.epay_api_url.trim() && form.epay_pid.trim() && hasEpayKey);
+ const hasSmtpPassword = !clearSmtpPassword && (form.has_smtp_password || Boolean(smtpPasswordInput.trim()));
+ const smtpNeedsPassword = form.smtp_enabled && Boolean(form.smtp_user.trim());
+ const smtpReady = form.smtp_enabled && Boolean(form.smtp_host.trim() && form.smtp_from.trim() && (!smtpNeedsPassword || hasSmtpPassword));
+ const moneyHint = (key: NumericKey) => {
+ const raw = numericDrafts[key] ?? form[key];
+ return raw === "" ? "请输入以分为单位的金额。" : `当前金额 ¥${(Number(raw) / 100).toFixed(2)};100 分 = 1 元。`;
+ };
+
+ return <div className="space-y-5">
+ <SettingsTabShell onSave={handleSave} saving={saving} saveLabel="保存支付与通知设置">
+ <SettingsStatusBar title="支付与通知状态" items={[
+ { id: "epay", label: "易支付", ready: epayReady, readyText: "配置完整", pendingText: "未完成接入" },
+ { id: "billing", label: "余额计费", ready: form.billing_enabled, readyText: "已开启", pendingText: "已关闭" },
+ { id: "smtp", label: "邮件发送", ready: smtpReady, readyText: "配置完整", pendingText: form.smtp_enabled ? "请补全 SMTP" : "未启用" },
+ ]} />
+
+ <SettingsPanel title="支付接入" description="配置易支付收款。已有商户密钥不回显,输入新密钥后保存即可替换。">
+ <div className="settings-field-grid">
+ <LabeledControl label="支付网关地址" required={epayInUse} hint="填写服务商提供的完整网关地址,例如 https://pay.example.com。">
+ <input className="settings-input" type="url" placeholder="https://pay.example.com" value={form.epay_api_url} onChange={(event) => patchField("epay_api_url", event.target.value)} autoCapitalize="none" spellCheck={false} />
+ </LabeledControl>
+ <LabeledControl label="商户编号 PID" required={epayInUse} hint="易支付控制台中的商户编号。">
+ <input className="settings-input" placeholder="例如 10001" value={form.epay_pid} onChange={(event) => patchField("epay_pid", event.target.value)} autoCapitalize="none" spellCheck={false} />
+ </LabeledControl>
+ <SecretField label="商户密钥" value={epayKeyInput} configured={form.has_epay_key} required={epayInUse}
+ clearPending={clearEpayKey} onUndoClear={() => setClearEpayKey(false)}
+ onChange={(value) => { setEpayKeyInput(value); setClearEpayKey(false); }} onClear={() => setClearEpayKey(true)} />
+ </div>
+ <details className="settings-advanced mt-5">
+ <summary>高级接入 · 回调与支付完成页</summary>
<div className="settings-field-grid">
- <LabeledControl label="LLM">
- <input
- className="settings-input"
- type="number"
- step="0.1"
- value={form.billing_llm_per_m}
- onChange={(e) => patchField("billing_llm_per_m", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="Seedream 生图">
- <input
- className="settings-input"
- type="number"
- step="0.1"
- value={form.billing_seedream_per_m}
- onChange={(e) => patchField("billing_seedream_per_m", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="TTS 语音">
- <input
- className="settings-input"
- type="number"
- step="0.1"
- value={form.billing_tts_per_m}
- onChange={(e) => patchField("billing_tts_per_m", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="Seedance video0">
- <input
- className="settings-input"
- type="number"
- step="0.1"
- value={form.billing_seedance_video0}
- onChange={(e) => patchField("billing_seedance_video0", Number(e.target.value))}
- />
+ <LabeledControl label="异步通知地址" optional hint="生产示例:https://www.example.com/epay/notify,路径不包含 /api/。">
+ <input className="settings-input" type="url" placeholder="https://www.example.com/epay/notify" value={form.epay_notify_url} onChange={(event) => patchField("epay_notify_url", event.target.value)} autoCapitalize="none" spellCheck={false} />
</LabeledControl>
- <LabeledControl label="Seedance video1">
- <input
- className="settings-input"
- type="number"
- step="0.1"
- value={form.billing_seedance_video1}
- onChange={(e) => patchField("billing_seedance_video1", Number(e.target.value))}
- />
+ <LabeledControl label="支付完成跳转地址" optional hint="用户支付完成后返回的页面,填写完整 http:// 或 https:// 地址。">
+ <input className="settings-input" type="url" placeholder="https://www.example.com/settings" value={form.epay_return_url} onChange={(event) => patchField("epay_return_url", event.target.value)} autoCapitalize="none" spellCheck={false} />
</LabeledControl>
</div>
-
-
- <div className="settings-subsection-title">估算 token(缺 usage 时)</div>
- <div className="settings-field-grid">
- <LabeledControl label="LLM 估算">
- <input
- className="settings-input"
- type="number"
- value={form.billing_est_llm_tokens}
- onChange={(e) => patchField("billing_est_llm_tokens", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="Seedream 估算">
- <input
- className="settings-input"
- type="number"
- value={form.billing_est_seedream_tokens}
- onChange={(e) => patchField("billing_est_seedream_tokens", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="TTS 估算">
- <input
- className="settings-input"
- type="number"
- value={form.billing_est_tts_tokens}
- onChange={(e) => patchField("billing_est_tts_tokens", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="Seedance token/秒">
- <input
- className="settings-input"
- type="number"
- value={form.billing_est_seedance_tokens_per_sec}
- onChange={(e) => patchField("billing_est_seedance_tokens_per_sec", Number(e.target.value))}
- />
- </LabeledControl>
+ </details>
+ </SettingsPanel>
+
+ <SettingsPanel title="余额与计费" description="控制生成扣费及新用户赠送。图片与视频价格在下方单独发布,不随本表单保存。">
+ <div className="settings-toggle-row">
+ <div><strong>启用余额计费</strong><span>开启后按规则扣除用户余额;关闭后生成不扣余额。</span></div>
+ <Switch aria-label="启用余额计费" checked={form.billing_enabled} onCheckedChange={(value) => patchField("billing_enabled", value)} />
+ </div>
+ <div className="settings-field-grid mt-5">
+ <LabeledControl label="注册赠送金额(分)" required hint={moneyHint("billing_signup_grant_fen")}>
+ <input className="settings-input" type="number" min={0} step={1} placeholder="0" {...numericControl("billing_signup_grant_fen")} />
+ </LabeledControl>
+ </div>
+ <details className="settings-advanced mt-5">
+ <summary>高级计费 · Token 单价、冻结缓冲与缺省估算</summary>
+ <div>
+ <p className="settings-runtime-note">图视频发布并启用站内价格后优先使用发布价格;下方兼容单价仅用于仍采用原计费规则的调用。LLM、TTS 继续使用 Token 规则。</p>
+ <fieldset className="m-0 min-w-0 border-0 p-0" disabled={!form.billing_enabled}>
+ <div className="settings-subsection-title">Token 单价与积分换算</div>
+ <div className="settings-field-grid">
+ {RATE_FIELDS.map((field) => <LabeledControl key={field.key} label={field.label} required={form.billing_enabled} hint={field.unit}>
+ <input className="settings-input" type="number" min={0} step="any" {...numericControl(field.key)} />
+ </LabeledControl>)}
+ </div>
+ <div className="settings-subsection-title">任务预估</div>
+ <div className="settings-field-grid">
+ <LabeledControl label="冻结缓冲系数(倍)" required={form.billing_enabled} hint="最低 1;例如 1.2 表示在预估费用上预留 20%。">
+ <input className="settings-input" type="number" min={1} step="0.01" {...numericControl("billing_estimate_buffer")} />
+ </LabeledControl>
+ {ESTIMATE_FIELDS.map((field) => <LabeledControl key={field.key} label={`${field.label} 缺省用量`} required={form.billing_enabled} hint={`${field.unit};上游未返回 usage 时使用。`}>
+ <input className="settings-input" type="number" min={1} step={1} {...numericControl(field.key)} />
+ </LabeledControl>)}
+ </div>
+ </fieldset>
+ {!form.billing_enabled && <p className="settings-panel-footnote">余额计费已关闭;开启后可调整上述规则,现有数值保留。</p>}
</div>
- </SettingsPanel>
- </div>
-
- <div className="settings-routing-grid">
- <SettingsPanel
- className="settings-panel--compact"
- title="3. 额度告警与 SMTP"
- description="用户消费提醒与邮件发送"
- >
+ </details>
+ </SettingsPanel>
+
+ <SettingsPanel title="消费提醒" description="用户累计消费达到设置的间隔金额时,在产品内展示提醒。">
+ <div className="settings-toggle-row">
+ <div><strong>用户消费弹窗提醒</strong><span>累计扣费达到间隔档位时提醒,每笔结算最多弹出一次。</span></div>
+ <Switch aria-label="用户消费弹窗提醒" checked={form.billing_user_alert_enabled} disabled={!form.billing_enabled} onCheckedChange={(value) => patchField("billing_user_alert_enabled", value)} />
+ </div>
+ <div className="settings-field-grid mt-5">
+ <LabeledControl label="消费提醒间隔(分)" required={form.billing_enabled && form.billing_user_alert_enabled} hint={form.billing_enabled ? moneyHint("billing_user_alert_interval_fen") : "需先启用余额计费;原提醒设置保留。"}>
+ <input className="settings-input" type="number" min={1} step={1} disabled={!form.billing_enabled || !form.billing_user_alert_enabled} {...numericControl("billing_user_alert_interval_fen")} />
+ </LabeledControl>
+ </div>
+ </SettingsPanel>
+
+ <details className="settings-advanced" open={form.smtp_enabled || undefined}>
+ <summary>邮件发送 SMTP · {form.smtp_enabled ? "已启用" : "未启用,点击配置"}</summary>
+ <SettingsPanel title="邮件发送" description="用于密码重置、团队邀请等邮件。使用邮箱服务商的 SMTP 服务及授权码;停用时保留已有配置。">
<div className="settings-toggle-row">
- <div>
- <strong>用户弹窗提醒</strong>
- <span>累计扣费达间隔档位时弹一次(跨多档也不连弹)</span>
- </div>
- <Switch
- checked={form.billing_user_alert_enabled}
- onCheckedChange={(v) => patchField("billing_user_alert_enabled", v)}
- />
- </div>
- <div className="settings-field-grid mt-2">
- <LabeledControl label="提醒间隔(分)" hint="10000 = ¥100;每笔结算最多弹一次">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.billing_user_alert_interval_fen}
- onChange={(e) => patchField("billing_user_alert_interval_fen", Number(e.target.value))}
- />
- </LabeledControl>
- </div>
-
-
- <div className="settings-toggle-row mt-3">
- <div>
- <strong>启用 SMTP</strong>
- <span>邮件发送依赖 SMTP</span>
- </div>
- <Switch checked={form.smtp_enabled} onCheckedChange={(v) => patchField("smtp_enabled", v)} />
+ <div><strong>启用 SMTP 邮件发送</strong><span>开启并保存配置后,可发送密码重置、团队邀请等邮件。</span></div>
+ <Switch aria-label="启用 SMTP 邮件发送" checked={form.smtp_enabled} onCheckedChange={(value) => patchField("smtp_enabled", value)} />
</div>
- <div className="settings-field-grid mt-2">
- <LabeledControl label="SMTP 主机">
- <input
- className="settings-input"
- placeholder="smtp.example.com"
- value={form.smtp_host}
- onChange={(e) => patchField("smtp_host", e.target.value)}
- />
+ <div className="settings-field-grid mt-5">
+ <LabeledControl label="SMTP 服务器" required={form.smtp_enabled} hint="仅填写主机名,不含 https://,例如 smtp.example.com。">
+ <input className="settings-input" disabled={!form.smtp_enabled} placeholder="smtp.example.com" value={form.smtp_host} onChange={(event) => patchField("smtp_host", event.target.value)} autoCapitalize="none" spellCheck={false} pattern="[^/:\s]+" />
</LabeledControl>
- <LabeledControl label="端口">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.smtp_port}
- onChange={(e) => patchField("smtp_port", Number(e.target.value))}
- />
+ <LabeledControl label="SMTP 端口" required={form.smtp_enabled} hint="1–65535;587 常用于 STARTTLS,465 使用隐式 SSL。">
+ <input className="settings-input" type="number" disabled={!form.smtp_enabled} min={1} max={65535} step={1} placeholder="587" {...numericControl("smtp_port")} />
</LabeledControl>
- <LabeledControl label="发件人">
- <input
- className="settings-input"
- value={form.smtp_from}
- onChange={(e) => patchField("smtp_from", e.target.value)}
- />
+ <LabeledControl label="发件人地址" required={form.smtp_enabled} hint="收件人看到的邮箱地址,例如 [email protected]。">
+ <input className="settings-input" type="email" disabled={!form.smtp_enabled} placeholder="[email protected]" value={form.smtp_from} onChange={(event) => patchField("smtp_from", event.target.value)} autoCapitalize="none" spellCheck={false} />
</LabeledControl>
- <LabeledControl label="用户名">
- <input
- className="settings-input"
- value={form.smtp_user}
- onChange={(e) => patchField("smtp_user", e.target.value)}
- />
+ <LabeledControl label="SMTP 登录用户名" optional hint="服务商要求认证时填写,通常与发件邮箱相同;免认证中继可留空。">
+ <input className="settings-input" disabled={!form.smtp_enabled} placeholder="[email protected]" value={form.smtp_user} onChange={(event) => patchField("smtp_user", event.target.value)} autoCapitalize="none" spellCheck={false} />
</LabeledControl>
- <SecretField
- label="SMTP 密码"
- value={smtpPasswordInput}
- configured={form.has_smtp_password && !clearSmtpPassword}
- onChange={setSmtpPasswordInput}
- onClear={() => {
- setSmtpPasswordInput("");
- setClearSmtpPassword(true);
- }}
- />
- <LabeledControl label="使用 TLS">
+ <SecretField label="SMTP 密码 / 授权码" value={smtpPasswordInput} configured={form.has_smtp_password} required={smtpNeedsPassword}
+ clearPending={clearSmtpPassword} onUndoClear={() => setClearSmtpPassword(false)}
+ hint="多数邮箱使用 SMTP 授权码;停用时也可更新或清除凭证。"
+ error={smtpNeedsPassword && clearSmtpPassword ? "请先停用 SMTP 或清空免认证中继的用户名,再清除密码。" : undefined}
+ onChange={(value) => { setSmtpPasswordInput(value); setClearSmtpPassword(false); }} onClear={() => setClearSmtpPassword(true)} />
+ <LabeledControl label="STARTTLS 加密" hint={[465, 8465, 2465].includes(form.smtp_port) ? "当前端口使用隐式 SSL,此开关不影响加密。" : "587 端口通常开启;具体以邮箱服务商要求为准。"}>
<div className="settings-inline-switch">
- <Switch checked={form.smtp_use_tls} onCheckedChange={(v) => patchField("smtp_use_tls", v)} />
+ <Switch aria-label="启用 SMTP STARTTLS 加密" disabled={!form.smtp_enabled || [465, 8465, 2465].includes(form.smtp_port)} checked={form.smtp_use_tls} onCheckedChange={(value) => patchField("smtp_use_tls", value)} />
</div>
</LabeledControl>
</div>
</SettingsPanel>
- </div>
+ </details>
</SettingsTabShell>
- );
+ <MediaPriceSettings />
+ </div>;
}
diff --git a/admin/src/components/settings/RuntimeSettingsPanel.tsx b/admin/src/components/settings/RuntimeSettingsPanel.tsx
index 0122662..dce2260 100644
--- a/admin/src/components/settings/RuntimeSettingsPanel.tsx
+++ b/admin/src/components/settings/RuntimeSettingsPanel.tsx
@@ -11,17 +11,27 @@ import {
} from "@/components/settings/SettingsPanel";
import { Switch } from "@/components/ui/switch";
+const NUMBER_FIELDS = [
+ "seedance_duration_min", "seedance_duration_max", "ark_video_poll_interval", "ark_video_poll_timeout",
+ "pipeline_image_concurrency", "pipeline_video_concurrency", "pipeline_audio_concurrency",
+ "task_runtime_max_concurrency", "task_user_max_concurrency", "task_poll_max_concurrency",
+ "drama_user_video_job_limit", "drama_fragment_max_attempts",
+] as const;
+type NumberField = (typeof NUMBER_FIELDS)[number];
+
// 运行参数配置(并发、质量、Mock 等 flat 字段)
export function RuntimeSettingsPanel() {
const [form, setForm] = useState<AdminModelSettings | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
+ const [numberDrafts, setNumberDrafts] = useState<Partial<Record<NumberField, string>>>({});
const load = useCallback(async () => {
setLoading(true);
try {
const data = await api<AdminModelSettings>("/api/admin/settings/models");
setForm(data);
+ setNumberDrafts({});
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载失败");
} finally {
@@ -49,8 +59,52 @@ export function RuntimeSettingsPanel() {
setForm((prev) => (prev ? { ...prev, [key]: value } : prev));
}
+ const errors: Partial<Record<NumberField | "ark_image_size" | "ark_video_resolution" | "ark_video_ratio", string>> = {};
+ if (form) {
+ NUMBER_FIELDS.forEach((key) => {
+ const raw = numberDrafts[key] ?? String(form[key]);
+ const value = Number(raw);
+ const seconds = key === "ark_video_poll_interval" || key === "ark_video_poll_timeout";
+ if (!raw.trim() || !Number.isFinite(value) || value <= 0) errors[key] = seconds ? "请输入大于 0 的秒数" : "请输入不小于 1 的整数";
+ else if (!seconds && !Number.isInteger(value)) errors[key] = "请输入整数";
+ });
+ if (!errors.seedance_duration_min && !errors.seedance_duration_max && form.seedance_duration_min > form.seedance_duration_max) {
+ errors.seedance_duration_max = "最大时长不能小于最小时长";
+ }
+ if (!errors.ark_video_poll_interval && !errors.ark_video_poll_timeout && form.ark_video_poll_timeout <= form.ark_video_poll_interval) {
+ errors.ark_video_poll_timeout = "超时应大于轮询间隔";
+ }
+ (["ark_image_size", "ark_video_resolution", "ark_video_ratio"] as const).forEach((key) => {
+ if (!form[key].trim()) errors[key] = "请填写默认值";
+ });
+ }
+ const hasErrors = Object.keys(errors).length > 0;
+
+ function numberField(key: NumberField, label: string, hint: string, unit: string) {
+ if (!form) return null;
+ const seconds = key === "ark_video_poll_interval" || key === "ark_video_poll_timeout";
+ return (
+ <LabeledControl label={label} hint={hint} error={errors[key]} required>
+ <div className="relative">
+ <input
+ className="settings-input !pr-12"
+ type="number" required min={seconds ? 0 : 1} step={seconds ? "any" : 1}
+ aria-invalid={Boolean(errors[key])}
+ value={numberDrafts[key] ?? form[key]}
+ onChange={(event) => {
+ const raw = event.target.value;
+ setNumberDrafts((prev) => ({ ...prev, [key]: raw }));
+ if (raw.trim() && Number.isFinite(Number(raw))) patchField(key, Number(raw));
+ }}
+ />
+ <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-xs text-[var(--admin-muted)]">{unit}</span>
+ </div>
+ </LabeledControl>
+ );
+ }
+
async function handleSave() {
- if (!form) return;
+ if (!form || saving || hasErrors) return;
setSaving(true);
try {
const body = {
@@ -86,7 +140,7 @@ export function RuntimeSettingsPanel() {
}
return (
- <SettingsTabShell onSave={() => void handleSave()} saving={saving}>
+ <SettingsTabShell onSave={handleSave} saving={saving} disabled={hasErrors} saveLabel="保存运行设置">
<SettingsStatusBar
title="路由就绪状态"
items={
@@ -96,180 +150,65 @@ export function RuntimeSettingsPanel() {
}
extra={
<span className="settings-status-extra">
- {form.readiness?.every((item) => item.ready) ? "四类能力已就绪" : "请在「模型」填写 TokenFree Key 并选择模型"}
+ {form.readiness?.length && form.readiness.every((item) => item.ready) ? "四类能力已就绪" : "请在「模型」填写 TokenFree Key 并选择模型"}
</span>
}
/>
- <div className="settings-routing-grid">
- <SettingsPanel
- className="settings-panel--compact"
- title="1. 质量与默认值"
- description="生图尺寸、视频清晰度、Seedance 时长与轮询"
- >
- <div className="settings-field-grid">
- <LabeledControl label="默认生图尺寸">
- <input
- className="settings-input"
- value={form.ark_image_size}
- onChange={(e) => patchField("ark_image_size", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="默认视频清晰度">
- <input
- className="settings-input"
- value={form.ark_video_resolution}
- onChange={(e) => patchField("ark_video_resolution", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="默认视频比例">
- <input
- className="settings-input"
- value={form.ark_video_ratio}
- onChange={(e) => patchField("ark_video_ratio", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="Seedance 最小时长(秒)">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.seedance_duration_min}
- onChange={(e) => patchField("seedance_duration_min", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="Seedance 最大时长(秒)">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.seedance_duration_max}
- onChange={(e) => patchField("seedance_duration_max", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="视频轮询间隔(秒)">
- <input
- className="settings-input"
- type="number"
- step="0.5"
- value={form.ark_video_poll_interval}
- onChange={(e) => patchField("ark_video_poll_interval", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="视频轮询超时(秒)">
- <input
- className="settings-input"
- type="number"
- value={form.ark_video_poll_timeout}
- onChange={(e) => patchField("ark_video_poll_timeout", Number(e.target.value))}
- />
- </LabeledControl>
- </div>
- </SettingsPanel>
+ <SettingsPanel title="生成默认值" description="设置新生成任务的默认画质、画幅和时长;具体支持范围仍由所选模型决定。">
+ <div className="settings-field-grid settings-field-grid--3">
+ <LabeledControl label="生图尺寸" hint="沿用上游支持的尺寸,例如 2K 或 1024x1024。" error={errors.ark_image_size} required>
+ <input className="settings-input" required placeholder="例如 2K" aria-invalid={Boolean(errors.ark_image_size)} value={form.ark_image_size} onChange={(e) => patchField("ark_image_size", e.target.value)} />
+ </LabeledControl>
+ <LabeledControl label="视频清晰度" hint="例如 480p、720p;以当前模型支持值为准。" error={errors.ark_video_resolution} required>
+ <input className="settings-input" required placeholder="例如 720p" aria-invalid={Boolean(errors.ark_video_resolution)} value={form.ark_video_resolution} onChange={(e) => patchField("ark_video_resolution", e.target.value)} />
+ </LabeledControl>
+ <LabeledControl label="视频画幅" hint="宽:高,例如 16:9 或 9:16。" error={errors.ark_video_ratio} required>
+ <input className="settings-input" required placeholder="例如 16:9" aria-invalid={Boolean(errors.ark_video_ratio)} value={form.ark_video_ratio} onChange={(e) => patchField("ark_video_ratio", e.target.value)} />
+ </LabeledControl>
+ </div>
+ <div className="settings-field-grid settings-field-grid--2 mt-5">
+ {numberField("seedance_duration_min", "Seedance 最小时长", "不小于 1 秒,与最大时长一起限制单段生成时长。", "秒")}
+ {numberField("seedance_duration_max", "Seedance 最大时长", "不小于最小时长;最终仍受模型时长范围限制。", "秒")}
+ </div>
+ </SettingsPanel>
+
+ <SettingsPanel title="任务并发" description="控制同时执行的任务数量,以及单个用户可占用的资源。">
+ <div className="settings-field-grid settings-field-grid--3">
+ {numberField("task_runtime_max_concurrency", "全站执行槽位", "全站可同时运行的 Worker 任务数,不小于 1。", "个")}
+ {numberField("task_user_max_concurrency", "单用户执行槽位", "单个用户可占用的任务数,仍受全站槽位约束。", "个")}
+ {numberField("drama_user_video_job_limit", "单用户漫剧视频在途上限", "限制排队与处理中的视频任务总数,不小于 1。", "个")}
+ </div>
+ <div className="settings-runtime-note mt-5">
+ <Activity className="h-4 w-4 shrink-0 text-[var(--admin-forest)]" />
+ <span>当前草稿:全站 <strong>{form.task_runtime_max_concurrency}</strong> 个执行槽位,单用户最多 <strong>{form.task_user_max_concurrency}</strong> 个;等待上游轮询的任务不占 Worker 槽位。</span>
+ </div>
+ </SettingsPanel>
- <SettingsPanel
- className="settings-panel--compact"
- title="2. 并发与限制"
- description="管线并发、任务槽位与漫剧分镜上限"
- >
- <div className="settings-field-grid">
- <LabeledControl label="生图并发">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.pipeline_image_concurrency}
- onChange={(e) => patchField("pipeline_image_concurrency", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="视频并发">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.pipeline_video_concurrency}
- onChange={(e) => patchField("pipeline_video_concurrency", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="配音并发">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.pipeline_audio_concurrency}
- onChange={(e) => patchField("pipeline_audio_concurrency", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="任务平台槽位(全站)">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.task_runtime_max_concurrency}
- onChange={(e) => patchField("task_runtime_max_concurrency", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="单用户任务槽位">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.task_user_max_concurrency}
- onChange={(e) => patchField("task_user_max_concurrency", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="Selector 轮询并发">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.task_poll_max_concurrency}
- onChange={(e) => patchField("task_poll_max_concurrency", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="单用户漫剧视频在途上限">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.drama_user_video_job_limit}
- onChange={(e) => patchField("drama_user_video_job_limit", Number(e.target.value))}
- />
- </LabeledControl>
- <LabeledControl label="分镜视频最大尝试次数">
- <input
- className="settings-input"
- type="number"
- min={1}
- value={form.drama_fragment_max_attempts}
- onChange={(e) => patchField("drama_fragment_max_attempts", Number(e.target.value))}
- />
- </LabeledControl>
+ <details className="settings-advanced">
+ <summary><span>高级运行参数</span><span>管线分配、轮询与模拟模式</span></summary>
+ <SettingsPanel title="生成管线" description="分别控制各类媒体任务的并行处理数;均为不小于 1 的整数。">
+ <div className="settings-field-grid settings-field-grid--3">
+ {numberField("pipeline_image_concurrency", "生图并发", "同时处理的图像任务数。", "路")}
+ {numberField("pipeline_video_concurrency", "视频并发", "同时处理的视频任务数。", "路")}
+ {numberField("pipeline_audio_concurrency", "配音并发", "同时处理的配音任务数。", "路")}
</div>
- <div className="settings-toggle-row mt-3">
- <div>
- <strong>ARK Mock 模式</strong>
- <span>开发环境模拟生成,不调用真实上游</span>
- </div>
- <Switch checked={form.ark_mock} onCheckedChange={(v) => patchField("ark_mock", v)} />
+ </SettingsPanel>
+ <SettingsPanel title="上游轮询与重试" description="在查询频率和等待时长之间取得平衡;超时应大于查询间隔。">
+ <div className="settings-field-grid settings-field-grid--2">
+ {numberField("ark_video_poll_interval", "视频轮询间隔", "大于 0 秒;间隔越短,上游查询频率越高。", "秒")}
+ {numberField("ark_video_poll_timeout", "视频轮询超时", "大于轮询间隔;超过此时长后结束等待。", "秒")}
+ {numberField("task_poll_max_concurrency", "每轮上游查询并发", "Selector 每轮非阻塞查询的最大路数,不小于 1。", "路")}
+ {numberField("drama_fragment_max_attempts", "分镜视频最大尝试次数", "包含首次生成与失败后的重试,不小于 1。", "次")}
</div>
</SettingsPanel>
- </div>
-
- <SettingsPanel className="settings-panel--compact" title="3. 运行时摘要" description="当前生效的 Worker / Selector 槽位">
- <div className="settings-runtime-summary">
- <div className="settings-runtime-summary-row">
- <Activity className="h-4 w-4 text-[var(--admin-forest)]" />
- <span>
- Worker 槽位 <strong>{form.task_runtime_max_concurrency}</strong> · 单用户{" "}
- <strong>{form.task_user_max_concurrency}</strong>
- </span>
+ <SettingsPanel title="开发与调试" description="切换生成请求的运行方式。">
+ <div className="settings-toggle-row">
+ <div><strong>ARK Mock 模式</strong><span>使用模拟结果调试 ARK 接口,开启后不调用对应真实上游。</span></div>
+ <Switch aria-label="ARK Mock 模式" checked={form.ark_mock} onCheckedChange={(v) => patchField("ark_mock", v)} />
</div>
- <p className="settings-runtime-summary-hint">
- Selector 每轮最多 {form.task_poll_max_concurrency} 路上游非阻塞查询;awaiting_poll 不计入 Worker 占用。
- </p>
- </div>
- </SettingsPanel>
+ </SettingsPanel>
+ </details>
</SettingsTabShell>
);
}
diff --git a/admin/src/components/settings/SecretField.tsx b/admin/src/components/settings/SecretField.tsx
index e82b9eb..33a2554 100644
--- a/admin/src/components/settings/SecretField.tsx
+++ b/admin/src/components/settings/SecretField.tsx
@@ -1,4 +1,7 @@
+import { useState } from "react";
+import { Check, Eye, EyeOff, RotateCcw, Trash2 } from "lucide-react";
import { LabeledControl } from "@/components/settings/SettingsPanel";
+import { Button } from "@/components/ui/button";
type SecretFieldProps = {
label: string;
@@ -8,9 +11,14 @@ type SecretFieldProps = {
placeholder?: string;
onChange: (value: string) => void;
onClear?: () => void;
+ clearPending?: boolean;
+ onUndoClear?: () => void;
+ disabled?: boolean;
+ required?: boolean;
+ error?: string;
};
-// 密钥输入:留空不修改,支持清除已存密钥
+// Only the new draft can be revealed; existing secrets are never loaded into this field.
export function SecretField({
label,
hint,
@@ -19,29 +27,57 @@ export function SecretField({
placeholder,
onChange,
onClear,
+ clearPending = false,
+ onUndoClear,
+ disabled = false,
+ required = false,
+ error,
}: SecretFieldProps) {
+ const [visible, setVisible] = useState(false);
+ const hasDraft = value.trim().length > 0;
+ const status = clearPending ? "保存后清除" : hasDraft ? "新凭证待保存" : configured ? "已配置" : "未配置";
+ const inputRequired = required && !configured && !clearPending;
+ const fieldError = error ?? (value.length > 0 && !hasDraft && !clearPending ? "凭证不能只包含空格。" : undefined);
+ const guidance = clearPending
+ ? "当前只是标记清除,保存后生效;可撤销清除。"
+ : configured
+ ? "已有凭证不会回显;留空保留,输入新值后保存以替换。"
+ : "填写新凭证后保存;显示按钮仅展示本次输入。";
return (
<LabeledControl
label={label}
- hint={hint ?? (configured ? "已配置;留空保存则不修改" : undefined)}
+ hint={[hint, guidance].filter(Boolean).join(" ")}
+ required={inputRequired}
+ error={fieldError}
>
<div className="admin-secret-field">
- <div className="admin-secret-field-row">
+ <div className="admin-secret-field-row settings-secret-row">
<input
- type="password"
+ type={visible && !clearPending ? "text" : "password"}
className="settings-input is-secret"
- placeholder={placeholder ?? (configured ? "留空则不修改" : "填写密钥")}
- value={value}
+ placeholder={clearPending ? "已标记清除" : placeholder ?? (configured ? "留空保留已有凭证" : "输入新凭证")}
+ value={clearPending ? "" : value}
+ disabled={disabled || clearPending}
+ required={inputRequired}
onChange={(e) => onChange(e.target.value)}
autoComplete="new-password"
+ autoCapitalize="none"
+ spellCheck={false}
/>
- {configured && onClear ? (
- <button type="button" className="admin-btn admin-btn-secondary settings-mini-btn" onClick={onClear}>
- 清除
- </button>
- ) : null}
+ <Button type="button" variant="outline" size="icon" disabled={disabled || clearPending || !hasDraft}
+ aria-label={`${visible ? "隐藏" : "显示"}新${label}`} aria-pressed={visible}
+ title={visible ? "隐藏本次输入" : "显示本次输入"} onClick={() => setVisible((current) => !current)}>
+ {visible ? <EyeOff size={16} /> : <Eye size={16} />}
+ </Button>
+ {clearPending && onUndoClear ? <Button type="button" variant="outline" disabled={disabled} onClick={onUndoClear}>
+ <RotateCcw size={14} />撤销
+ </Button> : (configured || hasDraft) && onClear ? <Button type="button" variant="outline" disabled={disabled} onClick={() => { setVisible(false); onClear(); }}>
+ <Trash2 size={14} />清除
+ </Button> : null}
</div>
- {configured ? <span className="admin-secret-status">已配置</span> : null}
+ <span className="admin-secret-status inline-flex items-center gap-1" role="status">
+ {configured && !clearPending && !hasDraft ? <Check size={12} /> : null}{status}
+ </span>
</div>
</LabeledControl>
);
diff --git a/admin/src/components/settings/SettingsPanel.tsx b/admin/src/components/settings/SettingsPanel.tsx
index b15443d..71bec0c 100644
--- a/admin/src/components/settings/SettingsPanel.tsx
+++ b/admin/src/components/settings/SettingsPanel.tsx
@@ -1,6 +1,8 @@
import type { ReactNode } from "react";
-import { useEffect, useRef } from "react";
-import { Loader2 } from "lucide-react";
+import { useCallback, useEffect, useRef } from "react";
+import { Loader2, Save } from "lucide-react";
+import { AdminField } from "@/components/admin/AdminField";
+import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { useSettingsSaveSlot } from "@/components/settings/SettingsSaveContext";
@@ -33,31 +35,55 @@ type SettingsTabShellProps = {
onSave?: () => void | Promise<void>;
saving?: boolean;
saveLabel?: string;
+ disabled?: boolean;
};
-// Tab 内容区:把保存动作注册到页头,不再单独占一行工具条
-export function SettingsTabShell({ children, onSave, saving, saveLabel = "保存" }: SettingsTabShellProps) {
+// Both save entries submit the same form, so keyboard and button validation stay consistent.
+export function SettingsTabShell({ children, onSave, saving, saveLabel = "保存当前设置", disabled }: SettingsTabShellProps) {
const { registerSave } = useSettingsSaveSlot();
+ const formRef = useRef<HTMLFormElement>(null);
const onSaveRef = useRef(onSave);
onSaveRef.current = onSave;
+ const hasSave = Boolean(onSave);
+ const submit = useCallback(() => {
+ if (saving || disabled || !onSaveRef.current) return;
+ const form = formRef.current;
+ const invalid = form?.querySelector<HTMLElement>("input:invalid, select:invalid, textarea:invalid, [aria-invalid='true']");
+ if (invalid) {
+ let parent = invalid.parentElement;
+ while (parent && parent !== form) {
+ if (parent instanceof HTMLDetailsElement) parent.open = true;
+ parent = parent.parentElement;
+ }
+ invalid.scrollIntoView({ block: "center", behavior: "smooth" });
+ invalid.focus({ preventScroll: true });
+ }
+ if (!form?.reportValidity() || invalid?.getAttribute("aria-invalid") === "true") return;
+ return onSaveRef.current();
+ }, [saving, disabled]);
useEffect(() => {
- if (!onSave) {
+ if (!hasSave) {
registerSave(null);
return () => registerSave(null);
}
registerSave({
- onSave: () => onSaveRef.current?.(),
+ onSave: submit,
saving,
+ disabled,
label: saveLabel,
});
return () => registerSave(null);
- }, [onSave ? true : false, saving, saveLabel, registerSave]);
+ }, [hasSave, saving, disabled, saveLabel, registerSave, submit]);
return (
- <div className="settings-tab-shell">
- <div className="settings-tab-body">{children}</div>
- </div>
+ <form ref={formRef} className="settings-tab-shell" noValidate onSubmit={(event) => { event.preventDefault(); void submit(); }}>
+ <fieldset disabled={saving} className="settings-tab-body">{children}</fieldset>
+ {hasSave ? <div className="settings-save-bar">
+ <div><strong>{saving ? "正在保存设置…" : "保存当前分区"}</strong><p>本页修改将在保存成功后生效。</p></div>
+ <Button type="submit" disabled={saving || disabled}>{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}{saving ? "保存中…" : saveLabel}</Button>
+ </div> : null}
+ </form>
);
}
@@ -87,18 +113,20 @@ export function LabeledControl({
hint,
children,
className,
+ error,
+ required,
+ optional,
}: {
label: string;
hint?: string;
children: ReactNode;
className?: string;
+ error?: string;
+ required?: boolean;
+ optional?: boolean;
}) {
return (
- <label className={cn("settings-field", className)}>
- <span className="settings-field-label">{label}</span>
- {children}
- {hint ? <span className="settings-field-hint">{hint}</span> : null}
- </label>
+ <AdminField label={label} hint={hint} error={error} required={required} optional={optional} className={cn("settings-field", className)}>{children}</AdminField>
);
}
diff --git a/admin/src/components/settings/SettingsSaveContext.tsx b/admin/src/components/settings/SettingsSaveContext.tsx
index 8c59dcd..bc1a958 100644
--- a/admin/src/components/settings/SettingsSaveContext.tsx
+++ b/admin/src/components/settings/SettingsSaveContext.tsx
@@ -12,6 +12,7 @@ export type SettingsSaveAction = {
onSave: () => void | Promise<void>;
saving?: boolean;
label?: string;
+ disabled?: boolean;
};
type SettingsSaveContextValue = {
@@ -31,6 +32,7 @@ export function SettingsSaveProvider({ children }: { children: ReactNode }) {
prev &&
next &&
prev.saving === next.saving &&
+ prev.disabled === next.disabled &&
(prev.label ?? "保存") === (next.label ?? "保存")
) {
// 同步最新 onSave,避免闭包过期;不触发无意义重渲染依赖
diff --git a/admin/src/components/settings/SiteSettingsPanel.tsx b/admin/src/components/settings/SiteSettingsPanel.tsx
index 6abb782..57c169c 100644
--- a/admin/src/components/settings/SiteSettingsPanel.tsx
+++ b/admin/src/components/settings/SiteSettingsPanel.tsx
@@ -32,7 +32,7 @@ export function SiteSettingsPanel() {
const hasFfprobe = Boolean(form.ffprobe_path?.trim());
return (
- <SettingsTabShell onSave={() => void handleSave()} saving={saving}>
+ <SettingsTabShell onSave={handleSave} saving={saving} saveLabel="保存站点设置">
<SettingsStatusBar
title="站点工具状态"
items={[
@@ -63,17 +63,21 @@ export function SiteSettingsPanel() {
<div className="settings-routing-grid">
<SettingsPanel
className="settings-panel--compact"
- title="1. 公网地址"
- description="支付回调、分享链接与 OSS 回填"
+ title="站点访问地址"
+ description="供支付回调、分享链接和媒体地址回填使用,填写可从公网访问的后端地址。"
>
<div className="settings-field-grid">
<LabeledControl
label="后端公网基址"
- hint="例:https://www.printfilm.com"
+ hint="例如 https://www.printfilm.com;留空使用服务器默认配置。"
+ optional
className="settings-field-span-full"
>
<input
className="settings-input"
+ type="url"
+ placeholder="https://www.printfilm.com"
+ autoComplete="url"
value={form.public_base_url}
onChange={(e) => patchField("public_base_url", e.target.value)}
/>
@@ -86,11 +90,11 @@ export function SiteSettingsPanel() {
<SettingsPanel
className="settings-panel--compact"
- title="2. 媒体工具"
- description="合成与抽帧依赖本机 ffmpeg / ffprobe"
+ title="媒体处理工具"
+ description="视频合成与抽帧使用服务器上的工具。已加入服务器 PATH 时,可保持默认名称。"
>
<div className="settings-field-grid">
- <LabeledControl label="ffmpeg 路径">
+ <LabeledControl label="视频处理工具(ffmpeg)" hint="可填写命令名或服务器上的完整路径。" optional>
<input
className="settings-input"
placeholder="ffmpeg"
@@ -98,7 +102,7 @@ export function SiteSettingsPanel() {
onChange={(e) => patchField("ffmpeg_path", e.target.value)}
/>
</LabeledControl>
- <LabeledControl label="ffprobe 路径">
+ <LabeledControl label="媒体信息工具(ffprobe)" hint="与 ffmpeg 使用同一安装目录。" optional>
<input
className="settings-input"
placeholder="ffprobe"
diff --git a/admin/src/components/teams/TeamBudgetModal.tsx b/admin/src/components/teams/TeamBudgetModal.tsx
index 8554b95..eac5c78 100644
--- a/admin/src/components/teams/TeamBudgetModal.tsx
+++ b/admin/src/components/teams/TeamBudgetModal.tsx
@@ -1,8 +1,12 @@
-import { useRef, useState } from "react";
+import { useId, useRef, useState } from "react";
+import { Info, Loader2 } from "lucide-react";
import { setAdminTeamBudget } from "@/api/teams";
import { AdminModal } from "@/components/admin/AdminModal";
+import { AdminField } from "@/components/admin/AdminField";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
+import { yuanInputToFen } from "@/lib/moneyInput";
+import { fenToYuan } from "@/lib/utils";
/** 设置团队或成员月上限,零元停用新消费,空值代表不限额。 */
export function TeamBudgetModal({ teamId, memberId, name, limit, onClose, onSaved }: {
@@ -10,27 +14,81 @@ export function TeamBudgetModal({ teamId, memberId, name, limit, onClose, onSave
onClose: () => void; onSaved: () => void;
}) {
const [unlimited, setUnlimited] = useState(limit === null);
- const [amount, setAmount] = useState(((limit ?? 0) / 100).toFixed(2));
+ const [amount, setAmount] = useState(limit === null ? "" : fenToYuan(limit));
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
+ const [amountTouched, setAmountTouched] = useState(false);
+ const [submitAttempted, setSubmitAttempted] = useState(false);
const pending = useRef(false);
+ const formId = useId();
+ const modeName = useId();
+ const amountFen = yuanInputToFen(amount);
+ const amountError = unlimited ? "" : !amount.trim()
+ ? "请输入每月消费上限"
+ : amountFen === null ? "请输入非负金额,最多保留两位小数"
+ : amountFen > 100000000 ? "每月消费上限不能超过 1,000,000 元"
+ : "";
+ const nextLimit = unlimited ? null : amountFen;
+ const changed = unlimited ? limit !== null : amountError !== "" || nextLimit !== limit;
+ const visibleAmountError = amountTouched || submitAttempted ? amountError : "";
+
/** 保存金额只接受两位小数,精确转换为整数分,重复点击不重复请求。 */
async function save() {
- if (pending.current) return;
- if (!unlimited && !/^\d+(\.\d{1,2})?$/.test(amount.trim())) { setError("请输入非负金额,最多两位小数"); return; }
- const fen = unlimited ? null : Math.round(Number(amount) * 100);
- if (fen !== null && (!Number.isSafeInteger(fen) || fen > 100000000)) { setError("额度不得超过 1,000,000 元"); return; }
+ if (pending.current || !changed) return;
+ setSubmitAttempted(true);
+ setError("");
+ if (amountError) return;
pending.current = true; setBusy(true); setError("");
- try { await setAdminTeamBudget(teamId, fen, memberId); onSaved(); onClose(); }
+ try { await setAdminTeamBudget(teamId, nextLimit, memberId); onSaved(); onClose(); }
catch (cause) { setError(cause instanceof Error ? cause.message : "保存额度失败"); }
finally { pending.current = false; setBusy(false); }
}
- return <AdminModal open onOpenChange={(open) => { if (!open && !busy) onClose(); }} size="md" title={memberId === undefined ? "团队月度消费上限" : "成员月度消费上限"} subtitle={name}
- footer={<><Button variant="outline" disabled={busy} onClick={onClose}>取消</Button><Button disabled={busy} onClick={save}>{busy ? "正在保存…" : "保存消费上限"}</Button></>}>
- <div className="space-y-4"><p className="text-sm text-[var(--admin-muted)]">按上海时区自然月统计,已消费及在途预留均占用额度。设为 0 元停止新消费,降低上限不会取消已受理任务。费用由受理时的所有者个人账户支付。</p>
- <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={unlimited} disabled={busy} onChange={(e) => setUnlimited(e.target.checked)} />不限额</label>
- <label className="block space-y-2 text-sm"><span>每月上限(元)</span><Input value={amount} inputMode="decimal" disabled={unlimited || busy} onChange={(e) => setAmount(e.target.value)} /></label>
- {error && <p role="alert" className="text-sm text-red-600">{error}</p>}
- </div>
- </AdminModal>;
+ return (
+ <AdminModal
+ open
+ onOpenChange={(open) => { if (!open && !pending.current) onClose(); }}
+ size="lg"
+ title={memberId === undefined ? "团队月度消费上限" : "成员月度消费上限"}
+ subtitle={name}
+ footer={<>
+ <Button type="button" variant="outline" disabled={busy} onClick={onClose}>取消</Button>
+ <Button type="submit" form={formId} disabled={busy || !changed} aria-busy={busy}>
+ {busy ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" /> : null}
+ {busy ? "正在保存…" : "保存消费上限"}
+ </Button>
+ </>}
+ >
+ <form id={formId} noValidate onSubmit={(event) => { event.preventDefault(); void save(); }} className="space-y-5">
+ <div className="admin-form-summary rounded-xl border border-[var(--admin-border)] bg-[#f7f9f4] px-4 py-3">
+ <div className="text-xs text-[var(--admin-muted)]">当前每月消费上限</div>
+ <div className="mt-1.5 text-xl font-semibold tabular-nums text-[var(--admin-text)]">{limit === null ? "不限额" : `¥${fenToYuan(limit)}`}</div>
+ </div>
+ <fieldset disabled={busy} className="min-w-0 space-y-3">
+ <legend className="mb-3 text-sm font-semibold text-[var(--admin-text)]">消费限制方式</legend>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <label className={`admin-choice-card flex cursor-pointer items-start gap-3 rounded-xl border p-4 transition-colors ${!unlimited ? "border-[var(--admin-forest)] bg-[var(--admin-accent-soft)]" : "border-[var(--admin-border)] bg-white"} ${busy ? "opacity-60" : ""}`}>
+ <input type="radio" name={modeName} value="limited" checked={!unlimited} disabled={busy} onChange={() => { setUnlimited(false); setError(""); }} className="mt-0.5 h-4 w-4 shrink-0 accent-[var(--admin-forest)]" />
+ <span><span className="block text-sm font-semibold text-[var(--admin-text)]">设置月度上限</span><span className="mt-1 block text-xs leading-relaxed text-[var(--admin-muted)]">达到限额后暂停新的消费请求</span></span>
+ </label>
+ <label className={`admin-choice-card flex cursor-pointer items-start gap-3 rounded-xl border p-4 transition-colors ${unlimited ? "border-[var(--admin-forest)] bg-[var(--admin-accent-soft)]" : "border-[var(--admin-border)] bg-white"} ${busy ? "opacity-60" : ""}`}>
+ <input type="radio" name={modeName} value="unlimited" checked={unlimited} disabled={busy} onChange={() => { setUnlimited(true); setError(""); }} className="mt-0.5 h-4 w-4 shrink-0 accent-[var(--admin-forest)]" />
+ <span><span className="block text-sm font-semibold text-[var(--admin-text)]">不限额</span><span className="mt-1 block text-xs leading-relaxed text-[var(--admin-muted)]">不额外设置{memberId === undefined ? "团队" : "该成员"}月度消费限额</span></span>
+ </label>
+ </div>
+ </fieldset>
+ <AdminField label="每月消费上限(元)" required={!unlimited} hint={unlimited ? "已选择不限额,无需填写金额。" : "可设置 0–1,000,000 元,最多两位小数;0 元表示停止新消费。"} error={visibleAmountError}>
+ <Input value={amount} inputMode="decimal" placeholder={unlimited ? "不限额,无需填写" : "例如 1000.00"} disabled={unlimited || busy} onBlur={() => setAmountTouched(true)} onChange={(event) => { setAmount(event.target.value); setError(""); }} />
+ </AdminField>
+ <div className="admin-form-notice flex items-start gap-2.5 rounded-xl border border-[var(--admin-border)] bg-[#f8f9f5] p-4 text-xs leading-7 text-[var(--admin-muted)]">
+ <Info className="mt-1 h-4 w-4 shrink-0" aria-hidden="true" />
+ <div>
+ <p>按上海时区自然月统计,已消费金额与在途预留金额均占用额度。</p>
+ <p>{memberId === undefined ? "团队上限统计所有成员消费;成员自己的上限同时生效。" : "成员消费同时受个人上限与团队总上限限制。"}降低上限不会取消已受理任务。</p>
+ <p>费用从受理时的团队所有者个人账户扣除,设置上限不会调整账户余额。</p>
+ </div>
+ </div>
+ {error ? <p role="alert" className="admin-form-error rounded-lg border border-[#f0d9d5] bg-[#fcf0ee] px-3 py-2.5 text-sm leading-relaxed text-[#aa3d37]">{error}</p> : null}
+ </form>
+ </AdminModal>
+ );
}
diff --git a/admin/src/components/templates/TemplateEditorDialog.tsx b/admin/src/components/templates/TemplateEditorDialog.tsx
index 14d1948..d4405df 100644
--- a/admin/src/components/templates/TemplateEditorDialog.tsx
+++ b/admin/src/components/templates/TemplateEditorDialog.tsx
@@ -1,5 +1,5 @@
import { ImageOff, Loader2, Save } from "lucide-react";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import type { AdminTemplate } from "@/api/client";
import { AdminField } from "@/components/admin/AdminField";
import { AdminModal } from "@/components/admin/AdminModal";
@@ -9,6 +9,7 @@ import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/select";
import { cn } from "@/lib/utils";
+import { validateTemplateDraft } from "@/lib/templateForm";
export type TemplateFormState = {
id: string;
@@ -76,9 +77,29 @@ export function TemplateEditorDialog({
onSave,
}: TemplateEditorDialogProps) {
const [tab, setTab] = useState<EditorTab>("basic");
+ const [attempted, setAttempted] = useState(false);
+ const editorRef = useRef<HTMLDivElement>(null);
+ const errors = validateTemplateDraft(form, !editing);
const previewSrc = useMemo(() => coverPreviewSrc(form.preview_cover), [form.preview_cover]);
+ useEffect(() => { if (open) { setTab("basic"); setAttempted(false); } }, [open]);
+
+ function requestSave() {
+ if (saving) return;
+ setAttempted(true);
+ if (Object.keys(errors).length) {
+ setTab("basic");
+ requestAnimationFrame(() => {
+ const invalid = editorRef.current?.querySelector<HTMLElement>("[aria-invalid='true']");
+ invalid?.focus({ preventScroll: true });
+ invalid?.closest(".admin-form-field")?.scrollIntoView({ block: "center" });
+ });
+ return;
+ }
+ onSave();
+ }
const handleOpenChange = (next: boolean) => {
+ if (saving) return;
if (!next) setTab("basic");
onOpenChange(next);
};
@@ -91,20 +112,20 @@ export function TemplateEditorDialog({
className="template-editor-dialog max-h-[92vh] overflow-hidden"
bodyClassName="p-0 overflow-hidden"
title={editing ? `编辑模板 · ${editing.name}` : "新建模板"}
- subtitle={editing ? editing.id : "填写基础信息与提示词,保存后立即生效"}
+ subtitle={editing ? editing.id : "先填写展示信息与生成默认值,再按需配置提示词和上架状态"}
footer={
<>
- <Button variant="outline" onClick={() => handleOpenChange(false)}>
+ <Button variant="outline" disabled={saving} onClick={() => handleOpenChange(false)}>
取消
</Button>
- <Button disabled={saving} onClick={onSave}>
+ <Button disabled={saving} onClick={requestSave}>
{saving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Save className="mr-2 h-4 w-4" />}
{saving ? "保存中…" : "保存模板"}
</Button>
</>
}
>
- <div className="template-editor-layout">
+ <div ref={editorRef} className="template-editor-layout" inert={saving}>
<aside className="template-editor-preview">
<div className="template-editor-preview-frame">
{previewSrc ? (
@@ -116,6 +137,7 @@ export function TemplateEditorDialog({
</div>
)}
</div>
+ <div className="settings-price-note"><strong>{form.name || "未命名模板"}</strong><br />{form.default_ratio} · {form.shot_duration_min}–{form.shot_duration_max} 秒 / 镜<br />{form.is_active ? "保存后上架展示" : "保存为下架状态"}</div>
<AdminField label="封面 URL" hint="支持相对路径(/static)或 HTTPS;建议 16:9 横图。">
<Input
className="admin-input h-9"
@@ -143,26 +165,30 @@ export function TemplateEditorDialog({
</div>
<div className="template-editor-panel">
+ {attempted && Object.keys(errors).length ? <div role="alert" className="template-editor-validation">请先完善基础信息:{Object.values(errors).join(";")}。</div> : null}
{tab === "basic" ? (
<div className="template-editor-grid">
+ <h3 className="template-editor-section-title">展示信息</h3>
{!editing ? (
- <AdminField label="模板 ID" className="template-editor-field--full">
+ <AdminField label="模板 ID" required error={attempted ? errors.id : undefined} hint="模板的唯一标识,创建后不可修改。" className="template-editor-field--full">
<Input
className="admin-input h-9"
placeholder="例如 live_street_interview"
+ maxLength={64}
value={form.id}
onChange={(e) => onChange({ id: e.target.value })}
/>
</AdminField>
) : null}
- <AdminField label="名称" className="template-editor-field--full">
+ <AdminField label="模板名称" required error={attempted ? errors.name : undefined} hint="显示在用户选择模板的列表中。" className="template-editor-field--full">
<Input
className="admin-input h-9"
+ maxLength={128}
value={form.name}
onChange={(e) => onChange({ name: e.target.value })}
/>
</AdminField>
- <AdminField label="描述" className="template-editor-field--full">
+ <AdminField label="模板简介" optional hint="简要说明适合的题材与视觉效果。" className="template-editor-field--full">
<Textarea
value={form.description}
onChange={(e) => onChange({ description: e.target.value })}
@@ -170,11 +196,11 @@ export function TemplateEditorDialog({
/>
</AdminField>
<AdminField
- label="分类(逗号分隔)"
+ label="分类标签"
hint={
categorySuggestions.length
? `常用:${categorySuggestions.slice(0, 8).join("、")}${categorySuggestions.length > 8 ? "…" : ""}`
- : undefined
+ : "多个标签用英文逗号分隔。"
}
>
<Input
@@ -183,14 +209,19 @@ export function TemplateEditorDialog({
value={form.category}
onChange={(e) => onChange({ category: e.target.value })}
/>
+ {categorySuggestions.length ? <div className="template-category-suggestions">{categorySuggestions.slice(0, 8).map((category) => <button type="button" key={category} onClick={() => {
+ const current = form.category.split(/[,,]/).map((item) => item.trim()).filter(Boolean);
+ if (!current.includes(category)) onChange({ category: [...current, category].join(",") });
+ }}>+ {category}</button>)}</div> : null}
</AdminField>
+ <h3 className="template-editor-section-title">生成默认值</h3>
<AdminSelect
label="默认画幅"
value={form.default_ratio}
options={RATIO_OPTIONS}
onChange={(v) => onChange({ default_ratio: v })}
/>
- <AdminField label="排序">
+ <AdminField label="展示排序" error={attempted ? errors.sort_order : undefined} hint="数值越小越靠前,可使用负数。">
<Input
className="admin-input h-9"
type="number"
@@ -198,18 +229,22 @@ export function TemplateEditorDialog({
onChange={(e) => onChange({ sort_order: Number(e.target.value) })}
/>
</AdminField>
- <AdminField label="镜头时长 min(秒)">
+ <AdminField label="最短镜头时长(秒)" required error={attempted ? errors.shot_duration_min : undefined}>
<Input
className="admin-input h-9"
type="number"
+ min={1}
+ step={1}
value={form.shot_duration_min}
onChange={(e) => onChange({ shot_duration_min: Number(e.target.value) })}
/>
</AdminField>
- <AdminField label="镜头时长 max(秒)">
+ <AdminField label="最长镜头时长(秒)" required error={attempted ? errors.shot_duration_max : undefined} hint="不得小于最短时长。">
<Input
className="admin-input h-9"
type="number"
+ min={form.shot_duration_min || 1}
+ step={1}
value={form.shot_duration_max}
onChange={(e) => onChange({ shot_duration_max: Number(e.target.value) })}
/>
@@ -219,35 +254,35 @@ export function TemplateEditorDialog({
{tab === "prompts" ? (
<div className="template-editor-grid template-editor-grid--prompts">
- <AdminField label="风格提示词" className="template-editor-field--full">
+ <AdminField label="风格提示词" optional hint="描述画面风格、光线与色彩,会作为生成的基础风格。" className="template-editor-field--full">
<Textarea
value={form.style_prefix}
onChange={(e) => onChange({ style_prefix: e.target.value })}
className="min-h-[100px] font-mono text-[13px]"
/>
</AdminField>
- <AdminField label="角色提示词" className="template-editor-field--full">
+ <AdminField label="角色提示词" optional hint="用于角色图像的外观与服饰要求。" className="template-editor-field--full">
<Textarea
value={form.character_prompt}
onChange={(e) => onChange({ character_prompt: e.target.value })}
className="min-h-[88px] font-mono text-[13px]"
/>
</AdminField>
- <AdminField label="额外提示词" className="template-editor-field--full">
+ <AdminField label="额外提示词" optional hint="补充图片生成的统一要求。" className="template-editor-field--full">
<Textarea
value={form.extra_prompt}
onChange={(e) => onChange({ extra_prompt: e.target.value })}
className="min-h-[88px] font-mono text-[13px]"
/>
</AdminField>
- <AdminField label="LLM 系统附加说明" className="template-editor-field--full">
+ <AdminField label="文本模型附加说明" optional hint="追加给文本模型的脚本与规划说明。" className="template-editor-field--full">
<Textarea
value={form.llm_system_addon}
onChange={(e) => onChange({ llm_system_addon: e.target.value })}
className="min-h-[88px] font-mono text-[13px]"
/>
</AdminField>
- <AdminField label="负面提示词" className="template-editor-field--full">
+ <AdminField label="负面提示词" optional hint="列出希望避免出现的画面内容或效果。" className="template-editor-field--full">
<Textarea
value={form.negative_prompt}
onChange={(e) => onChange({ negative_prompt: e.target.value })}
diff --git a/admin/src/hooks/useAdminModelSettings.ts b/admin/src/hooks/useAdminModelSettings.ts
index 993c373..daca89e 100644
--- a/admin/src/hooks/useAdminModelSettings.ts
+++ b/admin/src/hooks/useAdminModelSettings.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { api, type AdminModelSettings } from "@/api/client";
@@ -7,6 +7,7 @@ export function useAdminModelSettings() {
const [form, setForm] = useState<AdminModelSettings | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
+ const pendingSave = useRef(false);
const load = useCallback(async () => {
setLoading(true);
@@ -27,15 +28,20 @@ export function useAdminModelSettings() {
setForm((prev) => (prev ? { ...prev, [key]: value } : prev));
}
- async function save(body: Record<string, unknown>, successMessage = "配置已保存") {
+ async function save(body: Record<string, unknown>, successMessage = "配置已保存"): Promise<boolean> {
+ if (pendingSave.current) return false;
+ pendingSave.current = true;
setSaving(true);
try {
await api("/api/admin/settings/models", { method: "PATCH", body: JSON.stringify(body) });
await load();
toast.success(successMessage);
+ return true;
} catch (err) {
toast.error(err instanceof Error ? err.message : "保存失败");
+ return false;
} finally {
+ pendingSave.current = false;
setSaving(false);
}
}
diff --git a/admin/src/lib/moneyInput.ts b/admin/src/lib/moneyInput.ts
new file mode 100644
index 0000000..9b55230
--- /dev/null
+++ b/admin/src/lib/moneyInput.ts
@@ -0,0 +1,8 @@
+/** Parse a decimal yuan amount without rounding away digits or accepting exponent notation. */
+export function yuanInputToFen(value: string): number | null {
+ const text = value.trim();
+ if (!/^\d+(?:\.\d{1,2})?$/.test(text)) return null;
+ const [yuan, fraction = ""] = text.split(".");
+ const fen = BigInt(yuan) * 100n + BigInt(fraction.padEnd(2, "0"));
+ return fen <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(fen) : null;
+}
diff --git a/admin/src/lib/templateForm.ts b/admin/src/lib/templateForm.ts
new file mode 100644
index 0000000..2ce9a89
--- /dev/null
+++ b/admin/src/lib/templateForm.ts
@@ -0,0 +1,14 @@
+type TemplateDraft = {
+ id: string; name: string; shot_duration_min: number; shot_duration_max: number; sort_order: number;
+};
+
+export function validateTemplateDraft(draft: TemplateDraft, creating: boolean) {
+ const errors: Partial<Record<keyof TemplateDraft, string>> = {};
+ if (creating && (!draft.id.trim() || draft.id.trim().length > 64)) errors.id = "请填写 1–64 个字符的模板 ID";
+ if (!draft.name.trim() || draft.name.trim().length > 128) errors.name = "请填写 1–128 个字符的模板名称";
+ if (!Number.isSafeInteger(draft.shot_duration_min) || draft.shot_duration_min <= 0) errors.shot_duration_min = "最短时长须为大于 0 的整数秒";
+ if (!Number.isSafeInteger(draft.shot_duration_max) || draft.shot_duration_max <= 0) errors.shot_duration_max = "最长时长须为大于 0 的整数秒";
+ if (!errors.shot_duration_min && !errors.shot_duration_max && draft.shot_duration_max < draft.shot_duration_min) errors.shot_duration_max = "最长时长不能小于最短时长";
+ if (!Number.isSafeInteger(draft.sort_order)) errors.sort_order = "排序值须为整数";
+ return errors;
+}
diff --git a/admin/src/main.tsx b/admin/src/main.tsx
index 1e90252..aee8146 100644
--- a/admin/src/main.tsx
+++ b/admin/src/main.tsx
@@ -5,6 +5,7 @@ import { Toaster } from "sonner";
import App from "./App";
import "./index.css";
import "./styles/admin-console.css";
+import "./styles/admin-forms.css";
createRoot(document.getElementById("root")!).render(
<StrictMode>
diff --git a/admin/src/pages/SettingsPage.tsx b/admin/src/pages/SettingsPage.tsx
index 0892b16..fb1136c 100644
--- a/admin/src/pages/SettingsPage.tsx
+++ b/admin/src/pages/SettingsPage.tsx
@@ -29,14 +29,14 @@ function SettingsPageHeader() {
<div className="min-w-0">
<h1 className="settings-page-title">系统设置</h1>
<p className="settings-head-desc">
- TokenFree API Key、运行参数、OSS / 易支付 / 计费与站点配置;密钥加密存库,留空保存不修改。
+ 管理生成模型、任务运行、存储连接、支付计费与站点工具。
</p>
</div>
{action ? (
<button
type="button"
className="admin-btn admin-btn-primary settings-save-btn"
- disabled={action.saving}
+ disabled={action.saving || action.disabled}
onClick={() => void action.onSave()}
>
{action.saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}
diff --git a/admin/src/pages/UsersPage.tsx b/admin/src/pages/UsersPage.tsx
index 491cbfc..4ef8b69 100644
--- a/admin/src/pages/UsersPage.tsx
+++ b/admin/src/pages/UsersPage.tsx
@@ -1,4 +1,5 @@
-import { useEffect, useState } from "react";
+import { useEffect, useId, useRef, useState } from "react";
+import { ArrowRight, Loader2, Wallet } from "lucide-react";
import { toast } from "sonner";
import { api, type AdminStats, type AdminUserRow, type PageMeta } from "@/api/client";
import { AdminField } from "@/components/admin/AdminField";
@@ -18,6 +19,8 @@ import { useAdminDetailQuery } from "@/hooks/useAdminDetailQuery";
import { formatAccountId } from "@/lib/admin-account";
import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { fenToYuan } from "@/lib/utils";
+import { yuanInputToFen } from "@/lib/moneyInput";
+import { Switch } from "@/components/ui/switch";
type ListRes = { items: AdminUserRow[]; meta: PageMeta };
@@ -41,8 +44,30 @@ export function UsersPage() {
balance_note: "",
});
const [saving, setSaving] = useState(false);
+ const [adjustBalance, setAdjustBalance] = useState(false);
+ const [amountTouched, setAmountTouched] = useState(false);
+ const [submitAttempted, setSubmitAttempted] = useState(false);
+ const [saveError, setSaveError] = useState("");
+ const pendingSave = useRef(false);
+ const editFormId = useId();
+ const adjustmentToggleId = useId();
const userDetail = useAdminDetailQuery("user");
+ const amountFen = yuanInputToFen(form.balance_amount_yuan);
+ const balanceAfterFen = editing && adjustBalance && amountFen !== null
+ ? editing.balance_fen + (form.balance_dir === "decrease" ? -amountFen : amountFen)
+ : editing?.balance_fen ?? 0;
+ const amountError = !adjustBalance ? "" : !form.balance_amount_yuan.trim()
+ ? "请输入需要调整的金额"
+ : amountFen === null ? "请输入有效金额,最多保留两位小数"
+ : amountFen === 0 ? "调账金额须大于 0 元"
+ : !Number.isSafeInteger(balanceAfterFen) ? "调整后金额过大,请减少调账金额"
+ : balanceAfterFen < 0 ? "减少金额不能超过当前余额"
+ : "";
+ const visibleAmountError = amountTouched || submitAttempted ? amountError : "";
+ const roleChanged = editing !== null && form.role !== editing.role;
+ const hasChanges = roleChanged || adjustBalance;
+
async function load(nextPage = page, nextQ = q, nextSize = pageSize) {
setLoading(true);
try {
@@ -82,7 +107,12 @@ export function UsersPage() {
}, [userDetail.id, data?.items]);
function openEdit(user: AdminUserRow) {
+ if (pendingSave.current) return;
setEditing(user);
+ setAdjustBalance(false);
+ setAmountTouched(false);
+ setSubmitAttempted(false);
+ setSaveError("");
setForm({
role: user.role || "user",
balance_dir: "increase",
@@ -92,7 +122,11 @@ export function UsersPage() {
}
async function saveEdit() {
- if (!editing) return;
+ if (!editing || pendingSave.current || !hasChanges) return;
+ setSubmitAttempted(true);
+ setSaveError("");
+ if (amountError) return;
+ pendingSave.current = true;
setSaving(true);
try {
const payload: {
@@ -101,21 +135,9 @@ export function UsersPage() {
balance_note?: string;
} = { role: form.role };
- const amountRaw = form.balance_amount_yuan.trim();
- if (amountRaw) {
- const amountYuan = parseFloat(amountRaw);
- if (Number.isNaN(amountYuan) || amountYuan < 0) {
- throw new Error("调账金额须为非负数字");
- }
- const amountFen = Math.round(amountYuan * 100);
- if (amountFen > 0) {
- const signed = form.balance_dir === "decrease" ? -amountFen : amountFen;
- if (form.balance_dir === "decrease" && signed + editing.balance_fen < 0) {
- throw new Error("减少后余额不能为负");
- }
- payload.balance_delta_fen = signed;
- payload.balance_note = form.balance_note || undefined;
- }
+ if (adjustBalance && amountFen !== null && amountFen > 0) {
+ payload.balance_delta_fen = form.balance_dir === "decrease" ? -amountFen : amountFen;
+ payload.balance_note = form.balance_note.trim() || undefined;
}
await api(`/api/admin/users/${editing.id}`, {
@@ -126,8 +148,9 @@ export function UsersPage() {
setEditing(null);
await load();
} catch (err) {
- toast.error(err instanceof Error ? err.message : "保存失败");
+ setSaveError(err instanceof Error ? err.message : "保存失败,请重试");
} finally {
+ pendingSave.current = false;
setSaving(false);
}
}
@@ -139,7 +162,7 @@ export function UsersPage() {
return (
<div className="admin-list-page">
- <PageHeader description="搜索用户,调整角色与余额" />
+ <PageHeader title="用户管理" description="搜索用户,调整角色与余额" />
<AdminFilterBar>
<AdminSearchInput
@@ -152,8 +175,8 @@ export function UsersPage() {
/>
<Select value={roleFilter} onChange={(e) => setRoleFilter(e.target.value)}>
<option value="">全部角色</option>
- <option value="user">user</option>
- <option value="admin">admin</option>
+ <option value="user">普通用户</option>
+ <option value="admin">管理员</option>
</Select>
<Button size="sm" className="admin-filter-action" onClick={applyFilters} disabled={loading}>
{loading ? "加载中…" : "搜索"}
@@ -200,7 +223,7 @@ export function UsersPage() {
<TableCell className="tabular-nums">¥{fenToYuan(u.balance_fen)}</TableCell>
<TableCell className="tabular-nums">¥{fenToYuan(u.frozen_fen)}</TableCell>
<TableCell>
- <Badge variant={u.role === "admin" ? "success" : "secondary"}>{u.role}</Badge>
+ <Badge variant={u.role === "admin" ? "success" : "secondary"}>{u.role === "admin" ? "管理员" : "普通用户"}</Badge>
</TableCell>
<TableCell className="text-xs text-muted-foreground">
{u.created_at ? new Date(u.created_at).toLocaleString() : "—"}
@@ -259,68 +282,60 @@ export function UsersPage() {
<AdminModal
open={!!editing}
- onOpenChange={(open) => !open && setEditing(null)}
- size="md"
+ onOpenChange={(open) => { if (!open && !pendingSave.current) setEditing(null); }}
+ size="lg"
title="编辑用户"
subtitle={editing?.email}
footer={
- <Button className="w-full sm:w-auto" disabled={saving} onClick={() => void saveEdit()}>
- {saving ? "保存中…" : "保存修改"}
- </Button>
+ <>
+ <Button type="button" variant="outline" disabled={saving} onClick={() => setEditing(null)}>取消</Button>
+ <Button type="submit" form={editFormId} disabled={saving || !hasChanges} aria-busy={saving}>
+ {saving ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" /> : null}
+ {saving ? "正在保存…" : adjustBalance ? "确认调账并保存" : "保存权限修改"}
+ </Button>
+ </>
}
>
- <div className="admin-form-grid admin-form-grid--2">
- <AdminField label="角色">
- <Select value={form.role} onChange={(e) => setForm((f) => ({ ...f, role: e.target.value }))}>
- <option value="user">user</option>
- <option value="admin">admin</option>
- </Select>
- </AdminField>
- <AdminField label="当前余额" hint="只读">
- <Input value={editing ? `¥${fenToYuan(editing.balance_fen)}` : "—"} disabled readOnly />
- </AdminField>
- <AdminField label="调账方向">
- <Select
- value={form.balance_dir}
- onChange={(e) =>
- setForm((f) => ({
- ...f,
- balance_dir: e.target.value === "decrease" ? "decrease" : "increase",
- }))
- }
- >
- <option value="increase">增加</option>
- <option value="decrease">减少</option>
- </Select>
- </AdminField>
- <AdminField
- label="调账金额(元)"
- hint={
- form.balance_amount_yuan.trim()
- ? form.balance_dir === "increase"
- ? "保存后余额将增加该金额"
- : "保存后余额将减少该金额"
- : "留空则不改余额"
- }
- >
- <Input
- type="number"
- min="0"
- step="0.01"
- inputMode="decimal"
- value={form.balance_amount_yuan}
- onChange={(e) => setForm((f) => ({ ...f, balance_amount_yuan: e.target.value }))}
- placeholder="例如 100"
- />
- </AdminField>
- <AdminField label="调账备注" hint="可选;仅改余额时写入流水">
- <Input
- value={form.balance_note}
- onChange={(e) => setForm((f) => ({ ...f, balance_note: e.target.value }))}
- placeholder="管理员备注"
- />
- </AdminField>
- </div>
+ <form id={editFormId} noValidate onSubmit={(event) => { event.preventDefault(); void saveEdit(); }} className="space-y-6">
+ <div className="admin-form-summary grid gap-4 rounded-xl border border-[var(--admin-border)] bg-[#f7f9f4] p-4 sm:grid-cols-2">
+ <div className="admin-form-summary-item"><div className="text-xs text-[var(--admin-muted)]">当前账户余额</div><div className="mt-1.5 text-2xl font-semibold tabular-nums text-[var(--admin-text)]">¥{fenToYuan(editing?.balance_fen ?? 0)}</div></div>
+ <div className="admin-form-summary-item"><div className="text-xs text-[var(--admin-muted)]">已冻结金额</div><div className="mt-1.5 text-lg font-medium tabular-nums text-[var(--admin-text)]">¥{fenToYuan(editing?.frozen_fen ?? 0)}</div><p className="mt-1 text-xs leading-relaxed text-[var(--admin-muted)]">调账不会修改任务已冻结的金额</p></div>
+ </div>
+ <fieldset disabled={saving} className="admin-form-section min-w-0 space-y-4">
+ <legend className="admin-form-section-title mb-1 text-sm font-semibold text-[var(--admin-text)]">账号权限</legend>
+ <AdminField label="账号角色" required hint="管理员可进入管理端,查看和管理全部业务数据。">
+ <Select value={form.role} onChange={(e) => { setSaveError(""); setForm((f) => ({ ...f, role: e.target.value })); }} disabled={saving}>
+ <option value="user">普通用户</option><option value="admin">管理员</option>
+ </Select>
+ </AdminField>
+ </fieldset>
+ <section className="admin-form-section space-y-4 border-t border-[var(--admin-border)] pt-5">
+ <div className="flex items-start justify-between gap-4">
+ <div><label htmlFor={adjustmentToggleId} className="text-sm font-semibold text-[var(--admin-text)]">调整账户余额</label><p className="mt-1 text-xs leading-relaxed text-[var(--admin-muted)]">按需开启;仅修改角色时,账户余额保持不变。</p></div>
+ <Switch id={adjustmentToggleId} checked={adjustBalance} disabled={saving} onCheckedChange={(checked) => { setAdjustBalance(checked); setSaveError(""); }} />
+ </div>
+ {adjustBalance ? <fieldset disabled={saving} className="min-w-0 space-y-4">
+ <div className="admin-form-grid admin-form-grid--2">
+ <AdminField label="调整方向" required>
+ <Select value={form.balance_dir} disabled={saving} onChange={(e) => { setSaveError(""); setForm((f) => ({ ...f, balance_dir: e.target.value === "decrease" ? "decrease" : "increase" })); }}>
+ <option value="increase">增加余额</option><option value="decrease">减少余额</option>
+ </Select>
+ </AdminField>
+ <AdminField label="调整金额(元)" required hint="大于 0,最多两位小数。" error={visibleAmountError}>
+ <Input inputMode="decimal" value={form.balance_amount_yuan} disabled={saving} placeholder="例如 100.00" onBlur={() => setAmountTouched(true)} onChange={(e) => { setSaveError(""); setForm((f) => ({ ...f, balance_amount_yuan: e.target.value })); }} />
+ </AdminField>
+ </div>
+ <AdminField label="调账备注" optional hint="备注会写入账户流水,便于后续核对。">
+ <Input value={form.balance_note} disabled={saving} onChange={(e) => setForm((f) => ({ ...f, balance_note: e.target.value }))} placeholder="例如:活动奖励补发、退款扣回" />
+ </AdminField>
+ {!amountError && amountFen !== null ? <div className="admin-form-preview rounded-xl border border-[#d5e6d1] bg-[var(--admin-accent-soft)] p-4" aria-live="polite">
+ <div className="mb-2 flex items-center gap-2 text-xs font-medium text-[var(--admin-forest)]"><Wallet className="h-4 w-4" aria-hidden="true" />保存后的账户余额</div>
+ <div className="flex flex-wrap items-center gap-3 text-lg font-semibold tabular-nums text-[var(--admin-text)]"><span className="text-[var(--admin-muted)]">¥{fenToYuan(editing?.balance_fen ?? 0)}</span><ArrowRight className="h-4 w-4 text-[var(--admin-muted)]" aria-hidden="true" /><span>¥{fenToYuan(balanceAfterFen)}</span><span className="text-xs font-medium text-[var(--admin-forest)]">{form.balance_dir === "decrease" ? "减少" : "增加"} ¥{fenToYuan(amountFen)}</span></div>
+ </div> : null}
+ </fieldset> : null}
+ </section>
+ {saveError ? <p role="alert" className="admin-form-error rounded-lg border border-[#f0d9d5] bg-[#fcf0ee] px-3 py-2.5 text-sm leading-relaxed text-[#aa3d37]">{saveError}</p> : null}
+ </form>
</AdminModal>
</div>
);
diff --git a/admin/src/styles/admin-forms.css b/admin/src/styles/admin-forms.css
new file mode 100644
index 0000000..4703dd3
--- /dev/null
+++ b/admin/src/styles/admin-forms.css
@@ -0,0 +1,99 @@
+/* Form structure: readable sections, visible units, and one clear save boundary. */
+.admin-field-label { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; color: var(--admin-text); font-size: 13px; line-height: 1.5; font-weight: 600; }
+.admin-field-required, .admin-field-optional { font-size: 10px; line-height: 1.5; font-weight: 400; }
+.admin-field-required { color: #a74338; }
+.admin-field-optional { color: #879086; }
+.admin-field-hint { font-size: 12px; line-height: 1.65; color: var(--admin-muted); margin: 0; }
+.admin-field-error { margin: 0; color: #b13b33; font-size: 12px; line-height: 1.6; }
+.admin-form-field.has-error input, .admin-form-field.has-error textarea, .admin-form-field.has-error .admin-select-trigger { border-color: #c86d64; }
+.admin-form-section { display: flex; flex-direction: column; gap: 16px; padding-bottom: 22px; border-bottom: 1px solid var(--admin-border); }
+.admin-form-section:last-child { padding-bottom: 0; border-bottom: 0; }
+.admin-form-section-heading { display: flex; flex-direction: column; gap: 4px; }
+.admin-form-section-title { margin: 0; color: var(--admin-text); font-size: 14px; font-weight: 650; }
+.admin-form-section-description { margin: 0; color: var(--admin-muted); font-size: 12px; line-height: 1.7; }
+.admin-form-summary { display: flex; flex-wrap: wrap; gap: 20px; border: 1px solid var(--admin-border); border-radius: 10px; padding: 15px 17px; background: #f7f9f4; }
+.admin-form-summary-item { display: flex; flex-direction: column; gap: 5px; min-width: 0; }
+.admin-form-summary-item > span { font-size: 12px; color: var(--admin-muted); }
+.admin-form-summary-item > strong { font-size: 16px; font-weight: 600; overflow-wrap: anywhere; }
+.admin-form-summary:has(.admin-form-summary-item) { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }
+.admin-form-summary:not(:has(.admin-form-summary-item)) { flex-direction: column; gap: 4px; }
+.admin-form-section + .admin-form-section { border-top: 0; padding-top: 0; }
+.admin-form-notice, .admin-form-preview { padding: 13px 15px; border: 1px solid #dbe7d3; background: #f4f8ee; border-radius: 9px; color: #3a5d36; font-size: 12px; line-height: 1.7; }
+.admin-form-error { color: #b13b33; font-size: 12px; line-height: 1.6; }
+.settings-page { gap: 22px; }
+.settings-page .settings-head-desc { max-width: 720px; font-size: 13px; line-height: 1.8; }
+.settings-page .settings-routing-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: 20px; align-items: start; }
+.settings-page .settings-tab-body { display: flex; flex-direction: column; gap: 20px; margin: 0; padding: 0; border: 0; min-width: 0; }
+.settings-page .settings-panel { display: grid; grid-template-columns: minmax(180px, 230px) minmax(0, 1fr); overflow: visible; border: 1px solid var(--admin-border); box-shadow: 0 2px 4px rgb(25 34 30 / 2%); border-radius: 12px; }
+.settings-page .settings-panel-header { display: flex; flex-direction: column; justify-content: flex-start; gap: 16px; padding: 24px; border-bottom: 0; border-right: 1px solid var(--admin-border); border-radius: 12px 0 0 12px; background: #fafbf8; }
+.settings-page .settings-panel-title { font-size: 15px; line-height: 1.5; font-weight: 650; color: var(--admin-text); }
+.settings-page .settings-panel-desc { margin-top: 9px; font-size: 12px; line-height: 1.8; color: var(--admin-muted); }
+.settings-page .settings-panel-body { padding: 24px; min-width: 0; }
+.settings-page .settings-field-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px 22px; align-items: start; }
+.settings-page .settings-field-grid--3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+.settings-page .settings-field { min-width: 0; margin: 0; gap: 7px; }
+.settings-page .settings-input, .settings-page .settings-select { min-width: 0; width: 100%; height: 40px; padding: 0 12px; font-size: 13px; line-height: 1.5; border: 1px solid var(--admin-border); border-radius: 9px; background: #fff; }
+.settings-page .settings-input:disabled { background: #f4f6f1; color: #869081; }
+.settings-page .settings-input:focus { outline: 0; border-color: #81a38b; box-shadow: 0 0 0 3px var(--admin-accent-ring); }
+.settings-page .settings-input[aria-invalid='true'] { border-color: #c86d64; }
+.settings-page textarea.settings-input { height: auto; min-height: 100px; padding: 11px 12px; }
+.settings-page .settings-subsection-title { margin: 26px 0 13px; font-size: 13px; color: var(--admin-text); font-weight: 650; }
+.settings-page .settings-toggle-row { padding: 14px 16px; gap: 18px; border: 1px solid var(--admin-border); border-radius: 10px; background: #f8faf5; }
+.settings-page .settings-toggle-row strong { font-size: 13px; line-height: 1.5; }
+.settings-page .settings-toggle-row span { font-size: 12px; line-height: 1.6; }
+.settings-page .settings-panel-footnote { margin: 18px 0 0; font-size: 12px; line-height: 1.75; }
+.settings-page .settings-readiness-bar { padding: 16px 20px; border: 1px solid var(--admin-border); background: #f0f5e9; }
+.settings-readiness-item { min-width: 0; overflow-wrap: anywhere; }
+.settings-save-bar { position: sticky; bottom: 12px; z-index: 15; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 14px; padding: 16px 20px; border: 1px solid #cfdcc6; border-radius: 12px; background: rgb(255 255 255 / 96%); box-shadow: 0 6px 24px rgb(25 34 30 / 8%); backdrop-filter: blur(10px); margin-top: 8px; }
+.settings-save-bar strong { font-size: 13px; font-weight: 600; }
+.settings-save-bar p { margin: 4px 0 0; color: var(--admin-muted); font-size: 12px; line-height: 1.6; }
+.settings-advanced { min-width: 0; border: 1px solid var(--admin-border); border-radius: 10px; background: #fff; }
+.settings-advanced > summary { padding: 15px 18px; cursor: pointer; font-size: 13px; font-weight: 600; color: var(--admin-text); }
+.settings-advanced > summary > span + span { margin-left: 12px; color: var(--admin-muted); font-size: 12px; font-weight: 400; }
+.settings-advanced[open] > summary { border-bottom: 1px solid var(--admin-border); }
+.settings-advanced > :not(summary) { margin: 18px; }
+.settings-advanced .settings-panel { margin: 0; border: 0; border-radius: 0; box-shadow: none; }
+.settings-advanced .settings-panel:last-child .settings-panel-header { border-radius: 0 0 0 10px; }
+.settings-runtime-note { margin: 0; padding: 13px 16px; font-size: 12px; line-height: 1.8; border: 1px solid #dbe7d3; border-radius: 9px; color: #426438; background: #f4f8ee; }
+.settings-secret-row { align-items: stretch; }
+.settings-secret-row > .settings-input { flex: 1; width: 0; }
+.settings-price-heading { margin: 0 0 12px; font-size: 13px; font-weight: 650; }
+.settings-price-table { overflow: auto; }
+.settings-price-table table { min-width: 580px; width: 100%; }
+.settings-price-table td { vertical-align: top; }
+.settings-price-cell { display: flex; flex-wrap: wrap; gap: 14px; }
+.settings-price-cell .admin-form-field { width: 125px; }
+.settings-price-cell .admin-field-label { font-size: 12px; }
+.settings-price-actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 20px; }
+.settings-price-note { margin: 12px 0; color: var(--admin-muted); font-size: 12px; line-height: 1.75; }
+.template-editor-validation { padding: 10px 14px; margin-bottom: 16px; border: 1px solid #e8c9c3; background: #fff7f4; border-radius: 8px; color: #a33c30; font-size: 12px; line-height: 1.7; }
+.template-editor-section-title { grid-column: 1/-1; font-size: 14px; font-weight: 650; margin: 8px 0 0; }
+.template-category-suggestions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 7px; }
+.template-category-suggestions button { border: 1px solid var(--admin-border); border-radius: 6px; background: #f7f9f4; padding: 3px 8px; color: #52664a; cursor: pointer; font-size: 11px; }
+.admin-ui-modal.template-editor-dialog { height: min(900px, 90dvh); }
+.template-editor-dialog .admin-modal-body { display: flex; flex: 1; overflow: hidden; padding: 0; scrollbar-gutter: auto; }
+.template-editor-dialog .template-editor-layout { flex: 1; width: 100%; height: 100%; min-height: 0; max-height: none; }
+.template-editor-dialog .template-editor-preview { min-height: 0; }
+.template-editor-dialog .template-editor-preview-frame, .template-editor-dialog .template-editor-tabs { flex-shrink: 0; }
+.template-editor-dialog .template-editor-panel { min-height: 0; }
+@media (max-width: 768px) {
+ .template-editor-dialog .admin-modal-body { display: block; overflow-y: auto; }
+ .template-editor-dialog .template-editor-layout { height: auto; }
+ .template-editor-dialog .template-editor-preview { display: grid; grid-template-columns: minmax(100px, 140px) minmax(0, 1fr); align-items: start; overflow: visible; }
+ .template-editor-dialog .template-editor-preview .admin-field { grid-column: 1 / -1; }
+ .template-editor-dialog .template-editor-tabs { position: sticky; top: 0; z-index: 5; }
+ .template-editor-dialog .template-editor-panel { overflow: visible; }
+}
+@media (max-width: 1100px) {
+ .settings-page .settings-panel { grid-template-columns: minmax(0, 1fr); }
+ .settings-page .settings-panel-header { border-right: 0; border-bottom: 1px solid var(--admin-border); border-radius: 12px 12px 0 0; padding: 20px; }
+ .settings-page .settings-panel-body { padding: 20px; }
+ .settings-page .settings-panel-desc { margin-top: 5px; }
+}
+@media (max-width: 600px) {
+ .settings-page .settings-panel-header, .settings-page .settings-panel-body { padding: 17px; }
+ .settings-page .settings-field-grid, .settings-page .settings-field-grid--3 { grid-template-columns: minmax(0, 1fr); gap: 18px; }
+ .settings-save-bar { bottom: 8px; padding: 14px; }
+ .settings-save-bar > button { width: 100%; }
+ .settings-advanced > :not(summary) { margin: 14px; }
+}
diff --git a/admin/tests/moneyInput.test.mjs b/admin/tests/moneyInput.test.mjs
new file mode 100644
index 0000000..6d79591
--- /dev/null
+++ b/admin/tests/moneyInput.test.mjs
@@ -0,0 +1,18 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { yuanInputToFen } from '../src/lib/moneyInput.ts';
+
+test('money input converts decimal yuan to exact integer fen', () => {
+ assert.equal(yuanInputToFen('0'), 0);
+ assert.equal(yuanInputToFen('0.29'), 29);
+ assert.equal(yuanInputToFen('1.01'), 101);
+ assert.equal(yuanInputToFen(' 1000.9 '), 100090);
+ assert.equal(yuanInputToFen('001.10'), 110);
+ assert.equal(yuanInputToFen('90071992547409.91'), Number.MAX_SAFE_INTEGER);
+});
+
+test('money input rejects partial, negative, non-finite, rounded or unsafe values', () => {
+ for (const value of ['', ' ', '-1', '+1', '1.', '.5', '1.001', '100abc', '1e3', 'Infinity', 'NaN', '90071992547409.92']) {
+ assert.equal(yuanInputToFen(value), null, value);
+ }
+});
diff --git a/admin/tests/templateForm.test.mjs b/admin/tests/templateForm.test.mjs
new file mode 100644
index 0000000..541bcc2
--- /dev/null
+++ b/admin/tests/templateForm.test.mjs
@@ -0,0 +1,21 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { validateTemplateDraft } from '../src/lib/templateForm.ts';
+
+const valid = { id: 'film', name: '电影风格', shot_duration_min: 3, shot_duration_max: 8, sort_order: 0 };
+test('template identity is required for creation and name is required for every save', () => {
+ assert.ok(validateTemplateDraft({ ...valid, id: ' ', name: ' ' }, true).id);
+ assert.ok(validateTemplateDraft({ ...valid, name: ' ' }, false).name);
+ assert.equal(validateTemplateDraft({ ...valid, id: '' }, false).id, undefined);
+});
+test('template durations reject fractional, zero, nonfinite and inverted ranges', () => {
+ for (const value of [0, -1, 1.5, NaN, Infinity]) assert.ok(validateTemplateDraft({ ...valid, shot_duration_min: value }, true).shot_duration_min);
+ assert.ok(validateTemplateDraft({ ...valid, shot_duration_max: 2 }, true).shot_duration_max);
+ assert.deepEqual(validateTemplateDraft({ ...valid, shot_duration_min: 8 }, true), {});
+});
+test('template limits and sort values are validated without rejecting valid negative sort order', () => {
+ assert.ok(validateTemplateDraft({ ...valid, id: 'x'.repeat(65) }, true).id);
+ assert.ok(validateTemplateDraft({ ...valid, name: 'x'.repeat(129) }, true).name);
+ assert.ok(validateTemplateDraft({ ...valid, sort_order: 0.5 }, true).sort_order);
+ assert.deepEqual(validateTemplateDraft({ ...valid, sort_order: -2 }, true), {});
+});