Skip to content

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

feat: 管理端按增减调账并记录操作人,MiniMax-H3 开放 480p/768p

yib3b258052860
diff --git a/admin/src/App.tsx b/admin/src/App.tsx
index 4a6cf92..2659b25 100644
--- a/admin/src/App.tsx
+++ b/admin/src/App.tsx
@@ -1,6 +1,7 @@
import { Navigate, Outlet, Route, Routes } from "react-router-dom";
import { AdminLayout } from "@/components/layout/AdminLayout";
import { getCachedUser, getToken, isAdminUser } from "@/lib/auth";
+import { AdjustRecordsPage } from "@/pages/AdjustRecordsPage";
import { FinanceListPage } from "@/pages/FinanceListPage";
import { DashboardPage } from "@/pages/DashboardPage";
import { LoginPage } from "@/pages/LoginPage";
@@ -40,6 +41,7 @@ export default function App() {
<Route index element={<DashboardPage />} />
<Route path="users" element={<UsersPage />} />
<Route path="orders" element={<OrdersPage />} />
+ <Route path="adjustments" element={<AdjustRecordsPage />} />
<Route path="finance" element={<FinanceListPage />} />
<Route path="projects" element={<ProjectsPage />} />
<Route path="drama-projects" element={<DramaProjectsPage />} />
diff --git a/admin/src/api/client.ts b/admin/src/api/client.ts
index 14710a9..32bba02 100644
--- a/admin/src/api/client.ts
+++ b/admin/src/api/client.ts
@@ -232,6 +232,8 @@ export type AdminLedger = {
ref_id: string;
note: string;
created_at: string;
+ /** 手动调账操作人邮箱(ref_type=admin 时) */
+ operator_email?: string | null;
};
export type AdminProject = {
diff --git a/admin/src/components/layout/AdminLayout.tsx b/admin/src/components/layout/AdminLayout.tsx
index 16fe00c..8d53fbd 100644
--- a/admin/src/components/layout/AdminLayout.tsx
+++ b/admin/src/components/layout/AdminLayout.tsx
@@ -28,6 +28,8 @@ import {
Receipt,
+ Scale,
+
Settings,
Shapes,
@@ -89,6 +91,9 @@ const navGroups: NavGroup[] = [
{ to: "/users", label: "用户管理", icon: Users },
{ to: "/orders", label: "订单流水", icon: Receipt },
+
+ { to: "/adjustments", label: "手动调账", icon: Scale },
+
{ to: "/finance", label: "财务列表", icon: Wallet },
{ to: "/projects", label: "科普项目", icon: Clapperboard },
@@ -150,6 +155,9 @@ const titles: Record<string, string> = {
"/users": "用户管理",
"/orders": "订单流水",
+
+ "/adjustments": "手动调账",
+
"/finance": "财务列表",
"/projects": "科普项目",
diff --git a/admin/src/pages/AdjustRecordsPage.tsx b/admin/src/pages/AdjustRecordsPage.tsx
new file mode 100644
index 0000000..3bd5aba
--- /dev/null
+++ b/admin/src/pages/AdjustRecordsPage.tsx
@@ -0,0 +1,194 @@
+import { useCallback, useEffect, useState } from "react";
+import { toast } from "sonner";
+import { api, type AdminLedger, type PageMeta } from "@/api/client";
+import { AdminDateRangeFilter } from "@/components/admin/AdminDateRangeFilter";
+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";
+import { AdminFilterBar } from "@/components/admin/AdminFilterBar";
+import { AdminUserSearchSelect } from "@/components/admin/AdminUserSearchSelect";
+import { PageSection } from "@/components/admin/PageSection";
+import { PaginationBar } from "@/components/PaginationBar";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { PageHeader } from "@/components/ui/page";
+import { Select } from "@/components/ui/select";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
+import { fenToYuan } from "@/lib/utils";
+
+type LedgerRes = { items: AdminLedger[]; meta: PageMeta };
+
+type DirectionFilter = "" | "credit" | "debit";
+
+/** 将 YYYY-MM-DD 转为东八区 ISO 边界(与订单用量筛选一致) */
+function toDayBoundary(date: string, endOfDay: boolean): string | null {
+ if (!date.trim()) return null;
+ return endOfDay ? `${date.trim()}T23:59:59+08:00` : `${date.trim()}T00:00:00+08:00`;
+}
+
+/** 调账方向文案:正数为调增,负数为调减 */
+function directionLabel(deltaFen: number): string {
+ return deltaFen >= 0 ? "调增" : "调减";
+}
+
+/** 管理端手动调账记录:仅展示 ref_type=admin 的钱包流水 */
+export function AdjustRecordsPage() {
+ const [userId, setUserId] = useState<number | null>(null);
+ const [direction, setDirection] = useState<DirectionFilter>("");
+ const [dateFrom, setDateFrom] = useState("");
+ const [dateTo, setDateTo] = useState("");
+ const [page, setPage] = useState(1);
+ const [data, setData] = useState<LedgerRes | null>(null);
+ const [loading, setLoading] = useState(true);
+
+ const load = useCallback(
+ async (nextPage = page) => {
+ setLoading(true);
+ try {
+ const params = new URLSearchParams({
+ page: String(nextPage),
+ page_size: String(DEFAULT_PAGE_SIZE),
+ ref_type: "admin",
+ });
+ if (userId) params.set("user_id", String(userId));
+ // 后台写流水:调减 kind=adjust,调增 kind=grant
+ if (direction === "credit") params.set("kind", "grant");
+ if (direction === "debit") params.set("kind", "adjust");
+ const fromIso = toDayBoundary(dateFrom, false);
+ const toIso = toDayBoundary(dateTo, true);
+ if (fromIso) params.set("created_from", fromIso);
+ if (toIso) params.set("created_to", toIso);
+ setData(await api<LedgerRes>(`/api/admin/ledger?${params}`));
+ } catch (err) {
+ setData(null);
+ toast.error(err instanceof Error ? err.message : "加载调账记录失败");
+ } finally {
+ setLoading(false);
+ }
+ },
+ [page, userId, direction, dateFrom, dateTo],
+ );
+
+ useEffect(() => {
+ void load(page);
+ }, [load, page]);
+
+ const rows = data?.items ?? [];
+
+ return (
+ <div className="admin-page">
+ <PageHeader description="用户管理里手动改余额产生的调账流水,含操作人与备注" />
+
+ <AdminFilterBar>
+ <AdminUserSearchSelect value={userId} onChange={setUserId} />
+ <Select
+ value={direction}
+ onChange={(e) => setDirection(e.target.value as DirectionFilter)}
+ >
+ <option value="">全部方向</option>
+ <option value="credit">调增</option>
+ <option value="debit">调减</option>
+ </Select>
+ <AdminDateRangeFilter
+ from={dateFrom}
+ to={dateTo}
+ onChange={({ from, to }) => {
+ setDateFrom(from);
+ setDateTo(to);
+ }}
+ />
+ <Button
+ size="sm"
+ variant="secondary"
+ className="admin-filter-action"
+ onClick={() => {
+ setPage(1);
+ void load(1);
+ }}
+ >
+ 筛选
+ </Button>
+ </AdminFilterBar>
+
+ <PageSection
+ title="手动调账记录"
+ description={data ? `共 ${data.meta.total} 条` : undefined}
+ bodyClassName="!pt-0"
+ >
+ <div className="admin-table-wrap">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>ID</TableHead>
+ <TableHead>时间</TableHead>
+ <TableHead>用户</TableHead>
+ <TableHead>方向</TableHead>
+ <TableHead>变动</TableHead>
+ <TableHead>余额后</TableHead>
+ <TableHead>操作人</TableHead>
+ <TableHead>备注</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {loading ? (
+ <TableRow>
+ <TableCell colSpan={8} className="!text-center text-[var(--admin-muted)]">
+ 加载中…
+ </TableCell>
+ </TableRow>
+ ) : rows.length === 0 ? (
+ <TableRow>
+ <TableCell colSpan={8} className="!text-center text-[var(--admin-muted)]">
+ 暂无手动调账记录
+ </TableCell>
+ </TableRow>
+ ) : (
+ rows.map((row) => (
+ <TableRow key={row.id}>
+ <TableCell className="font-mono text-xs">{row.id}</TableCell>
+ <TableCell className="text-xs text-muted-foreground whitespace-nowrap">
+ {new Date(row.created_at).toLocaleString()}
+ </TableCell>
+ <TableCell>
+ <AdminEntityLink kind="user" id={row.user_id} label={row.user_email ?? undefined} />
+ </TableCell>
+ <TableCell>
+ <Badge variant={row.delta_fen >= 0 ? "success" : "secondary"}>
+ {directionLabel(row.delta_fen)}
+ </Badge>
+ </TableCell>
+ <TableCell className={row.delta_fen >= 0 ? "text-emerald-700" : "text-red-600"}>
+ {row.delta_fen >= 0 ? "+" : ""}¥{fenToYuan(row.delta_fen)}
+ </TableCell>
+ <TableCell>¥{fenToYuan(row.balance_after)}</TableCell>
+ <TableCell>
+ {row.ref_id && /^\d+$/.test(row.ref_id) ? (
+ <AdminEntityLink
+ kind="user"
+ id={Number(row.ref_id)}
+ label={row.operator_email ?? undefined}
+ />
+ ) : (
+ row.operator_email || "—"
+ )}
+ </TableCell>
+ <TableCell className="max-w-[240px] truncate" title={row.note || undefined}>
+ {row.note || "—"}
+ </TableCell>
+ </TableRow>
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ {data ? (
+ <PaginationBar
+ page={data.meta.page}
+ pageSize={data.meta.page_size}
+ total={data.meta.total}
+ onPageChange={setPage}
+ />
+ ) : null}
+ </PageSection>
+ </div>
+ );
+}
diff --git a/admin/src/pages/UsersPage.tsx b/admin/src/pages/UsersPage.tsx
index 2d9d735..491cbfc 100644
--- a/admin/src/pages/UsersPage.tsx
+++ b/admin/src/pages/UsersPage.tsx
@@ -34,7 +34,10 @@ export function UsersPage() {
const [detailUser, setDetailUser] = useState<AdminUserRow | null>(null);
const [form, setForm] = useState({
role: "user",
- balance_yuan: "0",
+ /** increase=增加 / decrease=减少 */
+ balance_dir: "increase" as "increase" | "decrease",
+ /** 调账金额(元),空表示不改余额 */
+ balance_amount_yuan: "",
balance_note: "",
});
const [saving, setSaving] = useState(false);
@@ -82,7 +85,8 @@ export function UsersPage() {
setEditing(user);
setForm({
role: user.role || "user",
- balance_yuan: fenToYuan(user.balance_fen),
+ balance_dir: "increase",
+ balance_amount_yuan: "",
balance_note: "",
});
}
@@ -91,17 +95,34 @@ export function UsersPage() {
if (!editing) return;
setSaving(true);
try {
- const balanceFen = Math.round(parseFloat(form.balance_yuan || "0") * 100);
- if (Number.isNaN(balanceFen)) throw new Error("余额格式无效");
+ const payload: {
+ role: string;
+ balance_delta_fen?: number;
+ 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;
+ }
+ }
+
await api(`/api/admin/users/${editing.id}`, {
method: "PATCH",
- body: JSON.stringify({
- role: form.role,
- balance_fen: balanceFen,
- balance_note: form.balance_note || undefined,
- }),
+ body: JSON.stringify(payload),
});
- toast.success("已保存");
+ toast.success(payload.balance_delta_fen ? "已调账并保存" : "已保存");
setEditing(null);
await load();
} catch (err) {
@@ -255,13 +276,44 @@ export function UsersPage() {
<option value="admin">admin</option>
</Select>
</AdminField>
- <AdminField label="余额(元)">
+ <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
- value={form.balance_yuan}
- onChange={(e) => setForm((f) => ({ ...f, balance_yuan: e.target.value }))}
+ 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="可选">
+ <AdminField label="调账备注" hint="可选;仅改余额时写入流水">
<Input
value={form.balance_note}
onChange={(e) => setForm((f) => ({ ...f, balance_note: e.target.value }))}
diff --git a/backend/app/api/admin/ledger.py b/backend/app/api/admin/ledger.py
index d2216f3..51040d1 100644
--- a/backend/app/api/admin/ledger.py
+++ b/backend/app/api/admin/ledger.py
@@ -1,4 +1,6 @@
# Admin wallet ledger list
+from datetime import datetime
+
from fastapi import APIRouter, Depends, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -16,12 +18,15 @@ router = APIRouter()
async def list_ledger(
user_id: int | None = None,
kind: str | None = None,
+ ref_type: str | None = None,
+ created_from: datetime | None = None,
+ created_to: datetime | None = None,
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
) -> AdminLedgerListOut:
- # Paginated wallet ledger with owner email
+ # Paginated wallet ledger with owner email and admin operator email
owner = aliased(User)
stmt = select(WalletLedger, owner.email).outerjoin(owner, owner.id == WalletLedger.user_id)
count_stmt = select(func.count()).select_from(WalletLedger)
@@ -32,6 +37,15 @@ async def list_ledger(
if kind and kind.strip():
stmt = stmt.where(WalletLedger.kind == kind.strip())
count_stmt = count_stmt.where(WalletLedger.kind == kind.strip())
+ if ref_type and ref_type.strip():
+ stmt = stmt.where(WalletLedger.ref_type == ref_type.strip())
+ count_stmt = count_stmt.where(WalletLedger.ref_type == ref_type.strip())
+ if created_from is not None:
+ stmt = stmt.where(WalletLedger.created_at >= created_from)
+ count_stmt = count_stmt.where(WalletLedger.created_at >= created_from)
+ if created_to is not None:
+ stmt = stmt.where(WalletLedger.created_at <= created_to)
+ count_stmt = count_stmt.where(WalletLedger.created_at <= created_to)
total = int((await db.execute(count_stmt)).scalar_one() or 0)
rows = (
@@ -42,10 +56,24 @@ async def list_ledger(
)
).all()
+ operator_ids: set[int] = set()
+ for entry, _email in rows:
+ if entry.ref_type == "admin" and str(entry.ref_id or "").isdigit():
+ operator_ids.add(int(entry.ref_id))
+
+ operator_emails: dict[int, str] = {}
+ if operator_ids:
+ op_rows = (
+ await db.execute(select(User.id, User.email).where(User.id.in_(operator_ids)))
+ ).all()
+ operator_emails = {int(uid): (email or "") for uid, email in op_rows}
+
items: list[AdminLedgerOut] = []
for entry, email in rows:
data = AdminLedgerOut.model_validate(entry)
data.user_email = email
+ if entry.ref_type == "admin" and str(entry.ref_id or "").isdigit():
+ data.operator_email = operator_emails.get(int(entry.ref_id)) or None
items.append(data)
return AdminLedgerListOut(
diff --git a/backend/app/api/admin/users.py b/backend/app/api/admin/users.py
index 87fee0b..8605c75 100644
--- a/backend/app/api/admin/users.py
+++ b/backend/app/api/admin/users.py
@@ -76,25 +76,35 @@ async def patch_user(
raise HTTPException(status_code=400, detail="不能降低自己的管理员权限")
user.role = role
- if body.balance_fen is not None:
+ if body.balance_delta_fen is not None and body.balance_fen is not None:
+ raise HTTPException(status_code=400, detail="请只传 balance_delta_fen 或 balance_fen 之一")
+
+ current = int(user.balance_fen or 0)
+ delta: int | None = None
+ if body.balance_delta_fen is not None:
+ delta = int(body.balance_delta_fen)
+ elif body.balance_fen is not None:
target = int(body.balance_fen)
if target < 0:
raise HTTPException(status_code=400, detail="余额不能为负")
- current = int(user.balance_fen or 0)
delta = target - current
- if delta != 0:
- user.balance_fen = target
- db.add(
- WalletLedger(
- user_id=user.id,
- delta_fen=delta,
- balance_after=target,
- kind="adjust" if delta < 0 else "grant",
- ref_type="admin",
- ref_id=str(admin.id),
- note=(body.balance_note or "").strip() or "admin_adjust",
- )
+
+ if delta is not None and delta != 0:
+ target = current + delta
+ if target < 0:
+ raise HTTPException(status_code=400, detail="余额不能减为负数")
+ user.balance_fen = target
+ db.add(
+ WalletLedger(
+ user_id=user.id,
+ delta_fen=delta,
+ balance_after=target,
+ kind="adjust" if delta < 0 else "grant",
+ ref_type="admin",
+ ref_id=str(admin.id),
+ note=(body.balance_note or "").strip() or "admin_adjust",
)
+ )
await db.commit()
await db.refresh(user)
diff --git a/backend/app/schemas.py b/backend/app/schemas.py
index 8c1c0de..7a06dee 100644
--- a/backend/app/schemas.py
+++ b/backend/app/schemas.py
@@ -489,7 +489,9 @@ class AdminUserListOut(BaseModel):
class AdminUserPatch(BaseModel):
plan: str | None = None
role: str | None = None
- # Absolute target balance in fen; when set, write ledger delta
+ # 相对调账(分):正数增加、负数减少;与 balance_fen 互斥,优先本字段
+ balance_delta_fen: int | None = None
+ # 兼容旧客户端:绝对目标余额(分)
balance_fen: int | None = None
balance_note: str | None = None
@@ -527,6 +529,8 @@ class AdminLedgerOut(BaseModel):
ref_id: str
note: str
created_at: datetime
+ # 手动调账时 ref_type=admin,ref_id 为操作管理员 id
+ operator_email: str | None = None
model_config = {"from_attributes": True}
diff --git a/backend/app/services/drama/build_seedance_generate_body.py b/backend/app/services/drama/build_seedance_generate_body.py
index 3b52d94..d2cc160 100644
--- a/backend/app/services/drama/build_seedance_generate_body.py
+++ b/backend/app/services/drama/build_seedance_generate_body.py
@@ -1155,10 +1155,10 @@ def resolve_seedance_resolution(
*,
model_id: str | None = None,
) -> str:
- """解析并按模型能力钳制清晰度。"""
- from app.services.seedance_resolutions import clamp_video_resolution
+ """解析并按模型能力钳制清晰度(MiniMax 提交小写 480p/768p)。"""
+ from app.services.seedance_resolutions import format_video_resolution_for_upstream
- return clamp_video_resolution(model_id, resolution)
+ return format_video_resolution_for_upstream(model_id, resolution)
# 将分镜参数转为 Seedance 请求体
diff --git a/backend/app/services/media_model_presets.py b/backend/app/services/media_model_presets.py
index 2397812..883004f 100644
--- a/backend/app/services/media_model_presets.py
+++ b/backend/app/services/media_model_presets.py
@@ -94,7 +94,7 @@ PRESET_MODELS: dict[LogicalModelCapability, tuple[dict[str, str], ...]] = {
{
"id": "MiniMax-H3",
"label": "MiniMax H3",
- "note": "节奏感强、人物生动;4–15 秒,仅 720p",
+ "note": "节奏感强、人物生动;4–15 秒,480p / 768p",
"pricing_hint": "出片偏慢 · 约 ¥0.44–0.73/秒",
"eta_hint": "偏慢,4s 约 15 分钟起",
},
@@ -130,8 +130,8 @@ IMAGE_RESOLUTIONS_GPT_IMAGE_25: tuple[str, ...] = ("1K", "2K", "4K")
VIDEO_ASPECT_RATIOS: tuple[str, ...] = ("9:16", "16:9", "1:1")
VIDEO_RESOLUTIONS_FULL: tuple[str, ...] = ("480p", "720p", "1080p")
VIDEO_RESOLUTIONS_SAFE: tuple[str, ...] = ("480p", "720p")
-# MiniMax-H3 当前渠道仅 720p
-VIDEO_RESOLUTIONS_720_ONLY: tuple[str, ...] = ("720p",)
+# MiniMax-H3:TokenFree 枚举为小写 480p / 768p
+VIDEO_RESOLUTIONS_MINIMAX_H3: tuple[str, ...] = ("480p", "768p")
# 历史友好别名 / 旧连字符 id → TokenFree 点分规范 id
@@ -310,7 +310,7 @@ def model_generation_options(model_id: str | None) -> dict[str, Any]:
return {
"capability": "video",
"allowed_aspect_ratios": list(VIDEO_ASPECT_RATIOS),
- "allowed_resolutions": list(VIDEO_RESOLUTIONS_720_ONLY),
+ "allowed_resolutions": list(VIDEO_RESOLUTIONS_MINIMAX_H3),
"duration_min": 4,
"duration_max": 15,
}
diff --git a/backend/app/services/seedance_resolutions.py b/backend/app/services/seedance_resolutions.py
index a183537..1d3a98c 100644
--- a/backend/app/services/seedance_resolutions.py
+++ b/backend/app/services/seedance_resolutions.py
@@ -4,11 +4,12 @@ from __future__ import annotations
from app.services.model_routing_config import normalize_model_name
-# 全量 UI / 白名单最高档(不上 4k)
-ALL_VIDEO_RESOLUTIONS: tuple[str, ...] = ("480p", "720p", "1080p")
+# 全量 UI / 白名单(含 MiniMax 的 768p;不上 4k)
+ALL_VIDEO_RESOLUTIONS: tuple[str, ...] = ("480p", "720p", "768p", "1080p")
# mini / fast:渠道明确仅两档
SAFE_VIDEO_RESOLUTIONS: tuple[str, ...] = ("480p", "720p")
FULL_VIDEO_RESOLUTIONS: tuple[str, ...] = ("480p", "720p", "1080p")
+MINIMAX_H3_VIDEO_RESOLUTIONS: tuple[str, ...] = ("480p", "768p")
def allowed_video_resolutions(model_id: str | None) -> list[str]:
@@ -16,7 +17,7 @@ def allowed_video_resolutions(model_id: str | None) -> list[str]:
优先读站点预设表;否则:
- Seedance 2.5 → 含 1080p
- - MiniMax-H3 → 仅 720p
+ - MiniMax-H3 → 480p / 768p
- Seedance 2.0 / mini / fast / 其它 → 480p, 720p
"""
mid = normalize_model_name(model_id or "")
@@ -28,13 +29,17 @@ def allowed_video_resolutions(model_id: str | None) -> list[str]:
opts = model_generation_options(model_id)
raw = opts.get("allowed_resolutions") if isinstance(opts, dict) else None
if isinstance(raw, list) and raw:
- filtered = [str(x).strip().lower() for x in raw if str(x).strip().lower() in ALL_VIDEO_RESOLUTIONS]
+ filtered = [
+ str(x).strip().lower()
+ for x in raw
+ if str(x).strip().lower() in ALL_VIDEO_RESOLUTIONS
+ ]
if filtered:
return filtered
- # MiniMax H3:仅 720p(须先于其它启发式,避免被当成 mini)
+ # MiniMax H3:480p / 768p(须先于其它启发式,避免被当成 mini)
if "minimax" in mid and "h3" in mid.replace("-", "").replace("_", ""):
- return ["720p"]
+ return list(MINIMAX_H3_VIDEO_RESOLUTIONS)
# 仅 Seedance 2.5 含 1080p
if "seedance" in mid and ("2.5" in mid or "2-5" in mid):
@@ -49,10 +54,27 @@ def clamp_video_resolution(model_id: str | None, resolution: str | None) -> str:
raw = (resolution or "").strip().lower()
if raw in allowed:
return raw
- # 缺省 / 非法:取允许列表中最高档(通常 720p 或 1080p)
+ # MiniMax:历史 720p/1080p 就近落到 768p
+ mid = normalize_model_name(model_id or "")
+ if (
+ "minimax" in mid
+ and "h3" in mid.replace("-", "").replace("_", "")
+ and raw in {"720p", "1080p", "2k"}
+ and "768p" in allowed
+ ):
+ return "768p"
+ # 缺省 / 非法:取允许列表中最高档(通常 720p / 768p / 1080p)
return allowed[-1]
+def format_video_resolution_for_upstream(model_id: str | None, resolution: str | None) -> str:
+ """提交上游的清晰度字符串。
+
+ TokenFree MiniMax 插件枚举只认小写 480p / 768p(大写 480P 会报 plugin_usage_invalid)。
+ """
+ return clamp_video_resolution(model_id, resolution)
+
+
def video_duration_bounds(model_id: str | None) -> tuple[int, int]:
"""返回 (min, max) 秒;与站点 seedance_duration_* 取交集,缺省 4–30。"""
from app.config import get_settings
diff --git a/backend/app/services/tokenfree_pricing.py b/backend/app/services/tokenfree_pricing.py
index db1ef8b..f3784b2 100644
--- a/backend/app/services/tokenfree_pricing.py
+++ b/backend/app/services/tokenfree_pricing.py
@@ -122,15 +122,15 @@ VENDOR_VIDEO_YUAN_5S_BY_RES.update(
)
# Seedance 秒价表硬底:仅挡住低于旧错误表 ¥0.50/秒 的脏数据
SEEDANCE_VENDOR_FLOOR_YUAN_PER_SEC = 0.5
-# MiniMax-H3:约 $0.08/秒(768P);本站仅开放 720p;人民币按 billing_usd_cny 折算
-MINIMAX_H3_USD_PER_SEC_720P = 0.08
+# MiniMax-H3:约 $0.08/秒(768P 档参考);开放 480p / 768p;人民币按 billing_usd_cny 折算
+MINIMAX_H3_USD_PER_SEC = 0.08
def minimax_h3_yuan_per_sec(settings: Settings | None = None) -> float:
- """MiniMax-H3 720p 结算参考秒价(人民币)。"""
+ """MiniMax-H3 结算参考秒价(人民币,按 768P 档)。"""
s = settings or get_settings()
fx = float(getattr(s, "billing_usd_cny", 0) or 7.3)
- return MINIMAX_H3_USD_PER_SEC_720P * fx
+ return MINIMAX_H3_USD_PER_SEC * fx
# 兼容旧逻辑:480P 秒价(= 5 秒价 / 5)
@@ -143,9 +143,10 @@ VENDOR_VIDEO_YUAN_PER_SEC_480P = {
VIDEO_RESOLUTION_MULT = {
"480p": 1.0,
"720p": 2.0,
+ "768p": 2.0,
"1080p": 4.0,
}
-_VIDEO_RES_ORDER = ("480p", "720p", "1080p")
+_VIDEO_RES_ORDER = ("480p", "720p", "768p", "1080p")
# Kie sunburst 控制台档(USD / credits);公开 /api/pricing 往往只有笼统 gpt-image-2-5
KIE_SUNBURST_USD_1K = 0.03
KIE_SUNBURST_USD_2K = 0.05
@@ -230,7 +231,7 @@ RECOMMENDED_MODELS: tuple[dict[str, Any], ...] = (
"id": "MiniMax-H3",
"capability": "video",
"label": "MiniMax H3",
- "note": "4–15 秒,仅 720p",
+ "note": "4–15 秒,480p / 768p",
"recommended": False,
},
{
@@ -671,7 +672,7 @@ def charge_fen_official_llm(tokens: int, settings: Settings, *, model: str = "")
def normalize_video_resolution(resolution: str | None, settings: Settings | None = None) -> str:
- """预估用清晰度:只认 480p/720p/1080p。"""
+ """预估用清晰度:认 480p/720p/768p/1080p。"""
raw = (resolution or "").strip().lower()
if raw in VIDEO_RESOLUTION_MULT:
return raw
@@ -776,7 +777,7 @@ def format_video_pricing_hint(model: str) -> str:
if expr_parts:
return "按清晰度×时长 · " + " · ".join(expr_parts)
if _is_minimax_video_model(mid):
- return f"约 ¥{minimax_h3_yuan_per_sec():.2f}/秒 · 仅 720p"
+ return f"约 ¥{minimax_h3_yuan_per_sec():.2f}/秒 · 480p/768p"
key = _resolve_vendor_video_key(mid)
tiers = VENDOR_VIDEO_YUAN_5S_BY_RES.get(key)
if not tiers:
diff --git a/backend/tests/test_admin_ledger_adjust.py b/backend/tests/test_admin_ledger_adjust.py
new file mode 100644
index 0000000..6d24852
--- /dev/null
+++ b/backend/tests/test_admin_ledger_adjust.py
@@ -0,0 +1,66 @@
+"""手动调账流水列表:ref_type=admin 筛选与操作人邮箱。"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.admin.ledger import list_ledger
+from app.models import WalletLedger
+from tests.conftest import make_user
+
+
+async def test_admin_ledger_filters_ref_type_admin(db_session: AsyncSession) -> None:
+ # 造一条后台调账 + 一条注册赠送,仅调账应命中 ref_type=admin
+ user = await make_user(db_session, balance_fen=1000)
+ user.email = f"ledger-user-{uuid.uuid4().hex[:8]}@example.com"
+ admin = await make_user(db_session, balance_fen=0)
+ admin.email = f"ledger-admin-{uuid.uuid4().hex[:8]}@example.com"
+ admin.role = "admin"
+ await db_session.flush()
+
+ db_session.add_all(
+ [
+ WalletLedger(
+ user_id=user.id,
+ delta_fen=500,
+ balance_after=1500,
+ kind="grant",
+ ref_type="admin",
+ ref_id=str(admin.id),
+ note="手动充值",
+ ),
+ WalletLedger(
+ user_id=user.id,
+ delta_fen=100,
+ balance_after=100,
+ kind="grant",
+ ref_type="",
+ ref_id="",
+ note="signup_grant",
+ ),
+ ]
+ )
+ await db_session.commit()
+
+ out = await list_ledger(
+ user_id=None,
+ kind=None,
+ ref_type="admin",
+ created_from=None,
+ created_to=None,
+ page=1,
+ page_size=20,
+ _admin=admin,
+ db=db_session,
+ )
+ assert out.meta.total == 1
+ assert len(out.items) == 1
+ row = out.items[0]
+ assert row.ref_type == "admin"
+ assert row.note == "手动充值"
+ assert row.user_email == user.email
+ assert row.operator_email == admin.email
diff --git a/backend/tests/test_admin_user_balance_delta.py b/backend/tests/test_admin_user_balance_delta.py
new file mode 100644
index 0000000..0c73a23
--- /dev/null
+++ b/backend/tests/test_admin_user_balance_delta.py
@@ -0,0 +1,96 @@
+"""管理端用户调账:按增减金额(balance_delta_fen)而非设为目标余额。"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.admin.users import patch_user
+from app.models import WalletLedger
+from app.schemas import AdminUserPatch
+from tests.conftest import make_user
+
+
+async def test_admin_patch_user_balance_delta_increase(db_session: AsyncSession) -> None:
+ admin = await make_user(db_session, balance_fen=0)
+ admin.email = f"admin-{uuid.uuid4().hex[:8]}@example.com"
+ admin.role = "admin"
+ user = await make_user(db_session, balance_fen=1000)
+ user.email = f"user-{uuid.uuid4().hex[:8]}@example.com"
+ await db_session.commit()
+
+ out = await patch_user(
+ user_id=user.id,
+ body=AdminUserPatch(balance_delta_fen=500, balance_note="补款"),
+ admin=admin,
+ db=db_session,
+ )
+ assert out.balance_fen == 1500
+
+ ledgers = (
+ await db_session.execute(
+ select(WalletLedger).where(
+ WalletLedger.user_id == user.id,
+ WalletLedger.ref_type == "admin",
+ )
+ )
+ ).scalars().all()
+ assert len(ledgers) == 1
+ assert ledgers[0].delta_fen == 500
+ assert ledgers[0].kind == "grant"
+ assert ledgers[0].note == "补款"
+ assert ledgers[0].ref_id == str(admin.id)
+
+
+async def test_admin_patch_user_balance_delta_decrease(db_session: AsyncSession) -> None:
+ admin = await make_user(db_session, balance_fen=0)
+ admin.email = f"admin-{uuid.uuid4().hex[:8]}@example.com"
+ admin.role = "admin"
+ user = await make_user(db_session, balance_fen=1000)
+ user.email = f"user-{uuid.uuid4().hex[:8]}@example.com"
+ await db_session.commit()
+
+ out = await patch_user(
+ user_id=user.id,
+ body=AdminUserPatch(balance_delta_fen=-300),
+ admin=admin,
+ db=db_session,
+ )
+ assert out.balance_fen == 700
+
+ row = (
+ await db_session.execute(
+ select(WalletLedger).where(WalletLedger.user_id == user.id, WalletLedger.ref_type == "admin")
+ )
+ ).scalar_one()
+ assert row.delta_fen == -300
+ assert row.kind == "adjust"
+
+
+async def test_admin_patch_user_balance_delta_rejects_negative_result(
+ db_session: AsyncSession,
+) -> None:
+ from fastapi import HTTPException
+
+ admin = await make_user(db_session, balance_fen=0)
+ admin.email = f"admin-{uuid.uuid4().hex[:8]}@example.com"
+ admin.role = "admin"
+ user = await make_user(db_session, balance_fen=100)
+ user.email = f"user-{uuid.uuid4().hex[:8]}@example.com"
+ await db_session.commit()
+
+ with pytest.raises(HTTPException) as exc:
+ await patch_user(
+ user_id=user.id,
+ body=AdminUserPatch(balance_delta_fen=-200),
+ admin=admin,
+ db=db_session,
+ )
+ assert exc.value.status_code == 400
+ assert "负" in str(exc.value.detail)
diff --git a/backend/tests/test_media_model_presets.py b/backend/tests/test_media_model_presets.py
index aa0d3c9..c010f5d 100644
--- a/backend/tests/test_media_model_presets.py
+++ b/backend/tests/test_media_model_presets.py
@@ -91,7 +91,7 @@ def test_build_body_clamps_minimax_duration() -> None:
}
)
assert body["duration"] == 15
- assert body["resolution"] == "720p"
+ assert body["resolution"] == "768p"
def test_image_options_standard_1k_2k() -> None:
@@ -107,15 +107,17 @@ def test_image_options_standard_1k_2k() -> None:
def test_minimax_h3_video_options() -> None:
opts = model_generation_options("MiniMax-H3")
assert opts["capability"] == "video"
- assert opts["allowed_resolutions"] == ["720p"]
+ assert opts["allowed_resolutions"] == ["480p", "768p"]
assert opts["duration_min"] == 4
assert opts["duration_max"] == 15
- assert allowed_video_resolutions("MiniMax-H3") == ["720p"]
+ assert allowed_video_resolutions("MiniMax-H3") == ["480p", "768p"]
assert video_duration_bounds("MiniMax-H3") == (4, 15)
assert clamp_video_duration("MiniMax-H3", 30) == 15
assert clamp_video_duration("MiniMax-H3", 8) == 8
- assert clamp_video_resolution("MiniMax-H3", "1080p") == "720p"
- assert clamp_video_resolution("MiniMax-H3", "480p") == "720p"
+ assert clamp_video_resolution("MiniMax-H3", "1080p") == "768p"
+ assert clamp_video_resolution("MiniMax-H3", "720p") == "768p"
+ assert clamp_video_resolution("MiniMax-H3", "480p") == "480p"
+ assert clamp_video_resolution("MiniMax-H3", "768p") == "768p"
def test_seedance_20_options_safe() -> None:
@@ -172,7 +174,7 @@ def test_catalog_image_row_has_allowed_params() -> None:
assert img["pricing_hint"]
vid = {row["id"]: row for row in payload["video_models"]}["MiniMax-H3"]
assert vid["duration_max"] == 15
- assert vid["allowed_resolutions"] == ["720p"]
+ assert vid["allowed_resolutions"] == ["480p", "768p"]
assert "MiniMax" in vid["description"] or vid["description"]
assert vid["pricing_hint"]
assert vid["eta_hint"]
diff --git a/backend/tests/test_seedance_resolutions.py b/backend/tests/test_seedance_resolutions.py
index 2b2707e..1bfa4d2 100644
--- a/backend/tests/test_seedance_resolutions.py
+++ b/backend/tests/test_seedance_resolutions.py
@@ -34,11 +34,19 @@ def test_unknown_defaults_safe() -> None:
assert allowed_video_resolutions("some-other-video") == ["480p", "720p"]
-def test_minimax_h3_only_720p() -> None:
- assert allowed_video_resolutions("MiniMax-H3") == ["720p"]
- assert allowed_video_resolutions("minimax-h3") == ["720p"]
- assert clamp_video_resolution("MiniMax-H3", "1080p") == "720p"
- assert clamp_video_resolution("MiniMax-H3", "480p") == "720p"
+def test_minimax_h3_480_768() -> None:
+ assert allowed_video_resolutions("MiniMax-H3") == ["480p", "768p"]
+ assert allowed_video_resolutions("minimax-h3") == ["480p", "768p"]
+ assert clamp_video_resolution("MiniMax-H3", "1080p") == "768p"
+ assert clamp_video_resolution("MiniMax-H3", "720p") == "768p"
+ assert clamp_video_resolution("MiniMax-H3", "480p") == "480p"
+ from app.services.seedance_resolutions import format_video_resolution_for_upstream
+
+ # TokenFree 插件枚举要小写;勿写成 480P
+ assert format_video_resolution_for_upstream("MiniMax-H3", "480p") == "480p"
+ assert format_video_resolution_for_upstream("MiniMax-H3", "768p") == "768p"
+ assert format_video_resolution_for_upstream("MiniMax-H3", "720p") == "768p"
+ assert format_video_resolution_for_upstream("seedance-2.5", "720p") == "720p"
def test_clamp_1080p_on_mini_to_720p() -> None:
@@ -103,10 +111,10 @@ def test_catalog_video_row_has_allowed_resolutions() -> None:
defaults=DefaultModels(video_model="seedance-2-0-mini"),
)
by_id = {row["id"]: row for row in payload["video_models"]}
- assert by_id["seedance-2-0-mini"]["allowed_resolutions"] == ["480p", "720p"]
- assert by_id["seedance-2-5"]["allowed_resolutions"] == ["480p", "720p", "1080p"]
- assert by_id["seedance-2-5"]["label"] == "Seedance 2.5"
- # 别名 / 上游长 id 归一后不应再单独占一行 1080p 的 2.0
- assert "seedance-2.5" not in by_id
- assert by_id["seedance-2-0"]["allowed_resolutions"] == ["480p", "720p"]
- assert by_id["seedance-2-0"]["label"] == "Seedance 2.0"
+ # mini / 连字符 id 已别名到点分规范 id
+ assert "seedance-2-0-mini" not in by_id
+ assert "seedance-2-5" not in by_id
+ assert by_id["seedance-2.5"]["allowed_resolutions"] == ["480p", "720p", "1080p"]
+ assert by_id["seedance-2.5"]["label"] == "Seedance 2.5"
+ assert by_id["seedance-2.0"]["allowed_resolutions"] == ["480p", "720p"]
+ assert by_id["seedance-2.0"]["label"] == "Seedance 2.0"
diff --git a/backend/tests/test_tokenfree_pricing.py b/backend/tests/test_tokenfree_pricing.py
index c4d18ee..d1f39b1 100644
--- a/backend/tests/test_tokenfree_pricing.py
+++ b/backend/tests/test_tokenfree_pricing.py
@@ -388,7 +388,7 @@ def test_media_model_pricing_hint_lists_all_video_tiers() -> None:
# 2.0 720p ≈ ¥1.52/秒(刊例 46×1.5×22k tok)
assert "1.52" in h20 or "1.51" in h20 or "7.59" in h20
assert "0.58" in h_mm or "0.584" in h_mm
- assert "720p" in h_mm
+ assert "768p" in h_mm or "480p" in h_mm
def test_charge_official_llm_uses_in_out_split() -> None:
diff --git a/frontend/src/lib/dramaProjectOutputSettings.ts b/frontend/src/lib/dramaProjectOutputSettings.ts
index 259df14..da6cc75 100644
--- a/frontend/src/lib/dramaProjectOutputSettings.ts
+++ b/frontend/src/lib/dramaProjectOutputSettings.ts
@@ -1,6 +1,6 @@
/** 漫剧视频输出规格(画幅 / 清晰度):分集 params 优先,可回退 project.params */
export const DRAMA_RATIO_OPTIONS = ['9:16', '16:9', '1:1'] as const
-export const DRAMA_RES_OPTIONS = ['480p', '720p', '1080p'] as const
+export const DRAMA_RES_OPTIONS = ['480p', '720p', '768p', '1080p'] as const
export type DramaAspectRatio = (typeof DRAMA_RATIO_OPTIONS)[number]
export type DramaResolution = (typeof DRAMA_RES_OPTIONS)[number]
diff --git a/frontend/src/lib/dramaVideoGenerationOptions.ts b/frontend/src/lib/dramaVideoGenerationOptions.ts
index 65e78da..4e96063 100644
--- a/frontend/src/lib/dramaVideoGenerationOptions.ts
+++ b/frontend/src/lib/dramaVideoGenerationOptions.ts
@@ -4,7 +4,7 @@ import type { MediaModelOption, MediaModelsCatalog } from '../api'
export type VideoGenerationModelId = string
export type VideoAspectRatio = '9:16' | '16:9' | '1:1'
-export type VideoResolution = '480p' | '720p' | '1080p'
+export type VideoResolution = '480p' | '720p' | '768p' | '1080p'
export type VideoGenerationOptions = {
image_style_id?: string
@@ -15,7 +15,7 @@ export type VideoGenerationOptions = {
}
export const VIDEO_ASPECT_RATIO_OPTIONS: VideoAspectRatio[] = ['9:16', '16:9', '1:1']
-export const VIDEO_RESOLUTION_OPTIONS: VideoResolution[] = ['480p', '720p', '1080p']
+export const VIDEO_RESOLUTION_OPTIONS: VideoResolution[] = ['480p', '720p', '768p', '1080p']
/** 目录未到 / 未知模型时的保守档(与后端 SAFE 一致) */
export const SAFE_VIDEO_RESOLUTION_OPTIONS: VideoResolution[] = ['480p', '720p']
/** 时长快捷档;按模型 duration_min/max 过滤(2.0≤15,2.5≤30) */