PRINTFILM: AI short-video marketing and AI short-drama creation platform
merge: 同步 GitHub dev 并整合数字资产市场
yiad416041139d
diff --cc admin/src/App.tsxindex e91504d,57b8d67..3d0a7b8--- a/admin/src/App.tsx+++ b/admin/src/App.tsx@@@ -19,9 -19,8 +19,10 @@@ import { QueuesPage } from "@/pages/Queimport { SettingsPage } from "@/pages/SettingsPage";import { TemplatesPage } from "@/pages/TemplatesPage";import { UsersPage } from "@/pages/UsersPage";+import { TeamsPage } from "@/pages/TeamsPage";+import { TeamDetailPage } from "@/pages/TeamDetailPage";import { WorksPage } from "@/pages/WorksPage";+ import MarketplaceAdmin from "@/features/marketplace/MarketplaceAdmin";// Guard: require JWT + admin rolefunction RequireAdmin() {diff --cc admin/src/components/layout/AdminLayout.tsxindex 2245e32,900b934..32f0ff6--- a/admin/src/components/layout/AdminLayout.tsx+++ b/admin/src/components/layout/AdminLayout.tsx@@@ -1,4 -1,5 +1,5 @@@-import { useState } from "react";+import { useEffect, useLayoutEffect, useRef, useState } from "react";+ import { useMarketplaceEnabled } from "@/features/marketplace/api";import { NavLink, Outlet, useLocation, useNavigate } from "react-router-dom";@@@ -147,7 -147,9 +148,8 @@@ const navGroups: NavGroup[] =];---const titles: Record<string, string> = {"/marketplace": "数字资产平台运营",+const titles: Record<string, string> = {++ "/marketplace": "数字资产平台运营","/": "仪表盘",@@@ -197,156 -197,225 +199,160 @@@ function resolveTitle(pathname: string)}---// Admin shell: dark sidebar + glass top bar-+/** 统一运营工作台:桌面折叠导航、移动抽屉与可搜索入口。 */export function AdminLayout() {+ const marketplaceEnabled = useMarketplaceEnabled();-++ const visibleNavGroups = navGroups.map((group) => group.label === "业务" && marketplaceEnabled++ ? { ...group, items: [...group.items, { to: "/marketplace", label: "数字资产平台运营", icon: FileVideo } satisfies NavItem] }++ : group);const navigate = useNavigate();-const location = useLocation();-const user = getCachedUser();-- /*-- * collapsed sidebar collapsed state-- */-const [collapsed, setCollapsed] = useState(false);---- // Logout and return to login-- function handleLogout() {-- clearAuth();-- navigate("/login");-- }---+ const [mobileOpen, setMobileOpen] = useState(false);+ const [searchOpen, setSearchOpen] = useState(false);+ const [isMobile, setIsMobile] = useState(() => window.matchMedia("(max-width: 800px)").matches);+ const sidebarRef = useRef<HTMLElement>(null);+ const navigationToggleRef = useRef<HTMLButtonElement>(null);+ const sidebarCloseRef = useRef<HTMLButtonElement>(null);+ const mobileDrawerOpen = isMobile && mobileOpen;const title = resolveTitle(location.pathname);-const initial = (user?.nickname || user?.email || "A").slice(0, 1).toUpperCase();-+ useEffect(() => { setMobileOpen(false); }, [location.pathname]);+ useEffect(() => {+ const media = window.matchMedia("(max-width: 800px)");+ function onChange(event: MediaQueryListEvent) {+ setIsMobile(event.matches);+ if (!event.matches) setMobileOpen(false);+ }+ media.addEventListener("change", onChange);+ return () => media.removeEventListener("change", onChange);+ }, []);++ useLayoutEffect(() => {+ if (!mobileDrawerOpen) return;+ const sidebar = sidebarRef.current;+ if (!sidebar) return;+ const navigationToggle = navigationToggleRef.current;+ const previouslyFocused = document.activeElement instanceof HTMLElement && document.activeElement !== document.body+ ? document.activeElement : null;+ const previousOverflow = document.body.style.overflow;+ document.body.style.overflow = "hidden";+ sidebarCloseRef.current?.focus({ preventScroll: true });++ function focusableItems() {+ return Array.from(sidebar!.querySelectorAll<HTMLElement>('a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])'))+ .filter((element) => element.tabIndex >= 0 && element.getClientRects().length > 0);+ }+ function trapFocus(event: KeyboardEvent) {+ if (event.key !== "Tab") return;+ const items = focusableItems();+ const first = items[0];+ const last = items[items.length - 1];+ if (!first || !last) return;+ if (event.shiftKey && (document.activeElement === first || !sidebar!.contains(document.activeElement))) {+ event.preventDefault();+ last.focus();+ } else if (!event.shiftKey && (document.activeElement === last || !sidebar!.contains(document.activeElement))) {+ event.preventDefault();+ first.focus();+ }+ }+ function keepFocusInside(event: FocusEvent) {+ if (event.target instanceof Node && !sidebar!.contains(event.target)) {+ sidebarCloseRef.current?.focus({ preventScroll: true });+ }+ }+ document.addEventListener("keydown", trapFocus, true);+ document.addEventListener("focusin", keepFocusInside);+ return () => {+ document.removeEventListener("keydown", trapFocus, true);+ document.removeEventListener("focusin", keepFocusInside);+ document.body.style.overflow = previousOverflow;+ if (sidebar.contains(document.activeElement) || document.activeElement === document.body) {+ const restoreTarget = previouslyFocused?.isConnected ? previouslyFocused : navigationToggle;+ restoreTarget?.focus({ preventScroll: true });+ }+ };+ }, [mobileDrawerOpen]);++ useEffect(() => {+ function onKey(event: KeyboardEvent) {+ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") {+ event.preventDefault();+ setMobileOpen(false);+ setSearchOpen((value) => !value);+ }+ if (event.key === "Escape") setMobileOpen(false);+ }+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);++ function handleLogout() { clearAuth(); navigate("/login"); }+ function toggleNavigation() {+ if (isMobile) setMobileOpen((value) => !value);+ else setCollapsed((value) => !value);+ }return (-- <div className={cn("admin-app", collapsed && "is-collapsed")}>-- <aside className="admin-sidebar">-+ <div className={cn("admin-app", collapsed && "is-collapsed", mobileDrawerOpen && "is-mobile-open")}>+ <a className="admin-skip-link" href="#admin-main-content">跳至页面内容</a>+ {mobileDrawerOpen && <button type="button" className="admin-sidebar-scrim" tabIndex={-1} aria-label="关闭导航" onClick={() => setMobileOpen(false)} />}+ <aside ref={sidebarRef} className="admin-sidebar" id="admin-sidebar" aria-label="管理导航"+ role={mobileDrawerOpen ? "dialog" : undefined} aria-modal={mobileDrawerOpen ? true : undefined}+ aria-hidden={isMobile && !mobileOpen ? true : undefined} inert={isMobile && !mobileOpen}><div className="admin-brand">-- <div className="admin-brand-mark">PF</div>-- {!collapsed && (-- <div>-- <div className="admin-brand-name">PRINTFILM</div>-- <div className="admin-brand-sub">管理后台</div>-- </div>-- )}-+ <div className="admin-brand-mark"><Aperture size={23} strokeWidth={1.7} /></div>+ <div className="admin-brand-copy"><div className="admin-brand-name">PRINTFILM<span>®</span></div><div className="admin-brand-sub">运营控制台</div></div>+ <button ref={sidebarCloseRef} type="button" className="admin-icon-btn admin-sidebar-close" aria-label="关闭导航" onClick={() => setMobileOpen(false)}><X size={18} /></button></div>-- <nav className="admin-nav">-- {navGroups.map((group) => (-+ <nav className="admin-nav" aria-label="主导航">- {navGroups.map((group) => (++ {visibleNavGroups.map((group) => (<div key={group.label} className="admin-nav-group">-- {!collapsed ? <div className="admin-nav-group-label">{group.label}</div> : null}-- {[...group.items, ...(group.label === "业务" && marketplaceEnabled ? [{ to: "/marketplace", label: "数字资产平台运营", icon: FileVideo } satisfies NavItem] : [])].map((item) => (-- <NavLink-- key={item.to}-- to={item.to}-- end={item.end ?? !item.matchPrefix}-- className={({ isActive }) =>-- cn(-- "admin-nav-item",-- (isActive || (item.matchPrefix && location.pathname.startsWith(`${item.to}/`))) &&-- "is-active",-- )-- }-- title={item.label}-- >-- <item.icon className="h-[18px] w-[18px] shrink-0" />-- {!collapsed && <span>{item.label}</span>}-+ <div className="admin-nav-group-label">{group.label}</div>+ {group.items.map((item) => (+ <NavLink key={item.to} to={item.to} end={item.end ?? !item.matchPrefix}+ className={({ isActive }) => cn("admin-nav-item", (isActive || (item.matchPrefix && location.pathname.startsWith(`${item.to}/`))) && "is-active")}+ title={item.label} onClick={() => setMobileOpen(false)}>+ <item.icon className="h-[18px] w-[18px] shrink-0" strokeWidth={1.7} />+ <span className="admin-nav-label">{item.label}</span><ChevronRight className="admin-nav-arrow" size={14} /></NavLink>-))}-</div>-))}-</nav>-+ <div className="admin-sidebar-footnote"><span />PRINTFILM OPERATIONS</div><div className="admin-user-card">-<div className="admin-avatar">{initial}</div>-- {!collapsed && (-- <div className="min-w-0 flex-1">-- <div className="truncate text-[13px] font-medium text-[#e8f0eb]">{user?.email}</div>-- <div className="text-xs text-[rgba(240,245,242,0.45)]">超级管理员</div>-- </div>-- )}-- <button type="button" className="admin-icon-btn !text-[rgba(240,245,242,0.55)] hover:!text-[#e8f0eb]" onClick={handleLogout} title="退出登录">-- <LogOut className="h-4 w-4" />-- </button>-+ <div className="admin-user-copy"><strong>{user?.nickname || "管理员"}</strong><span title={user?.email}>{user?.email}</span></div>+ <button type="button" className="admin-icon-btn admin-logout" onClick={handleLogout} title="退出登录" aria-label="退出登录"><LogOut size={16} /></button></div>-</aside>---- <div className="admin-main">-+ <div className="admin-main" inert={mobileDrawerOpen}><header className="admin-topbar">-- <div className="flex items-center gap-3">-- <button-- type="button"-- className="admin-icon-btn"-- onClick={() => setCollapsed((v) => !v)}-- aria-label="折叠侧栏"-- >-- <Menu className="h-4 w-4" />-+ <div className="admin-topbar-leading">+ <button ref={navigationToggleRef} type="button" className="admin-icon-btn" onClick={toggleNavigation}+ aria-label={isMobile ? (mobileOpen ? "关闭导航" : "展开导航") : (collapsed ? "展开导航" : "折叠导航")}+ aria-controls="admin-sidebar" aria-expanded={isMobile ? mobileOpen : !collapsed}>+ <PanelLeftClose size={19} /></button>-- <div>-- <div className="admin-topbar-title">{title}</div>-- <div className="admin-topbar-crumb">PRINTFILM · 运营管理</div>-- </div>-+ <div className="admin-topbar-breadcrumb"><span>控制台</span><ChevronRight size={13} /><strong>{title}</strong></div></div>-- <div className="flex items-center gap-1">-- <button type="button" className="admin-icon-btn" title="通知">-- <Bell className="h-4 w-4" />-- </button>-- <button-- type="button"-- className="admin-icon-btn"-- title="全屏"-- onClick={() => {-- if (!document.fullscreenElement) void document.documentElement.requestFullscreen();-- else void document.exitFullscreen();-- }}-- >-- <Maximize2 className="h-4 w-4" />-- </button>-+ <div className="admin-topbar-actions">+ <button type="button" className="admin-command-trigger" aria-label="搜索管理功能" aria-keyshortcuts="Control+K Meta+K" onClick={() => setSearchOpen(true)}><Search size={15} /><span>搜索功能…</span><kbd>Ctrl K</kbd></button>+ <a className="admin-site-link" href={import.meta.env.DEV ? "http://127.0.0.1:5173" : "/"} target="_blank" rel="noreferrer">用户端<ArrowUpRight size={14} /></a>+ <button type="button" className="admin-icon-btn admin-fullscreen" title="切换全屏" aria-label="切换全屏" onClick={() => {+ if (!document.fullscreenElement) void document.documentElement.requestFullscreen().catch(() => undefined);+ else void document.exitFullscreen().catch(() => undefined);+ }}><Maximize2 size={17} /></button>+ <div className="admin-topbar-avatar" title={user?.email}>{initial}</div></div>-</header>-- <main className="admin-content">-- <Outlet />-- </main>-+ <main className="admin-content" id="admin-main-content" tabIndex={-1}><Outlet /></main></div>- <AdminNavigationSearch open={searchOpen} onOpenChange={setSearchOpen} groups={navGroups} />-++ <AdminNavigationSearch open={searchOpen} onOpenChange={setSearchOpen} groups={visibleNavGroups} /></div>-);-}diff --cc admin/src/components/settings/OssSettingsPanel.tsxindex 394269a,93530a8..a300596--- a/admin/src/components/settings/OssSettingsPanel.tsx+++ b/admin/src/components/settings/OssSettingsPanel.tsx@@@ -34,95 -52,137 +34,101 @@@ export function OssSettingsPanel()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>} />- <SettingsPanel title="存储连接" description="Endpoint 决定上传到哪里,Bucket 是存储空间名称。未启用时也可提前保存连接信息。">- 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="生成业务与数字资产市场共用此处的 Bucket 和凭证。Endpoint 决定上传到哪里,Bucket 是存储空间名称。">+ <div className="settings-toggle-row">- <div><strong>启用阿里云 OSS</strong><span>开启后上传生成文件;关闭后使用本地静态目录。</span></div>++ <div><strong>启用阿里云 OSS</strong><span>关闭后生成业务使用本地目录;数字资产市场文件上传与播放不可用。</span></div>+ <Switch aria-label="启用阿里云 OSS" checked={form.oss_enabled} onCheckedChange={(value) => patchField("oss_enabled", value)} />+ </div>++ <p className="mt-3 text-sm text-muted-foreground">++ 数字资产市场固定使用 marketplace/ 目录,不受下方生成业务目录设置影响。++ 市场文件以私有权限上传,通过短时签名访问,不使用公开域名。++ Bucket 须为私有且不得存在匿名 Allow 策略;此页保存配置不会自动修改 Bucket 权限。++ “配置完整”仅表示配置项已填写,实际权限仍需云端验证。++ </p>+ <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。">++ <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 分开配置。">++ <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="原有生成业务与数字资产市场共用此处的 Bucket 和凭证"- >- <div className="settings-toggle-row">- <div>- <strong>启用 OSS</strong>- <span>关闭后原生成业务使用本地目录;数字资产市场文件上传与播放不可用</span>- </div>- <Switch checked={form.oss_enabled} onCheckedChange={(v) => patchField("oss_enabled", v)} />- </div>- <p className="mt-3 text-sm text-muted-foreground">- 数字资产市场固定使用 marketplace/ 目录,不受下方原业务目录设置影响。- 市场文件以私有权限上传,通过短时签名访问,不使用公开域名。- Bucket 须为私有且不得存在匿名 Allow 策略;此页保存配置不会自动修改 Bucket 权限。- “已就绪”仅表示配置完整,实际权限仍需云端验证。- </p>- <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 --cc backend/app/main.pyindex 653929c,1c0670d..a3e62de--- a/backend/app/main.py+++ b/backend/app/main.py@@@ -113,15 -89,15 +113,19 @@@ app.include_router(creation.router, preapp.include_router(tasks.router, prefix="/api")app.include_router(billing.router, prefix="/api")app.include_router(tools.router, prefix="/api")-app.include_router(user_api_keys.router, prefix="/api")-app.include_router(v1_router, prefix="/api")app.include_router(drama_router, prefix="/api")+app.include_router(teams.router, prefix="/api")+app.include_router(teams.invitation_router, prefix="/api")+app.include_router(team_billing.router, prefix="/api")+app.include_router(team_content.router, prefix="/api")+app.include_router(team_content.personal_router, prefix="/api")+app.include_router(team_edit_locks.router, prefix="/api")app.include_router(admin_router, prefix="/api")+ # 下游扩展仅注册独立路由和初始化,不改变原发布、生成及存储逻辑。+ from app.marketplace.bootstrap import install as install_marketplace+ install_marketplace(app)+async def _load_startup_model_settings() -> None:async with AsyncSessionLocal() as db:@@@ -178,15 -165,14 +193,18 @@@ async def _pg_columns(conn, table: strreturn {row[0] for row in result.fetchall()}-async def _apply_schema_patches() -> None:+async def _apply_schema_patches(engine_override: AsyncEngine | None = None) -> None:"""Lightweight additive migrations(仅 PostgreSQL)。"""- async with engine.begin() as conn:- # Local unit tests may use SQLite, while production uses PostgreSQL. The- # information_schema queries and ALTER TABLE syntax below are deliberately- # PostgreSQL-only; create_all() already handles a fresh SQLite database.+ target_engine = engine_override if engine_override is not None else engine+ async with target_engine.begin() as conn:++ # 现有 SQLite 测试库由 create_all 建表;以下补列只适用于 PostgreSQL。+ if conn.dialect.name != "postgresql":+ return+ from app.team_schema import apply_team_schema_patches++ await apply_team_schema_patches(conn)+ from app.media_schema import apply_media_schema_patches+ await apply_media_schema_patches(conn)scols = await _pg_columns(conn, "shots")if "segment_script" not in scols:await conn.execute(text("ALTER TABLE shots ADD COLUMN segment_script TEXT DEFAULT ''"))diff --cc backend/app/marketplace/drama_publish.pyindex 0000000,1157e67..085de1cmode 000000,100644..100644--- a/backend/app/marketplace/drama_publish.py+++ b/backend/app/marketplace/drama_publish.py@@@ -1,0 -1,317 +1,319 @@@+ """漫剧整集到市场的显式快照发布。只读原漫剧,写入独立市场表。"""+ from __future__ import annotations++ import asyncio+ import hashlib+ import json++ from fastapi import APIRouter, HTTPException+ from sqlalchemy import func, or_, select, text, update++ from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaProject+ from app.models_tasks import TaskRun++from app.services.drama.access import require_drama_project_access+ from .authorization import current as current_authorization+ from .dependencies import Actor, DB, storage_ready+ from .models import DramaPublishBatch, Handoff, Publication, Rights, Series, SeriesEpisode+ from .schemas import DramaPublishEpisode, DramaPublishInput+ from .service import ensure_kept, fail++ router = APIRouter()+ ACTIVE = ("pending", "leased", "running", "awaiting_poll", "awaiting_review")+ BUSY = ("queued", "running", "generating", "pending", "leased")+++ def terminal_source_task(item) -> bool:+ return bool(item and item.status == "failed" and any(code in (item.error or "") for code in (+ "SOURCE_CHANGED", "TARGET_CHANGED", "SOURCE_INCOMPATIBLE", "重新选择分集")))+++ def digest(value) -> str:+ return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, default=str).encode()).hexdigest()+++ def episode_number(episode) -> int:+ try:+ return max(0, int((episode.params or {}).get("episodeNumber") or 0))+ except (ValueError, TypeError):+ return 0+++ async def owned_project(db, owner_id: int, project_id: int):+ project = await db.get(DramaProject, project_id)+ if not project or project.user_id != owner_id:+ fail("漫剧项目不存在或无权访问", 404)++ await require_drama_project_access(db, project, owner_id)+ return project+++ async def episode_snapshot(db, owner_id: int, project_id: int, episode_id: int) -> dict:+ """服务端保存有序分镜与实际文件身份,不接受客户端传入视频地址。"""+ from .drama_media import source_stamp, stamp_version++ project = await owned_project(db, owner_id, project_id)+ episode = await db.get(DramaEpisode, episode_id)+ if not episode or episode.project_id != project.id:+ fail("存在不属于该漫剧项目的分集", 404)+ fragments = list((await db.execute(select(DramaEpisodeFragment).where(+ DramaEpisodeFragment.episode_id == episode.id+ ).order_by(DramaEpisodeFragment.sort_order, DramaEpisodeFragment.id))).scalars().all())+ active = (await db.execute(select(TaskRun.id).where(+ TaskRun.domain == "drama", TaskRun.task_type.in_(("fragment_video", "fragment_plan")),+ TaskRun.status.in_(ACTIVE),+ or_(TaskRun.episode_id == episode.id, TaskRun.fragment_id.in_([f.id for f in fragments])),+ ).limit(1))).scalar_one_or_none()+ if active or (episode.params or {}).get("fragment_plan_status") in BUSY:+ fail("MARKETPLACE_SOURCE_NOT_READY:分集正在生成视频或重新分镜,请完成后再发布", 409)+ if not fragments or any(not (fragment.video or "").strip() for fragment in fragments):+ fail("MARKETPLACE_SOURCE_NOT_READY:请先完成这一集的全部分镜视频", 409)+ clips = []+ for fragment in fragments:+ params = fragment.params or {}+ generation = params.get("generation") or params.get("video_gen") or params.get("video_generation") or {}+ if (isinstance(generation, dict) and generation.get("status") in BUSY) or params.get("video_status") in BUSY:+ fail("MARKETPLACE_SOURCE_NOT_READY:分镜视频仍在生成中", 409)+ locator = fragment.video.strip()+ try:+ stamp = await asyncio.to_thread(source_stamp, locator)+ except HTTPException:+ raise+ except (ValueError, OSError) as exc:+ fail(str(exc) if str(exc).startswith("MARKETPLACE_") else "MARKETPLACE_SOURCE_NOT_READY:源视频不可用", 409)+ clips.append({"id": fragment.id, "sort_order": fragment.sort_order, "locator": locator,+ "stamp": stamp, "updated_at": fragment.updated_at.isoformat(),+ "cover": fragment.cover or ""})+ snapshot = {"schema_version": 2, "drama_project_id": project.id, "drama_episode_id": episode.id,+ "episode_number": episode_number(episode), "title": episode.name,+ "episode_updated_at": episode.updated_at.isoformat(), "clips": clips,+ "cover_locator": next((clip["cover"] for clip in clips if clip["cover"]), "")}+ snapshot["cover_stamp"] = None+ if snapshot["cover_locator"]:+ try:+ snapshot["cover_stamp"] = await asyncio.to_thread(source_stamp, snapshot["cover_locator"])+ except (HTTPException, ValueError, OSError):+ # A missing cover never selects an unrelated material. The editor asks for one.+ snapshot["cover_locator"] = ""+ snapshot["source_version"] = digest({"episode": episode.id, "title": episode.name,+ "episode_number": snapshot["episode_number"], "updated_at": snapshot["episode_updated_at"],+ "cover_stamp": stamp_version(snapshot["cover_stamp"]) if snapshot["cover_stamp"] else None,+ "clips": [{"id": clip["id"], "sort_order": clip["sort_order"], "updated_at": clip["updated_at"],+ "stamp": stamp_version(clip["stamp"]), "cover": clip["cover"]} for clip in clips]})+ return snapshot+++ async def episode_context(db, owner_id: int, project_id: int, episode) -> dict:+ fragments = list((await db.execute(select(DramaEpisodeFragment).where(DramaEpisodeFragment.episode_id == episode.id))).scalars().all())+ result = {"id": episode.id, "name": episode.name, "episode_number": episode_number(episode),+ "fragment_count": len(fragments), "completed_count": sum(bool((f.video or "").strip()) for f in fragments),+ "ready": False, "reason": "", "source_version": ""}+ try:+ snapshot = await episode_snapshot(db, owner_id, project_id, episode.id)+ result.update(ready=True, source_version=snapshot["source_version"])+ except HTTPException as exc:+ result["reason"] = str(exc.detail)+ return result+++ @router.get("/printfilm/dramas/{project_id}/publish-context", response_model=dict)+ async def publish_context(project_id: int, db: DB, user: Actor):+ from .storage import configured+ project = await owned_project(db, user.id, project_id)+ episodes = list((await db.execute(select(DramaEpisode).where(DramaEpisode.project_id == project.id))).scalars().all())+ episodes.sort(key=lambda row: (episode_number(row), row.id))+ targets = list((await db.execute(select(Series).where(Series.owner_id == user.id,+ Series.deleted_at.is_(None), Series.blocked.is_(False)).order_by(Series.id.desc()))).scalars().all())+ series_items = []+ for target in targets:+ imported = list((await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == target.id))).scalars().all())+ mappings = []+ for episode in imported:+ mapping = episode.source_snapshot or {}+ if mapping.get("source_kind") != "drama_episode":+ continue+ handoff_id = mapping.get("pending_handoff_id") or mapping.get("last_handoff_id")+ handoff = await db.get(Handoff, handoff_id) if handoff_id else (await db.execute(select(Handoff).where(+ Handoff.target_kind == "series_episode", Handoff.target_id == episode.id,+ Handoff.source_kind == "drama_episode").order_by(Handoff.id.desc()).limit(1))).scalar_one_or_none()+ frozen = (handoff.source_snapshot or {}) if handoff else {}+ reusable = bool(handoff and not terminal_source_task(handoff) and frozen.get("schema_version") == 2 and (+ (handoff.status == "ready" and handoff.asset_id == episode.asset_id and mapping.get("last_handoff_id") == handoff.id)+ or (handoff.status in ("pending", "running", "failed") and mapping.get("pending_handoff_id") == handoff.id+ and frozen.get("target_version") == episode.version and frozen.get("original_asset_id") == episode.asset_id)))+ mappings.append({"source_episode_id": mapping.get("drama_episode_id") or mapping.get("source_id"),+ "episode_id": episode.id, "source_version": handoff.source_version if handoff else mapping.get("imported_source_version", ""),+ "status": handoff.status if handoff else "legacy", "handoff_id": handoff.id if handoff else None,+ "requires_update": not reusable})+ series_items.append({"id": target.id, "title": target.title, "version": target.version,+ "series_version": target.version, "listed": target.listed,+ "audit_status": target.audit_status, "imports": mappings})+ return {"project": {"id": project.id, "title": project.title, "description": project.description or ""},+ "episodes": [await episode_context(db, user.id, project.id, episode) for episode in episodes],+ "series": series_items, "authorization_ready": bool(await current_authorization(db, user.id)),+ "storage_configured": configured()}+++ async def pause_sales(db, series):+ ids = select(SeriesEpisode.id).where(SeriesEpisode.series_id == series.id)+ await db.execute(update(Publication).where(Publication.content_type == "series_episode", Publication.content_id.in_(ids)).values(listed=False))+ await db.execute(update(SeriesEpisode).where(SeriesEpisode.series_id == series.id).values(listed=False))+ series.audit_status, series.listed, series.reason = "draft", False, ""+++ async def ensure_import_rights(db, episode):+ """PrintFilm 分集统一关联账号授权;材料关联绝不等于审核通过。"""+ if episode.source != "printfilm" or not episode.asset_id:+ return+ mapping = episode.source_snapshot or {}+ if episode.source_type == "drama_import":+ if not mapping.get("last_handoff_id"):+ return+ handoff = await db.get(Handoff, mapping["last_handoff_id"])+ if not handoff or handoff.status != "ready" or handoff.asset_id != episode.asset_id or handoff.owner_id != episode.owner_id:+ return+ authorization = await current_authorization(db, episode.owner_id)+ if not authorization:+ return+ rights = (await db.execute(select(Rights).where(Rights.asset_id == episode.asset_id).with_for_update())).scalar_one_or_none()+ if rights and (rights.blocked or str(rights.details.get("authorization_id")) == str(authorization.id)):+ return+ values = {"source": "printfilm", "authorization_id": str(authorization.id),+ "authorization_version": authorization.template_version, "scope": "数字资产市场展示、撮合及经审核的平台投放"}+ if rights is None:+ db.add(Rights(owner_id=episode.owner_id, asset_id=episode.asset_id, details=values))+ else:+ rights.details = values+ rights.version += 1+ rights.basic_status = rights.full_status = "draft"+++ async def batch_result(db, batch):+ from .handoff import _view+ from .series import _episode_data+ episodes = [await db.get(SeriesEpisode, item_id) for item_id in batch.episode_ids]+ tasks = [await db.get(Handoff, item_id) for item_id in batch.handoff_ids]+ return {"series_id": batch.series_id, "items": [await _episode_data(db, item, private=True) for item in episodes if item],+ "handoffs": [await _view(db, item) for item in tasks if item]}+++ async def publish_selected(project_id: int, body: DramaPublishInput, db, user):+ from .handoff import _category+ # A transaction lock serializes retries even when creating a brand new series.+ # It doesn't update any upstream user or drama record.+ request_hash = digest({"project_id": project_id, **body.model_dump(exclude={"idempotency_key"})})+ lock_id = int(digest([user.id, body.idempotency_key])[:16], 16)+ if lock_id >= 2**63:+ lock_id -= 2**64+ await db.execute(text("SELECT pg_advisory_xact_lock(:key)"), {"key": lock_id})+ existing = (await db.execute(select(DramaPublishBatch).where(DramaPublishBatch.owner_id == user.id,+ DramaPublishBatch.idempotency_key == body.idempotency_key))).scalar_one_or_none()+ if existing:+ if existing.request_hash != request_hash:+ fail("MARKETPLACE_TARGET_CHANGED:此请求编号已用于其他发布内容", 409)+ return await batch_result(db, existing)+ await storage_ready() # Must precede all series/episode/task writes.+ project = await owned_project(db, user.id, project_id)+ snapshots = []+ for selected in body.episodes:+ snapshot = await episode_snapshot(db, user.id, project.id, selected.episode_id)+ if selected.source_version != snapshot["source_version"]:+ fail("MARKETPLACE_SOURCE_CHANGED:分集内容已变化,请刷新并重新选择", 409)+ snapshots.append((snapshot, selected.update))+ snapshots.sort(key=lambda entry: (entry[0]["episode_number"], entry[0]["drama_episode_id"]))+ if body.series_id:+ series = (await db.execute(select(Series).where(Series.id == body.series_id).with_for_update())).scalar_one_or_none()+ if not series or series.owner_id != user.id:+ fail("系列不存在或无权访问", 404)+ ensure_kept(series)+ if series.blocked:+ fail("MARKETPLACE_TARGET_CHANGED:系列已封禁", 409)+ stale_target = body.series_version is not None and series.version != body.series_version+ else:+ series = Series(owner_id=user.id, title=(body.title or project.title or "未命名短剧")[:200],+ description=(project.description or "")[:5000], category=await _category(db, "短剧"), sale_type="copyright_contact")+ db.add(series)+ await db.flush()+ stale_target = False+ episodes = list((await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == series.id)+ .order_by(SeriesEpisode.episode_no).with_for_update())).scalars().all())+ next_no = max((episode.episode_no for episode in episodes), default=0) + 1+ targets, tasks = [], []+ changed = False+ for snapshot, confirmed_update in snapshots:+ source_id = snapshot["drama_episode_id"]+ target = next((row for row in episodes if (row.source_snapshot or {}).get("source_kind") == "drama_episode"+ and ((row.source_snapshot or {}).get("drama_episode_id") or (row.source_snapshot or {}).get("source_id")) == source_id), None)+ previous = (await db.execute(select(Handoff).where(Handoff.owner_id == user.id,+ Handoff.series_id == series.id, Handoff.target_id == target.id,+ Handoff.source_kind == "drama_episode", Handoff.source_id == source_id)+ .order_by(Handoff.id.desc()).limit(1))).scalar_one_or_none() if target else None+ previous_snapshot = previous.source_snapshot or {} if previous else {}+ mapping = target.source_snapshot or {} if target else {}+ previous_matches = bool(previous and not terminal_source_task(previous) and ((previous.status == "ready" and previous.asset_id == target.asset_id+ and mapping.get("last_handoff_id") == previous.id)+ or (previous.status in ("pending", "running", "failed") and previous_snapshot.get("target_version") == target.version+ and previous_snapshot.get("original_asset_id") == target.asset_id and mapping.get("pending_handoff_id") == previous.id)))+ if previous_matches and previous.source_version == snapshot["source_version"] and previous_snapshot.get("schema_version") == 2:+ targets.append(target)+ tasks.append(previous)+ continue+ if target and not confirmed_update:+ fail("MARKETPLACE_SOURCE_CHANGED:发现新版本或旧版导入记录,请明确确认更新", 409)+ if target and target.blocked:+ fail("MARKETPLACE_TARGET_CHANGED:该分集已封禁", 409)+ if stale_target:+ fail("MARKETPLACE_TARGET_CHANGED:市场系列已修改,请刷新后重试", 409)+ if previous and previous.status in ("pending", "running"):+ previous.status, previous.error = "failed", "MARKETPLACE_TARGET_CHANGED:已有新的同步任务,请查看最新进度"+ previous.lease_token, previous.lease_until = None, None+ if target:+ target.version += 1+ target.audit_status, target.listed, target.reason = "draft", False, ""+ target.preview_status, target.playback_status = "none", "none"+ else:+ target = SeriesEpisode(series_id=series.id, owner_id=user.id, episode_no=next_no,+ title=(snapshot["title"] or f"第{next_no}集")[:200], source="printfilm", source_type="drama_import")+ next_no += 1+ db.add(target)+ await db.flush()+ episodes.append(target)+ # A new request can supersede a prior failed/running task, never its output.+ task = Handoff(owner_id=user.id, idempotency_key=digest(["drama", series.id, target.id, target.version, body.idempotency_key]),+ source_kind="drama_episode", source_id=source_id, source_version=snapshot["source_version"],+ target_kind="series_episode", target_id=target.id, series_id=series.id, status="pending",+ source_snapshot={**snapshot, "phase": "queued", "target_version": target.version,+ "original_asset_id": target.asset_id})+ db.add(task)+ await db.flush()+ target.source = "printfilm"+ target.source_snapshot = {"source_kind": "drama_episode", "source_id": source_id,+ "drama_project_id": project.id, "drama_episode_id": source_id, "source_title": snapshot["title"],+ "source_episode_number": snapshot["episode_number"], "pending_handoff_id": task.id,+ "last_handoff_id": (target.source_snapshot or {}).get("last_handoff_id"),+ "imported_source_version": (target.source_snapshot or {}).get("imported_source_version", "")}+ targets.append(target)+ tasks.append(task)+ changed = True+ if changed:+ series.version += 1+ await pause_sales(db, series)+ batch = DramaPublishBatch(owner_id=user.id, idempotency_key=body.idempotency_key,+ request_hash=request_hash, series_id=series.id, episode_ids=[row.id for row in targets], handoff_ids=[row.id for row in tasks])+ db.add(batch)+ await db.commit()+ return await batch_result(db, batch)+++ @router.post("/printfilm/dramas/{project_id}/publish", response_model=dict)+ async def publish(project_id: int, body: DramaPublishInput, db: DB, user: Actor):+ return await publish_selected(project_id, body, db, user)+++ async def legacy_import(series_id: int, body, db, user):+ """兼容旧 URL;依然验证整集,绝不选择最后一个镜头。"""+ await storage_ready()+ snapshots = [await episode_snapshot(db, user.id, body.drama_project_id, episode_id) for episode_id in dict.fromkeys(body.episode_ids)]+ key = body.idempotency_key.strip() or digest(["legacy", series_id, [(s["drama_episode_id"], s["source_version"]) for s in snapshots]])+ payload = DramaPublishInput(series_id=series_id, idempotency_key=key,+ episodes=[DramaPublishEpisode(episode_id=s["drama_episode_id"], source_version=s["source_version"],+ update=s["drama_episode_id"] in body.update_episode_ids) for s in snapshots])+ return await publish_selected(body.drama_project_id, payload, db, user)diff --cc backend/app/marketplace/series.pyindex 0000000,a88d1c1..9d3758amode 000000,100644..100644--- a/backend/app/marketplace/series.py+++ b/backend/app/marketplace/series.py@@@ -1,0 -1,480 +1,487 @@@+ """短剧系列市场 API。++ 系列数据只使用 marketplace_ 表;原 drama 项目仅在用户明确导入时读取一次快照。+ """+ from __future__ import annotations++ from fastapi import APIRouter, Query+ from sqlalchemy import and_, not_, or_, select++ from app.models_drama import DramaProject++from app.models_teams import TeamMember+ from .dependencies import Actor, DB, Visitor, storage_ready+ from .models import Asset, ContentOrder, Entitlement, EpisodePreview, Handoff, PlaybackJob, Publication, RevenueConfig, Rights, Series, SeriesEpisode+ from .schemas import EpisodeInput, EpisodeUpdate, ImportEpisodesInput, SeriesInput, SeriesUpdate, Version+ from .service import asset_owned, asset_owned_for_draft, check_version, data, event, fail, now, notify, owned, page, validate_rights++ router = APIRouter()+++ async def ensure_series_idle(db, series_id: int, *, submitting: bool = False) -> None:+ active = (await db.execute(select(Handoff.id).where(+ Handoff.series_id == series_id, Handoff.status.in_(("pending", "running"))+ ).limit(1))).scalar_one_or_none()+ if active:+ fail("MARKETPLACE_SYNC_IN_PROGRESS", 409)+ if submitting:+ latest = await _latest_series_handoffs(db, series_id)+ if any(item.status == "failed" for item in latest):+ fail("MARKETPLACE_EPISODE_NOT_READY", 409)+++ async def _latest_series_handoffs(db, series_id: int) -> list[Handoff]:+ handoffs = list((await db.execute(select(Handoff).where(+ Handoff.series_id == series_id, Handoff.target_kind == "series_episode",+ Handoff.target_id.in_(select(SeriesEpisode.id).where(SeriesEpisode.series_id == series_id)),+ ).order_by(Handoff.id.desc()))).scalars().all())+ latest = {}+ for handoff in handoffs:+ latest.setdefault(handoff.target_id, handoff)+ return list(latest.values())+++ async def pause_series_sales(db, series: Series, *, bump_episode_versions: bool = False) -> list[SeriesEpisode]:+ """保留旧媒体及购买快照,仅关闭销售;系列资料更新时产生新的逐集版本。"""+ episodes = list((await db.execute(select(SeriesEpisode).where(+ SeriesEpisode.series_id == series.id).with_for_update())).scalars().all())+ series.listed = False+ for episode in episodes:+ episode.listed = False+ if bump_episode_versions:+ episode.version += 1+ episode.audit_status, episode.reason = "draft", ""+ if episodes:+ publications = list((await db.execute(select(Publication).where(+ Publication.content_type == "series_episode",+ Publication.content_id.in_([item.id for item in episodes]),+ ).with_for_update())).scalars().all())+ for publication in publications:+ publication.listed = False+ return episodes+++ def _sale_type(value: str, copyright_price: int) -> str:+ # 收费类型由用户明确选择;参考价为0仍可以先联系客服询价。+ return value+++ async def _series(db, series_id: int, user, *, lock: bool = False) -> Series:+ query = select(Series).where(Series.id == series_id)+ if lock:+ query = query.with_for_update()+ item = (await db.execute(query)).scalar_one_or_none()+ if not item or (item.owner_id != user.id and user.role != "admin"):+ fail("系列不存在或无权访问", 404)+ return item+++ async def _episode(db, episode_id: int, user, *, lock: bool = False) -> SeriesEpisode:+ query = select(SeriesEpisode).where(SeriesEpisode.id == episode_id)+ if lock:+ query = query.with_for_update()+ item = (await db.execute(query)).scalar_one_or_none()+ if not item or (item.owner_id != user.id and user.role != "admin"):+ fail("分集不存在或无权访问", 404)+ return item+++ async def _episode_data(db, item: SeriesEpisode, *, private: bool = False) -> dict:+ asset = await db.get(Asset, item.asset_id) if item.asset_id else None+ result = data(item, "id", "series_id", "episode_no", "title", "description", "copyright_price_fen", "unlock_price_fen", "share_bps", "source", "source_type", "version", "preview_status", "playback_status", "created_at")+ result.update(media_status=asset.status if asset else "missing", duration_seconds=asset.duration_seconds if asset else None)+ if private:+ result.update(data(item, "owner_id", "asset_id", "cover_asset_id", "audit_status", "listed", "blocked", "reason", "source_snapshot"))+ rights = (await db.execute(select(Rights).where(Rights.asset_id == item.asset_id))).scalar_one_or_none() if item.asset_id else None+ result.update(rights_ready=bool(rights and rights.basic_status == "approved" and rights.full_status == "approved"), rights_source=rights.details.get("source") if rights else None)+ return result+++ async def _series_data(db, item: Series, *, private: bool = False) -> dict:+ episodes = (await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == item.id).order_by(SeriesEpisode.episode_no))).scalars().all()+ result = data(item, "id", "title", "description", "category", "tags", "cover_asset_id", "sale_type", "copyright_price_fen", "free_episode_count", "created_at")+ result["episode_count"] = len(episodes)+ result["episodes"] = [await _episode_data(db, episode, private=private) for episode in episodes]+ if private:+ result.update(data(item, "owner_id", "version", "audit_status", "listed", "blocked", "reason", "share_bps"))+ from .authorization import current, summary+ from .handoff import _view+ authorization = await current(db, item.owner_id)+ handoffs = await _latest_series_handoffs(db, item.id)+ result.update(authorization_ready=bool(authorization), authorization=summary(authorization),+ sync_in_progress=any(handoff.status in ("pending", "running") for handoff in handoffs),+ pending_handoffs=[await _view(db, handoff) for handoff in handoffs])+ return result+++ def public_series_filters():+ """作品广场只展示已上架、且每一集都有水印文件的短剧。改免费集数不要求重做。"""+ watermarked = or_(+ EpisodePreview.object_key.startswith("marketplace/series-watermarks-full/"),+ EpisodePreview.object_key.startswith("marketplace/series-previews-hq/"),+ )+ missing = select(SeriesEpisode.id).where(+ SeriesEpisode.series_id == Series.id,+ not_(select(EpisodePreview.id).where(+ EpisodePreview.episode_id == SeriesEpisode.id,+ EpisodePreview.asset_id == SeriesEpisode.asset_id,+ EpisodePreview.status == "done",+ watermarked,+ ).exists()),+ ).exists()+ has_episode = select(SeriesEpisode.id).where(SeriesEpisode.series_id == Series.id).exists()+ return (Series.listed.is_(True), Series.blocked.is_(False), Series.deleted_at.is_(None), Series.audit_status == "approved", has_episode, not_(missing))+++ @router.get("/series", response_model=dict)+ async def list_series(db: DB, q: str = Query("", max_length=100), category: str = Query("", max_length=60), page_number: int = Query(1, alias="page", ge=1), page_size: int = Query(20, ge=1, le=100)):+ query = select(Series).where(*public_series_filters())+ if q:+ query = query.where(Series.title.ilike(f"%{q}%"))+ if category:+ query = query.where(Series.category == category)+ records, meta = await page(db, query.order_by(Series.id.desc()), page_number, page_size)+ return {"items": [await _series_data(db, row) for row in records], "meta": meta}+++ @router.get("/series/import-sources", response_model=dict)+ async def import_sources(db: DB, user: Actor):+ """列出当前用户可明确选择导入的漫剧项目和已生成分集。"""+ from .drama_publish import publish_context- projects = list((await db.execute(select(DramaProject).where(DramaProject.user_id == user.id).order_by(DramaProject.id.desc()))).scalars().all())++ active_teams = select(TeamMember.team_id).where(++ TeamMember.user_id == user.id, TeamMember.active.is_(True),++ )++ projects = list((await db.execute(select(DramaProject).where(++ DramaProject.user_id == user.id,++ or_(DramaProject.team_id.is_(None), DramaProject.team_id.in_(active_teams)),++ ).order_by(DramaProject.id.desc()))).scalars().all())+ result = []+ for project in projects:+ context = await publish_context(project.id, db, user)+ result.append({"id": project.id, "title": project.title, "episodes": context["episodes"]})+ return {"items": result}+++ @router.get("/series/{series_id}", response_model=dict)+ async def get_series(series_id: int, db: DB, user: Visitor):+ item = await db.get(Series, series_id)+ private = bool(item and user and not item.deleted_at and (item.owner_id == user.id or user.role == "admin"))+ if not item or item.deleted_at or (not private and item.blocked):+ fail("系列不存在或未公开", 404)+ if not private:+ visible = (await db.execute(select(Series.id).where(Series.id == series_id, *public_series_filters()))).scalar_one_or_none()+ if not visible:+ fail("系列不存在或未公开", 404)+ return await _series_data(db, item, private=private)+++ @router.post("/series", response_model=dict)+ async def create_series(body: SeriesInput, db: DB, user: Actor):+ from .categories import validate_category+ await validate_category(db, body.category)+ if body.cover_asset_id:+ await asset_owned(db, body.cover_asset_id, user, ("image",))+ values = body.model_dump()+ if "sale_type" not in body.model_fields_set and values["copyright_price_fen"] == 0:+ values["sale_type"] = "free"+ item = Series(owner_id=user.id, **values)+ item.sale_type = _sale_type(item.sale_type, item.copyright_price_fen)+ db.add(item)+ await db.commit()+ return await _series_data(db, item, private=True)+++ @router.patch("/series/{series_id}", response_model=dict)+ async def update_series(series_id: int, body: SeriesUpdate, db: DB, user: Actor):+ item = await _series(db, series_id, user, lock=True)+ from .service import ensure_kept+ ensure_kept(item)+ check_version(item, body.version)+ await ensure_series_idle(db, item.id)+ from .categories import validate_category+ await validate_category(db, body.category, item.category)+ if body.cover_asset_id:+ await asset_owned(db, body.cover_asset_id, user, ("image",))+ values = body.model_dump(exclude={"version"})+ if "sale_type" not in body.model_fields_set and values["copyright_price_fen"] == 0:+ values["sale_type"] = "free"+ values["sale_type"] = _sale_type(values["sale_type"], values["copyright_price_fen"])+ for key, value in values.items():+ setattr(item, key, value)+ item.version += 1+ item.audit_status, item.listed, item.reason = "draft", False, ""+ await pause_series_sales(db, item, bump_episode_versions=True)+ await db.commit()+ return await _series_data(db, item, private=True)+++ @router.post("/series/{series_id}/episodes", response_model=dict)+ async def create_episode(series_id: int, body: EpisodeInput, db: DB, user: Actor):+ series = await _series(db, series_id, user, lock=True)+ from .service import ensure_kept+ ensure_kept(series)+ await ensure_series_idle(db, series.id)+ duplicate = (await db.execute(select(SeriesEpisode.id).where(SeriesEpisode.series_id == series.id, SeriesEpisode.episode_no == body.episode_no))).scalar_one_or_none()+ if duplicate:+ fail("该集数已经存在", 409)+ if body.asset_id:+ await asset_owned_for_draft(db, body.asset_id, user)+ if body.cover_asset_id:+ await asset_owned(db, body.cover_asset_id, user, ("image",))+ item = SeriesEpisode(series_id=series.id, owner_id=user.id, source_type="upload", **body.model_dump())+ if series.sale_type == "platform_unlock" and item.unlock_price_fen <= 0:+ fail("平台投放系列必须为每集设置解锁价")+ db.add(item)+ series.version += 1+ series.audit_status, series.listed = "draft", False+ await pause_series_sales(db, series)+ await db.commit()+ return await _episode_data(db, item, private=True)+++ @router.patch("/series/{series_id}/episodes/{episode_id}", response_model=dict)+ async def update_episode(series_id: int, episode_id: int, body: EpisodeUpdate, db: DB, user: Actor):+ series = await _series(db, series_id, user, lock=True)+ from .service import ensure_kept+ ensure_kept(series)+ await ensure_series_idle(db, series.id)+ item = await _episode(db, episode_id, user, lock=True)+ if item.series_id != series.id:+ fail("分集不属于该系列", 404)+ check_version(item, body.version)+ if body.asset_id:+ await asset_owned_for_draft(db, body.asset_id, user)+ if body.cover_asset_id:+ await asset_owned(db, body.cover_asset_id, user, ("image",))+ asset_changed = body.asset_id != item.asset_id+ for key, value in body.model_dump(exclude={"version"}).items():+ setattr(item, key, value)+ if asset_changed:+ # A manually replaced video no longer represents the frozen imported+ # source. Keep historical tasks/publications, but detach the live mapping.+ item.source_type, item.source_snapshot = "upload", {}+ item.preview_status, item.preview_key, item.preview_attempts = "none", None, 0+ item.playback_status, item.playback_manifest_key, item.playback_attempts = "none", None, 0+ item.version += 1+ item.audit_status, item.listed, item.reason = "draft", False, ""+ series.version += 1+ series.audit_status, series.listed = "draft", False+ await pause_series_sales(db, series)+ await db.commit()+ return await _episode_data(db, item, private=True)+++ @router.delete("/series/{series_id}/episodes/{episode_id}", response_model=dict)+ async def delete_episode(series_id: int, episode_id: int, db: DB, user: Actor):+ series = await _series(db, series_id, user, lock=True)+ from .service import ensure_kept+ ensure_kept(series)+ await ensure_series_idle(db, series.id)+ item = await _episode(db, episode_id, user, lock=True)+ if item.series_id != series.id:+ fail("分集不属于该系列", 404)+ has_order = (await db.execute(select(ContentOrder.id).where(ContentOrder.episode_id == item.id).limit(1))).scalar_one_or_none()+ has_entitlement = (await db.execute(select(Entitlement.id).where(Entitlement.episode_id == item.id).limit(1))).scalar_one_or_none()+ if has_order or has_entitlement:+ fail("该分集已有订单或购买权益,不能删除;请下架系列并保留记录", 409)+ await pause_series_sales(db, series)+ await db.delete(item)+ series.version += 1+ series.audit_status, series.listed = "draft", False+ await db.commit()+ return {"ok": True}+++ @router.post("/series/{series_id}/episodes/import", response_model=dict)+ async def import_episodes(series_id: int, body: ImportEpisodesInput, db: DB, user: Actor):+ """只导入用户明确选择的漫剧分集。复制交给市场 Worker,请求本身不等待长视频。"""+ from .handoff import enqueue_series_import+ from .schemas import PrintfilmEpisodeInput++ payload = PrintfilmEpisodeInput(drama_project_id=body.drama_project_id, episode_ids=list(body.episode_ids))+ return await enqueue_series_import(series_id, payload, db, user)+++ @router.delete("/series/{series_id}", response_model=dict)+ async def delete_series(series_id: int, db: DB, user: Actor):+ """作者软删整部短剧。分集记录保留,但不再出现在广场和我的作品。"""+ item = await _series(db, series_id, user, lock=True)+ from .service import retire_owned+ await retire_owned(db, item, user, "series")+ await db.commit()+ return {"ok": True}+++ @router.post("/series/{series_id}/submit", response_model=dict)+ async def submit_series(series_id: int, body: Version, db: DB, user: Actor):+ series = await _series(db, series_id, user, lock=True)+ from .service import ensure_kept+ ensure_kept(series)+ check_version(series, body.version)+ await ensure_series_idle(db, series.id, submitting=True)+ if series.blocked:+ fail("系列已被管理员封禁")+ if series.audit_status in ("pending", "processing", "approved"):+ return await _series_data(db, series, private=True)+ episodes = list((await db.execute(select(SeriesEpisode).where(SeriesEpisode.series_id == series.id).order_by(SeriesEpisode.episode_no).with_for_update())).scalars().all())+ if not episodes:+ fail("至少添加一集后才能提交审核")+ if [episode.episode_no for episode in episodes] != list(range(1, len(episodes) + 1)):+ fail("分集编号必须从1开始连续排列")+ config = await db.get(RevenueConfig, 1)+ if series.sale_type == "platform_unlock" and (not config or not config.enabled):+ fail("MARKETPLACE_REVENUE_CONFIG_REQUIRED", 409)+ # Paid series require a real private bucket because the submission creates+ # a preview job that will immediately be consumed by the market Worker.+ # Reject early with the standard 503 instead of leaving a misleading pending+ # job when OSS is not configured.+ await storage_ready()+ from .previews import is_watermark_key+ pending_preview = False+ await pause_series_sales(db, series)+ for episode in episodes:+ if episode.blocked:+ fail(f"第{episode.episode_no}集已被限制发布", 409)+ asset = await asset_owned(db, episode.asset_id or 0, user)+ if not episode.cover_asset_id and not series.cover_asset_id:+ fail(f"第{episode.episode_no}集缺少封面,请上传分集封面或系列封面", 409)+ if episode.source == "printfilm":+ from .drama_publish import ensure_import_rights+ await ensure_import_rights(db, episode)+ rights = (await db.execute(select(Rights).where(Rights.asset_id == asset.id).with_for_update())).scalar_one_or_none()+ if not rights or rights.blocked:+ fail("请完成每集版权信息后再提交", 409)+ if rights.details.get("source") != episode.source:+ fail(f"第{episode.episode_no}集版权来源与分集来源不匹配", 409)+ validate_rights(rights.details, full=True, certificate=bool(rights.certificate_asset_id))+ if rights.valid_until and rights.valid_until <= now():+ fail(f"第{episode.episode_no}集版权授权已过期", 409)+ if series.sale_type == "platform_unlock" and episode.unlock_price_fen <= 0:+ fail(f"第{episode.episode_no}集必须设置解锁价")+ publication = (await db.execute(select(Publication).where(+ Publication.content_type == "series_episode", Publication.content_id == episode.id,+ Publication.version == episode.version).with_for_update())).scalar_one_or_none()+ if publication and publication.audit_status == "approved":+ # The series may be re-reviewed because another episode changed.+ # Never reset an approved version's media, financial or rights snapshot.+ episode.version += 1+ publication = None+ # 同一原片已有水印就沿用,改免费集数或收费类型不重新转码。+ done = (await db.execute(select(EpisodePreview).where(+ EpisodePreview.episode_id == episode.id, EpisodePreview.asset_id == asset.id,+ EpisodePreview.status == "done").order_by(EpisodePreview.id.desc()).limit(1))).scalar_one_or_none()+ preview = (await db.execute(select(EpisodePreview).where(+ EpisodePreview.episode_id == episode.id, EpisodePreview.asset_id == asset.id,+ EpisodePreview.version == episode.version).with_for_update())).scalar_one_or_none()+ if done and is_watermark_key(done.object_key):+ if preview is None:+ preview = EpisodePreview(episode_id=episode.id, asset_id=asset.id, version=episode.version, status="done", object_key=done.object_key)+ db.add(preview)+ elif preview.id != done.id:+ preview.status, preview.object_key, preview.error = "done", done.object_key, ""+ preview_status = "done"+ else:+ if preview is None:+ preview = EpisodePreview(episode_id=episode.id, asset_id=asset.id, version=episode.version)+ db.add(preview)+ elif preview.status == "failed":+ preview.status, preview.attempts, preview.error, preview.object_key = "pending", 0, "", None+ preview.lease_token, preview.lease_until = None, None+ preview_status = "done" if preview.status == "done" and is_watermark_key(preview.object_key) else "pending"+ pending_preview = pending_preview or preview_status != "done"+ share = episode.share_bps if episode.share_bps is not None else (+ series.share_bps if series.share_bps is not None else (config.platform_share_bps if config else None))+ values = dict(owner_id=user.id, version=episode.version, asset_id=asset.id,+ cover_asset_id=episode.cover_asset_id or series.cover_asset_id, sale_type=series.sale_type,+ copyright_price_fen=episode.copyright_price_fen or series.copyright_price_fen,+ unlock_price_fen=episode.unlock_price_fen, share_bps=share,+ rights_snapshot={"details": rights.details, "certificate_asset_id": rights.certificate_asset_id,+ "evidence_ids": rights.evidence_ids}, audit_status="pending", listed=False,+ preview_status=preview_status, playback_status="done" if series.sale_type != "platform_unlock" else "pending")+ # Keep the episode's live access gate in sync with its immutable+ # publication. In particular, a paid episode must be marked pending+ # immediately so /media cannot fall back to the original while the+ # watermark job is still running.+ episode.preview_status = preview_status+ episode.playback_status = "done" if series.sale_type != "platform_unlock" else "pending"+ if publication is None:+ publication = Publication(content_type="series_episode", content_id=episode.id, **values)+ db.add(publication)+ else:+ for key, value in values.items():+ setattr(publication, key, value)+ if series.sale_type == "platform_unlock":+ await db.flush()+ playback_job = (await db.execute(select(PlaybackJob).where(+ PlaybackJob.publication_id == publication.id+ ).with_for_update())).scalar_one_or_none()+ if playback_job is None:+ db.add(PlaybackJob(publication_id=publication.id, status="pending"))+ else:+ playback_job.status, playback_job.error = "pending", ""+ playback_job.attempts = 0+ playback_job.lease_token, playback_job.lease_until = None, None+ publication.playback_manifest_key = None+ publication.playback_error = ""+ episode.audit_status = "pending"+ episode.listed = False+ rights.basic_status = rights.full_status = "pending"+ series.audit_status = "processing" if pending_preview else "pending"+ series.listed, series.reason = False, "正在生成水印播放文件" if pending_preview else ""+ event(db, user.id, "series", series.id, "submitted", version=series.version)+ await db.commit()+ return await _series_data(db, series, private=True)+++ @router.post("/series/{series_id}/listing", response_model=dict)+ async def listing_series(series_id: int, body: Version, db: DB, user: Actor, listed: bool = True):+ series = await _series(db, series_id, user, lock=True)+ from .service import ensure_kept+ ensure_kept(series)+ check_version(series, body.version)+ # Lock and snapshot the current episode versions once. Historical+ # publications are kept for entitlements but must never be relisted when a+ # newer episode version is approved.+ episodes = list((await db.execute(+ select(SeriesEpisode).where(SeriesEpisode.series_id == series.id).with_for_update()+ )).scalars().all())+ if listed:+ if series.blocked or series.audit_status != "approved":+ fail("系列内容或权属尚未通过,不能上架")+ if not episodes:+ fail("系列没有可上架的分集")+ from .previews import is_watermark_key+ for episode in episodes:+ if episode.blocked or episode.audit_status != "approved":+ fail(f"第{episode.episode_no}集尚未审核通过")+ preview = (await db.execute(select(EpisodePreview).where(+ EpisodePreview.episode_id == episode.id, EpisodePreview.asset_id == episode.asset_id,+ EpisodePreview.status == "done").order_by(EpisodePreview.id.desc()).limit(1))).scalar_one_or_none()+ if not preview or not is_watermark_key(preview.object_key):+ fail(f"第{episode.episode_no}集水印播放文件尚未生成", 409)+ if series.sale_type == "platform_unlock":+ publication = (await db.execute(select(Publication).where(Publication.content_type == "series_episode", Publication.content_id == episode.id, Publication.version == episode.version))).scalar_one_or_none()+ if not publication or publication.playback_status != "done":+ fail(f"第{episode.episode_no}集播放版本尚未就绪", 409)+ series.listed = listed+ episode_ids = [episode.id for episode in episodes]+ publications = []+ if episode_ids:+ publications = list((await db.execute(+ select(Publication).where(+ Publication.content_type == "series_episode",+ Publication.content_id.in_(episode_ids),+ ).with_for_update()+ )).scalars().all())+ for publication in publications:+ is_current = any(+ episode.id == publication.content_id and episode.version == publication.version+ for episode in episodes+ )+ publication.listed = listed and is_current and publication.audit_status == "approved" and (+ series.sale_type != "platform_unlock" or publication.playback_status == "done"+ )+ for episode in episodes:+ episode.listed = listed and episode.audit_status == "approved" and not episode.blocked+ await db.commit()+ return await _series_data(db, series, private=True)+diff --cc backend/tests/test_marketplace_drama_concurrency.pyindex 0000000,c508a21..0a5bc61mode 000000,100644..100644--- a/backend/tests/test_marketplace_drama_concurrency.py+++ b/backend/tests/test_marketplace_drama_concurrency.py@@@ -1,0 -1,189 +1,190 @@@+ """真实并发发布:两个独立 HTTP 请求/数据库事务,验证 PG 锁和提交可见性。"""+ import asyncio+ import re+ from types import SimpleNamespace+ import uuid++ from fastapi import FastAPI+ import httpx+ import pytest_asyncio+ from sqlalchemy import func, select, text+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++ from app.config import get_settings+ from app.database import Base, get_db+ from app.deps import get_current_user+ from app.models import Project, Shot, Template, User+ from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProject, DramaScript+ from app.models_tasks import TaskRun++from app.models_teams import Team, TeamMember+ from app.marketplace import drama_media, drama_publish, storage+ from app.marketplace.models import DramaPublishBatch, Handoff, MarketBase, Series, SeriesEpisode+ from conftest import _ensure_test_database, _resolve_test_database_url+++ @pytest_asyncio.fixture+ async def concurrent_publish_ctx(monkeypatch):+ """独立测试库内提交随机 schema,finally 仅删除本用例拥有的 schema。"""+ url, name = _resolve_test_database_url(get_settings().database_url)+ await _ensure_test_database(url, name)+ base_engine = create_async_engine(url, pool_size=5)+ schema = f"drama_concurrency_test_{uuid.uuid4().hex}"+ assert re.fullmatch(r"drama_concurrency_test_[0-9a-f]{32}", schema)+ engine = base_engine.execution_options(schema_translate_map={None: schema})+ sessions = async_sessionmaker(engine, expire_on_commit=False)+ state = SimpleNamespace(engine=engine, sessions=sessions, request_pids=[])+ try:+ async with base_engine.begin() as connection:+ await connection.execute(text(f'CREATE SCHEMA "{schema}"'))+ async with engine.begin() as connection:+ tables = [item.__table__ for item in (- User, Template, Project, Shot, DramaProject, DramaScript,++ User, Team, TeamMember, Template, Project, Shot, DramaProject, DramaScript,+ DramaAsset, DramaEpisode, DramaEpisodeFragment, TaskRun,+ )]+ await connection.run_sync(lambda sync: Base.metadata.create_all(sync, tables=tables))+ await connection.run_sync(MarketBase.metadata.create_all)+ async with sessions() as db:+ owner = User(email="[email protected]", hashed_password="unused")+ db.add(owner)+ await db.flush()+ project = DramaProject(user_id=owner.id, title="并发整集发布", description="独立来源快照")+ db.add(project)+ await db.flush()+ episode = DramaEpisode(project_id=project.id, name="第1集", params={"episodeNumber": 1})+ db.add(episode)+ await db.flush()+ for order in range(3):+ db.add(DramaEpisodeFragment(episode_id=episode.id, sort_order=order,+ video=f"/static/test/concurrent-shot-{order}.mp4"))+ await db.commit()+ state.owner_id, state.project_id, state.episode_id = owner.id, project.id, episode.id++ async def db_override():+ # No shared outer transaction or savepoint: each HTTP request must+ # really commit, release PG locks and expose rows to the other.+ async with sessions() as db:+ state.request_pids.append(await db.scalar(text("SELECT pg_backend_pid()")))+ try:+ yield db+ except BaseException:+ await db.rollback()+ raise++ async def actor_override():+ return SimpleNamespace(id=state.owner_id, role="user")++ monkeypatch.setattr(storage, "bucket", lambda: object())+ monkeypatch.setattr(storage, "configured", lambda: True)+ monkeypatch.setattr(drama_media, "source_stamp", lambda locator: {+ "kind": "local", "locator": locator, "size_bytes": 100,+ "file_id": "stable-source", "mtime_ns": 1, "fingerprint": "test-source",+ })+ async with sessions() as db:+ snapshot = await drama_publish.episode_snapshot(db, state.owner_id, state.project_id, state.episode_id)+ state.source_version = snapshot["source_version"]+ app = FastAPI()+ app.include_router(drama_publish.router, prefix="/api/marketplace")+ app.dependency_overrides[get_db] = db_override+ app.dependency_overrides[get_current_user] = actor_override+ async with (+ httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://first") as first,+ httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://second") as second,+ ):+ state.clients = (first, second)+ yield state+ finally:+ # The generated identifier is checked again at the destructive boundary.+ # No shared/public schema or pre-existing test tables are touched.+ assert re.fullmatch(r"drama_concurrency_test_[0-9a-f]{32}", schema)+ async with base_engine.begin() as connection:+ await connection.execute(text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE'))+ await base_engine.dispose()+++ def payload(ctx, key, *, series_id=None, series_version=None):+ return {"episodes": [{"episode_id": ctx.episode_id, "source_version": ctx.source_version}],+ "idempotency_key": key, "series_id": series_id, "series_version": series_version}+++ async def wait_for_two_database_waiters(ctx):+ """不依赖调度运气:确认两个不同 PG 连接实际争用锁后才放行。"""+ async with asyncio.timeout(10):+ async with ctx.engine.connect() as observer:+ while True:+ if len(ctx.request_pids) == 2:+ first, second = ctx.request_pids+ assert first != second, "必须使用两个独立数据库连接"+ waiting = set((await observer.execute(text(+ "SELECT DISTINCT pid FROM pg_locks WHERE pid IN (:first, :second) AND NOT granted"+ ), {"first": first, "second": second})).scalars().all())+ if waiting == {first, second}:+ return+ await asyncio.sleep(0.01)+++ async def race_requests(ctx, bodies, *, guard_key=None, guard_series_id=None):+ """第三个事务先持锁,让两个请求确定重叠;释放后使用真实提交顺序。"""+ tasks = []+ async with ctx.sessions() as guard:+ try:+ if guard_key is not None:+ lock_id = int(drama_publish.digest([ctx.owner_id, guard_key])[:16], 16)+ if lock_id >= 2**63:+ lock_id -= 2**64+ await guard.execute(text("SELECT pg_advisory_xact_lock(:key)"), {"key": lock_id})+ else:+ await guard.execute(select(Series).where(Series.id == guard_series_id).with_for_update())+ path = f"/api/marketplace/printfilm/dramas/{ctx.project_id}/publish"+ tasks = [asyncio.create_task(client.post(path, json=body)) for client, body in zip(ctx.clients, bodies)]+ await wait_for_two_database_waiters(ctx)+ assert not any(task.done() for task in tasks)+ await guard.commit()+ return await asyncio.wait_for(asyncio.gather(*tasks), timeout=10)+ finally:+ await guard.rollback()+ for task in tasks:+ if not task.done():+ task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)+++ async def test_concurrent_same_key_new_series_creates_one_batch_episode_and_handoff(concurrent_publish_ctx):+ ctx = concurrent_publish_ctx+ key = uuid.uuid4().hex+ body = payload(ctx, key)+ responses = await race_requests(ctx, (body, body), guard_key=key)+ assert [response.status_code for response in responses] == [200, 200], [response.text for response in responses]+ assert responses[0].json() == responses[1].json()+ async with ctx.sessions() as db:+ for model in (Series, DramaPublishBatch, SeriesEpisode, Handoff):+ assert await db.scalar(select(func.count()).select_from(model)) == 1+ target = (await db.execute(select(SeriesEpisode))).scalar_one()+ handoff = (await db.execute(select(Handoff))).scalar_one()+ batch = (await db.execute(select(DramaPublishBatch))).scalar_one()+ assert batch.episode_ids == [target.id] and batch.handoff_ids == [handoff.id]+ assert handoff.target_id == target.id and handoff.status == "pending"+ assert [clip["sort_order"] for clip in handoff.source_snapshot["clips"]] == [0, 1, 2]+++ async def test_concurrent_different_keys_same_target_source_version_never_duplicates_episode(concurrent_publish_ctx):+ ctx = concurrent_publish_ctx+ async with ctx.sessions() as db:+ target = Series(owner_id=ctx.owner_id, title="已有系列", description="保留已有简介")+ db.add(target)+ await db.commit()+ series_id, version = target.id, target.version+ bodies = [payload(ctx, uuid.uuid4().hex, series_id=series_id, series_version=version) for _ in range(2)]+ responses = await race_requests(ctx, bodies, guard_series_id=series_id)+ statuses = [response.status_code for response in responses]+ assert 200 in statuses and all(status in (200, 409) for status in statuses), [response.text for response in responses]+ successes = [response.json() for response in responses if response.status_code == 200]+ assert len({item["items"][0]["id"] for item in successes}) == 1+ assert len({item["handoffs"][0]["id"] for item in successes}) == 1+ async with ctx.sessions() as db:+ for model in (Series, SeriesEpisode, Handoff):+ assert await db.scalar(select(func.count()).select_from(model)) == 1+ assert await db.scalar(select(func.count()).select_from(DramaPublishBatch)) == len(successes)+ target = await db.get(Series, series_id)+ assert target.title == "已有系列" and target.description == "保留已有简介"+ assert target.version == version + 1diff --cc backend/tests/test_marketplace_drama_publish.pyindex 0000000,4ece813..ce49aa6mode 000000,100644..100644--- a/backend/tests/test_marketplace_drama_publish.py+++ b/backend/tests/test_marketplace_drama_publish.py@@@ -1,0 -1,399 +1,432 @@@+ """漫剧到市场的整集发布:隔离测试库/schema,文件存储仅使用测试替身。"""+ from types import SimpleNamespace+ from contextlib import asynccontextmanager+ from datetime import timedelta+ import uuid++ from fastapi import FastAPI, HTTPException+ import httpx+ import pytest+ import pytest_asyncio+ from sqlalchemy import func, select, text+ from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine++ from app.config import get_settings+ from app.database import Base, get_db+ from app.deps import get_current_user+ from app.models import Project, Shot, Template, User+ from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProject, DramaScript+ from app.models_tasks import TaskRun++from app.models_teams import Team, TeamMember+ from app.marketplace import drama_media, drama_publish, handoff, storage++from app.marketplace import series as series_api+ from app.marketplace.authorization import VERSION+ from app.marketplace.models import Asset, Authorization, DramaPublishBatch, Handoff, MarketBase, Publication, Rights, Series, SeriesEpisode+ from app.marketplace.service import now+ from conftest import _ensure_test_database, _resolve_test_database_url+++ @pytest_asyncio.fixture+ async def drama_publish_ctx(monkeypatch):+ url, name = _resolve_test_database_url(get_settings().database_url)+ await _ensure_test_database(url, name)+ engine = create_async_engine(url)+ async with engine.connect() as connection:+ outer = await connection.begin()+ schema = f"drama_publish_test_{uuid.uuid4().hex}"+ await connection.execute(text(f'CREATE SCHEMA "{schema}"'))+ connection = await connection.execution_options(schema_translate_map={None: schema})- tables = [item.__table__ for item in (User, Template, Project, Shot, DramaProject, DramaScript, DramaAsset, DramaEpisode, DramaEpisodeFragment, TaskRun)]++ tables = [item.__table__ for item in (User, Team, TeamMember, Template, Project, Shot, DramaProject, DramaScript, DramaAsset, DramaEpisode, DramaEpisodeFragment, TaskRun)]+ await connection.run_sync(lambda sync: Base.metadata.create_all(sync, tables=tables))+ await connection.run_sync(MarketBase.metadata.create_all)+ db = AsyncSession(bind=connection, expire_on_commit=False, join_transaction_mode="create_savepoint")+ owner = User(email="[email protected]", hashed_password="unused")+ other = User(email="[email protected]", hashed_password="unused")+ db.add_all([owner, other])+ await db.commit()+ ctx = SimpleNamespace(db=db, owner=owner, other=other, user=owner, source_revision=1)++ async def db_override():+ try:+ yield db+ except Exception:+ await db.rollback()+ await db.refresh(owner)+ await db.refresh(other)+ raise++ async def actor_override():+ return ctx.user++ def source_stamp(locator):+ return {"kind": "local", "locator": locator, "size_bytes": 100, "file_id": "source-file", "mtime_ns": ctx.source_revision, "fingerprint": f"revision-{ctx.source_revision}"}++ app = FastAPI()+ app.include_router(drama_publish.router, prefix="/api/marketplace")+ app.include_router(handoff.router, prefix="/api/marketplace")+ app.dependency_overrides[get_db] = db_override+ app.dependency_overrides[get_current_user] = actor_override+ monkeypatch.setattr(storage, "bucket", lambda: object())+ monkeypatch.setattr(storage, "configured", lambda: True)+ monkeypatch.setattr(drama_media, "source_stamp", source_stamp)+ try:+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:+ ctx.client = client+ yield ctx+ finally:+ await db.close()+ await outer.rollback()+ await engine.dispose()+++ async def source(ctx, *, owner=None, episodes=1, fragments=3):+ project = DramaProject(user_id=(owner or ctx.owner).id, title="完整漫剧", description="导入后的独立介绍")+ ctx.db.add(project)+ await ctx.db.flush()+ items, clips = [], []+ for number in range(1, episodes + 1):+ episode = DramaEpisode(project_id=project.id, name=f"原第{number}集", params={"episodeNumber": number})+ ctx.db.add(episode)+ await ctx.db.flush()+ for index in range(fragments):+ # 故意逆序创建,用排序断言防止只导入最后一镜。+ order = fragments - index - 1+ clip = DramaEpisodeFragment(episode_id=episode.id, sort_order=order, video=f"/static/test/episode-{number}-shot-{order}.mp4", cover=f"/static/test/cover-{number}.png")+ ctx.db.add(clip)+ clips.append(clip)+ items.append(episode)+ await ctx.db.commit()+ return project, items, clips+++ async def publish_payload(ctx, project, episodes, *, key=None, series=None, update=False):+ snapshot = [await drama_publish.episode_snapshot(ctx.db, ctx.owner.id, project.id, episode.id) for episode in episodes]+ return {"episodes": [{"episode_id": item["drama_episode_id"], "source_version": item["source_version"], "update": update} for item in snapshot],+ "series_id": series.id if series else None, "series_version": series.version if series else None, "idempotency_key": key or uuid.uuid4().hex}+++ async def post_publish(ctx, project, payload):+ return await ctx.client.post(f"/api/marketplace/printfilm/dramas/{project.id}/publish", json=payload)+++ async def published(ctx):+ project, episodes, clips = await source(ctx)+ response = await post_publish(ctx, project, await publish_payload(ctx, project, episodes))+ assert response.status_code == 200, response.text+ body = response.json()+ task = await ctx.db.get(Handoff, body["handoffs"][0]["id"])+ target = await ctx.db.get(SeriesEpisode, body["items"][0]["id"])+ series = await ctx.db.get(Series, body["series_id"])+ return SimpleNamespace(project=project, episodes=episodes, clips=clips, task=task, target=target, series=series)+++ async def test_context_shows_complete_counts_and_all_owned_target_series(drama_publish_ctx):+ ctx = drama_publish_ctx+ project, episodes, clips = await source(ctx, episodes=2)+ clips[0].video = ""+ own = Series(owner_id=ctx.owner.id, title="我的其他系列")+ foreign = Series(owner_id=ctx.other.id, title="其他人的系列")+ ctx.db.add_all([own, foreign])+ await ctx.db.commit()+ response = await ctx.client.get(f"/api/marketplace/printfilm/dramas/{project.id}/publish-context")+ assert response.status_code == 200, response.text+ body = response.json()+ assert body["project"]["description"] == project.description+ assert body["episodes"][0]["fragment_count"] == 3 and body["episodes"][0]["completed_count"] == 2+ assert body["episodes"][0]["ready"] is False and "SOURCE_NOT_READY" in body["episodes"][0]["reason"]+ assert body["episodes"][1]["ready"] is True+ assert [item["id"] for item in body["series"]] == [own.id]+ assert body["storage_configured"] is True and body["authorization_ready"] is False+ assert "/static/" not in response.text++++async def test_team_creator_loses_publish_access_and_import_source_after_leaving(drama_publish_ctx):++ """创建者身份不会绕过离队限制,来源列表也保留个人与账号隔离。"""++ ctx = drama_publish_ctx++ team = Team(name="市场导入团队", owner_user_id=ctx.other.id)++ ctx.db.add(team)++ await ctx.db.flush()++ membership = TeamMember(team_id=team.id, user_id=ctx.owner.id, role="member", active=True)++ ctx.db.add(membership)++ personal, _, _ = await source(ctx)++ project, _, _ = await source(ctx)++ foreign, _, _ = await source(ctx, owner=ctx.other)++ project.team_id = foreign.team_id = team.id++ await ctx.db.commit()++ personal_id, project_id, foreign_id = personal.id, project.id, foreign.id++ path = f"/api/marketplace/printfilm/dramas/{project_id}/publish-context"++++ response = await ctx.client.get(path)++ assert response.status_code == 200, response.text++ sources = await series_api.import_sources(ctx.db, ctx.owner)++ assert {item["id"] for item in sources["items"]} == {personal_id, project_id}++ assert foreign_id not in {item["id"] for item in sources["items"]}++++ membership.active = False++ await ctx.db.commit()++ response = await ctx.client.get(path)++ assert response.status_code == 404, response.text++ assert (await ctx.db.get(DramaProject, project_id)).user_id == ctx.owner.id++ sources = await series_api.import_sources(ctx.db, ctx.owner)++ assert [item["id"] for item in sources["items"]] == [personal_id]+++++ @pytest.mark.parametrize("case", ["foreign_project", "foreign_episode", "foreign_target"])+ async def test_publish_rejects_cross_account_sources_and_targets(drama_publish_ctx, case):+ ctx = drama_publish_ctx+ project, episodes, _ = await source(ctx)+ payload = await publish_payload(ctx, project, episodes)+ if case == "foreign_project":+ ctx.user = ctx.other+ elif case == "foreign_episode":+ other_project, other_episodes, _ = await source(ctx, owner=ctx.other)+ payload["episodes"][0]["episode_id"] = other_episodes[0].id+ else:+ target = Series(owner_id=ctx.other.id, title="其他系列")+ ctx.db.add(target)+ await ctx.db.commit()+ payload["series_id"] = target.id+ payload["series_version"] = target.version+ response = await post_publish(ctx, project, payload)+ assert response.status_code == 404, response.text+ assert await ctx.db.scalar(select(func.count()).select_from(Handoff)) == 0+ assert await ctx.db.scalar(select(func.count()).select_from(DramaPublishBatch)) == 0+++ @pytest.mark.parametrize("case", ["missing_shot", "task_video", "task_plan", "episode_plan", "shot_video"])+ async def test_incomplete_or_generating_episode_creates_no_market_draft(drama_publish_ctx, case):+ ctx = drama_publish_ctx+ project, episodes, clips = await source(ctx)+ payload = await publish_payload(ctx, project, episodes)+ if case == "missing_shot":+ clips[0].video = ""+ elif case.startswith("task_"):+ ctx.db.add(TaskRun(domain="drama", task_type="fragment_video" if case == "task_video" else "fragment_plan", status="running", requested_by=ctx.owner.id,+ episode_id=episodes[0].id, drama_project_id=project.id, fragment_id=clips[0].id))+ elif case == "episode_plan":+ episodes[0].params = {"episodeNumber": 1, "fragment_plan_status": "running"}+ else:+ clips[0].params = {"video_gen": {"status": "running"}}+ await ctx.db.commit()+ response = await post_publish(ctx, project, payload)+ assert response.status_code == 409 and "MARKETPLACE_SOURCE_NOT_READY" in response.text+ assert await ctx.db.scalar(select(func.count()).select_from(Series)) == 0+ assert await ctx.db.scalar(select(func.count()).select_from(Handoff)) == 0+++ async def test_storage_unavailable_never_creates_empty_series(drama_publish_ctx, monkeypatch):+ ctx = drama_publish_ctx+ project, episodes, _ = await source(ctx)+ payload = await publish_payload(ctx, project, episodes)++ def unavailable():+ raise HTTPException(503, {"code": "MARKETPLACE_STORAGE_UNAVAILABLE", "message": "文件服务暂未配置"})++ monkeypatch.setattr(storage, "bucket", unavailable)+ response = await post_publish(ctx, project, payload)+ assert response.status_code == 503 and "MARKETPLACE_STORAGE_UNAVAILABLE" in response.text+ assert await ctx.db.scalar(select(func.count()).select_from(Series)) == 0+++ async def test_atomic_publish_is_idempotent_orders_all_clips_and_keeps_upstream(drama_publish_ctx):+ ctx = drama_publish_ctx+ project, episodes, clips = await source(ctx, episodes=2)+ payload = await publish_payload(ctx, project, list(reversed(episodes)))+ response = await post_publish(ctx, project, payload)+ assert response.status_code == 200, response.text+ result = response.json()+ again = await post_publish(ctx, project, payload)+ assert again.status_code == 200 and again.json() == result+ assert await ctx.db.scalar(select(func.count()).select_from(Series)) == 1+ assert await ctx.db.scalar(select(func.count()).select_from(SeriesEpisode)) == 2+ assert await ctx.db.scalar(select(func.count()).select_from(Handoff)) == 2+ target = await ctx.db.get(Series, result["series_id"])+ assert target.title == project.title and target.description == project.description+ for index, item in enumerate(result["items"]):+ assert item["episode_no"] == index + 1 and item["title"] == episodes[index].name+ task = await ctx.db.get(Handoff, result["handoffs"][index]["id"])+ assert [clip["sort_order"] for clip in task.source_snapshot["clips"]] == [0, 1, 2]+ assert len(task.source_snapshot["clips"]) == 3+ assert all(clip.video.startswith("/static/test/") for clip in clips)+ payload["title"] = "另一次不同发布"+ conflict = await post_publish(ctx, project, payload)+ assert conflict.status_code == 409+++ async def test_same_source_version_in_same_target_reuses_episode_across_batches(drama_publish_ctx):+ ctx = drama_publish_ctx+ existing = await published(ctx)+ response = await post_publish(ctx, existing.project, await publish_payload(ctx, existing.project, existing.episodes, series=existing.series))+ assert response.status_code == 200, response.text+ assert response.json()["items"][0]["id"] == existing.target.id+ assert response.json()["handoffs"][0]["id"] == existing.task.id+ assert await ctx.db.scalar(select(func.count()).select_from(SeriesEpisode)) == 1+ assert await ctx.db.scalar(select(func.count()).select_from(Handoff)) == 1+++ async def test_changed_source_requires_confirmation_and_preserves_old_publication_asset(drama_publish_ctx):+ ctx = drama_publish_ctx+ existing = await published(ctx)+ old_asset = Asset(owner_id=ctx.owner.id, kind="video", filename="old.mp4", content_type="video/mp4", size_bytes=100, object_key="marketplace/old.mp4", status="ready")+ ctx.db.add(old_asset)+ await ctx.db.flush()+ existing.target.asset_id, existing.target.audit_status, existing.target.listed = old_asset.id, "approved", True+ existing.target.source_snapshot = {**existing.target.source_snapshot, "pending_handoff_id": None, "last_handoff_id": existing.task.id}+ existing.task.status, existing.task.asset_id = "ready", old_asset.id+ existing.series.audit_status, existing.series.listed = "approved", True+ publication = Publication(content_type="series_episode", content_id=existing.target.id, owner_id=ctx.owner.id, version=existing.target.version,+ asset_id=old_asset.id, sale_type="copyright_contact", audit_status="approved", listed=True)+ ctx.db.add(publication)+ await ctx.db.commit()+ ctx.source_revision = 2+ payload = await publish_payload(ctx, existing.project, existing.episodes, series=existing.series)+ response = await post_publish(ctx, existing.project, payload)+ assert response.status_code == 409 and "SOURCE_CHANGED" in response.text+ # Failed request rolls back the savepoint; fetch state again before a new request.+ await ctx.db.refresh(existing.series)+ await ctx.db.refresh(existing.target)+ await ctx.db.refresh(publication)+ await ctx.db.refresh(existing.project)+ await ctx.db.refresh(old_asset)+ for episode in existing.episodes:+ await ctx.db.refresh(episode)+ payload = await publish_payload(ctx, existing.project, existing.episodes, series=existing.series, update=True)+ response = await post_publish(ctx, existing.project, payload)+ assert response.status_code == 200, response.text+ assert response.json()["items"][0]["id"] == existing.target.id+ assert existing.target.asset_id == old_asset.id and publication.asset_id == old_asset.id+ assert existing.series.listed is False and existing.series.audit_status == "draft"+ assert existing.target.listed is False and publication.listed is False+ assert await ctx.db.scalar(select(func.count()).select_from(Handoff)) == 2+++ @pytest.mark.parametrize("case", ["version", "asset", "new_task", "blocked", "deleted_series"])+ async def test_fenced_bind_never_overwrites_modified_deleted_or_superseded_target(drama_publish_ctx, case):+ ctx = drama_publish_ctx+ existing = await published(ctx)+ candidate = Asset(owner_id=ctx.owner.id, kind="video", filename="new.mp4", content_type="video/mp4", size_bytes=100, object_key=f"marketplace/{uuid.uuid4().hex}.mp4", status="ready")+ ctx.db.add(candidate)+ await ctx.db.flush()+ if case == "version":+ existing.target.version += 1+ elif case == "asset":+ existing.target.asset_id = candidate.id+ elif case == "new_task":+ existing.target.source_snapshot = {**existing.target.source_snapshot, "pending_handoff_id": existing.task.id + 1}+ elif case == "blocked":+ existing.target.blocked = True+ else:+ existing.series.deleted_at = now()+ before = existing.target.asset_id+ await ctx.db.flush()+ with pytest.raises(HTTPException, match="MARKETPLACE_TARGET_CHANGED"):+ await handoff._bind(ctx.db, existing.task, candidate.id, None)+ assert existing.target.asset_id == before+++ async def test_successful_bind_auto_attaches_authorization_without_approving_rights(drama_publish_ctx):+ ctx = drama_publish_ctx+ existing = await published(ctx)+ ctx.db.add(Authorization(owner_id=ctx.owner.id, template_version=VERSION, signer_name="测试用户", body="terms", body_hash="0"*64,+ letter_key="marketplace/letter.png", signature_key="marketplace/signature.png", client_ip="127.0.0.1", user_agent="test"))+ candidate = Asset(owner_id=ctx.owner.id, kind="video", filename="new.mp4", content_type="video/mp4", size_bytes=100, object_key="marketplace/new.mp4", status="ready")+ ctx.db.add(candidate)+ await ctx.db.flush()+ existing.task.asset_id = candidate.id+ await handoff._bind(ctx.db, existing.task, candidate.id, None)+ await ctx.db.flush()+ proof = (await ctx.db.execute(select(Rights).where(Rights.asset_id == candidate.id))).scalar_one()+ assert existing.target.asset_id == candidate.id and existing.task.status == "ready"+ assert proof.details["source"] == "printfilm" and int(proof.details["authorization_id"]) > 0+ assert proof.basic_status != "approved" and proof.full_status != "approved"+++ async def test_source_file_change_is_detected_before_worker_binding(drama_publish_ctx):+ ctx = drama_publish_ctx+ existing = await published(ctx)+ ctx.source_revision += 1+ with pytest.raises(HTTPException, match="MARKETPLACE_SOURCE_CHANGED"):+ await handoff._validate_drama_source(ctx.db, existing.task)+ assert existing.target.asset_id is None+++ async def test_terminal_same_source_can_be_explicitly_resynced(drama_publish_ctx):+ """源恢复原状后仍能重新确认,不永远复用终止的旧任务。"""+ ctx = drama_publish_ctx+ existing = await published(ctx)+ existing.task.status = "failed"+ existing.task.error = "MARKETPLACE_SOURCE_CHANGED:源分集曾在同步时重新生成"+ await ctx.db.commit()+ context = (await ctx.client.get(f"/api/marketplace/printfilm/dramas/{existing.project.id}/publish-context")).json()+ target = next(row for row in context["series"] if row["id"] == existing.series.id)+ assert target["imports"][0]["requires_update"] is True+ payload = await publish_payload(ctx, existing.project, existing.episodes, series=existing.series, update=True)+ response = await post_publish(ctx, existing.project, payload)+ assert response.status_code == 200, response.text+ assert response.json()["items"][0]["id"] == existing.target.id+ assert response.json()["handoffs"][0]["id"] != existing.task.id+ assert response.json()["handoffs"][0]["status"] == "pending"+ assert await ctx.db.scalar(select(func.count()).select_from(SeriesEpisode)) == 1+++ @pytest.mark.parametrize("case", ["success", "source_changed", "target_changed", "lease_stolen", "resume_expired_lease"])+ async def test_worker_recovery_and_final_binding_guards(drama_publish_ctx, monkeypatch, case):+ """实际执行领取/阶段/终态;仅替换远端存储与媒体制作,不伪造任务状态。"""+ ctx = drama_publish_ctx+ existing = await published(ctx)+ discarded, produced, phases = [], [], []+ original_phase = handoff._phase++ @asynccontextmanager+ async def sessions():+ # 每个 worker 阶段顺序使用同一测试连接,保持随机 schema 和外层回滚。+ yield ctx.db++ async def phase(handoff_id, token, value):+ phases.append(value)+ return await original_phase(handoff_id, token, value)++ async def prepare_video(snapshot, destination, on_phase):+ assert [item["sort_order"] for item in snapshot["clips"]] == [0, 1, 2]+ produced.append(destination)+ for value in ("copying", "composing", "validating"):+ await on_phase(value)+ if case == "source_changed":+ ctx.source_revision += 1+ elif case == "target_changed":+ existing.target.version += 1+ await ctx.db.commit()+ elif case == "lease_stolen":+ existing.task.lease_token = "other-worker"+ await ctx.db.commit()+ return {"size_bytes": 100, "content_type": "video/mp4", "fingerprint": "f"*64, "duration_seconds": 9.0}++ async def prepare_cover(_locator, destination, _stamp=None):+ produced.append(destination)+ return {"size_bytes": 10, "content_type": "image/png"}++ monkeypatch.setattr(handoff, "AsyncSessionLocal", sessions)+ monkeypatch.setattr(handoff, "_phase", phase)+ monkeypatch.setattr(drama_media, "prepare_drama_video", prepare_video)+ monkeypatch.setattr(drama_media, "prepare_drama_cover", prepare_cover)+ monkeypatch.setattr(storage, "discard_generated", discarded.append)+ if case == "resume_expired_lease":+ existing.task.status, existing.task.lease_token = "running", "dead-worker"+ existing.task.lease_until = now() - timedelta(seconds=1)+ await ctx.db.commit()+ assert await handoff.run_handoff_once() is True+ assert phases == ["copying", "composing", "validating"]+ if case in ("success", "resume_expired_lease"):+ assert existing.task.status == "ready" and existing.target.asset_id is not None+ assert existing.task.lease_token is None and existing.task.lease_until is None+ assert existing.target.cover_asset_id is not None+ assert await ctx.db.scalar(select(func.count()).select_from(Asset)) == 2+ assert discarded == []+ else:+ assert existing.target.asset_id is None and existing.target.cover_asset_id is None+ assert await ctx.db.scalar(select(func.count()).select_from(Asset)) == 0+ assert sorted(discarded) == sorted(produced)+ if case == "lease_stolen":+ assert existing.task.lease_token == "other-worker" # 旧 worker 不得改新租约。+ else:+ assert existing.task.status == "failed" and ("SOURCE_CHANGED" if case == "source_changed" else "TARGET_CHANGED") in existing.task.errordiff --cc backend/tests/test_team_schema_cli.pyindex 6c4986a,0000000..ed855e9mode 100644,000000..100644--- a/backend/tests/test_team_schema_cli.py+++ b/backend/tests/test_team_schema_cli.py@@@ -1,147 -1,0 +1,162 @@@+"""数据库结构 CLI 的离线回归,不连接数据库或执行真实迁移。"""+import asyncio+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest++from app import database, main, media_schema, team_schema+from scripts import prepare_team_schema as cli++- def stub_engine():++def stub_engine(dialect="postgresql"):+ """提供记录事务入口的假引擎与假连接,DDL 只由 AsyncMock 接收。"""- connection = SimpleNamespace(run_sync=AsyncMock(), execute=AsyncMock())++ connection = SimpleNamespace(dialect=SimpleNamespace(name=dialect), run_sync=AsyncMock(), execute=AsyncMock())+ entered = []++ @asynccontextmanager+ async def begin():+ """记录真正被选中的引擎,模拟正常结束事务。"""+ entered.append(True)+ yield connection++ return SimpleNamespace(begin=begin, dispose=AsyncMock()), connection, entered++[email protected]("explicit", [False, True])+async def test_init_db_uses_requested_engine_without_replacing_global(monkeypatch, explicit):+ """默认启动入口不变;显式迁移引擎只用于该次初始化。"""+ default, default_connection, default_entered = stub_engine()+ override, override_connection, override_entered = stub_engine()+ monkeypatch.setattr(database, "engine", default)+ await database.init_db(engine_override=override if explicit else None)+ selected = override_connection if explicit else default_connection+ selected.run_sync.assert_awaited_once_with(database.Base.metadata.create_all)+ assert database.engine is default+ assert len(default_entered) == (0 if explicit else 1)+ assert len(override_entered) == (1 if explicit else 0)++++async def test_schema_patches_skip_postgres_ddl_for_sqlite(monkeypatch):++ """SQLite 测试库不执行团队、媒体及市场的 PostgreSQL 增量补列。"""++ engine, connection, entered = stub_engine("sqlite")++ team_patches = AsyncMock()++ media_patches = AsyncMock()++ monkeypatch.setattr(team_schema, "apply_team_schema_patches", team_patches)++ monkeypatch.setattr(media_schema, "apply_media_schema_patches", media_patches)++ await main._apply_schema_patches(engine_override=engine)++ assert entered == [True]++ team_patches.assert_not_awaited()++ media_patches.assert_not_awaited()++ connection.execute.assert_not_awaited()++++[email protected]("explicit", [False, True])+async def test_schema_patches_use_requested_engine_without_replacing_global(monkeypatch, explicit):+ """补列与团队迁移共享显式引擎,不临时更换应用全局连接池。"""+ default, default_connection, default_entered = stub_engine()+ override, override_connection, override_entered = stub_engine()+ team_patches = AsyncMock()+ media_patches = AsyncMock()+ monkeypatch.setattr(main, "engine", default)+ monkeypatch.setattr(main, "_pg_columns", AsyncMock(return_value=set()))+ monkeypatch.setattr(team_schema, "apply_team_schema_patches", team_patches)+ monkeypatch.setattr(media_schema, "apply_media_schema_patches", media_patches)+ await main._apply_schema_patches(engine_override=override if explicit else None)+ selected = override_connection if explicit else default_connection+ team_patches.assert_awaited_once_with(selected)+ media_patches.assert_awaited_once_with(selected)+ assert selected.execute.await_count > 0+ assert main.engine is default+ assert len(default_entered) == (0 if explicit else 1)+ assert len(override_entered) == (1 if explicit else 0)++[email protected]("failure", [None, "init", "patch"])+async def test_schema_cli_owns_configured_engine_and_always_disposes(monkeypatch, failure):+ """两个步骤按顺序使用限时迁移连接,任一失败都关闭独立连接池。"""+ from app import config+ from sqlalchemy.ext import asyncio as sqlalchemy_asyncio++ engine, _, _ = stub_engine()+ created = Mock(return_value=engine)+ url = "postgresql+asyncpg://test.invalid/schema_test"+ monkeypatch.setattr(config, "get_settings", lambda: SimpleNamespace(database_url=url))+ monkeypatch.setattr(sqlalchemy_asyncio, "create_async_engine", created)+ steps = []+ deadlines = []++ async def init(*, engine_override):+ """模拟建表入口,记录执行顺序并可主动失败。"""+ assert engine_override is engine+ steps.append("init")+ if failure == "init":+ raise RuntimeError("init failed")++ async def patches(*, engine_override):+ """模拟补列入口,确认其复用同一独立引擎。"""+ assert engine_override is engine+ steps.append("patch")+ if failure == "patch":+ raise RuntimeError("patch failed")++ async def limited(awaitable, timeout):+ """仅记录生产超时参数,离线步骤直接执行。"""+ deadlines.append(timeout)+ return await awaitable++ monkeypatch.setattr(database, "init_db", init)+ monkeypatch.setattr(main, "_apply_schema_patches", patches)+ monkeypatch.setattr(cli.asyncio, "wait_for", limited)+ if failure:+ with pytest.raises(RuntimeError, match=failure):+ await cli.prepare()+ else:+ await cli.prepare()+ assert steps == (["init"] if failure == "init" else ["init", "patch"])+ assert deadlines == [60] * len(steps)+ created.assert_called_once_with(url, connect_args={"server_settings": {+ "application_name": "printfilm-team-schema", "jit": "off",+ "statement_timeout": "45000", "idle_in_transaction_session_timeout": "45000",+ }})+ engine.dispose.assert_awaited_once()+++async def test_cli_timeout_cancels_step_before_disposing_engine(monkeypatch):+ """超时会取消在途建表协程,再释放专属连接,避免留下客户端孤儿。"""+ from app import config+ from sqlalchemy.ext import asyncio as sqlalchemy_asyncio++ engine, _, _ = stub_engine()+ cancelled = []+ wait_for = asyncio.wait_for++ async def blocked(*, engine_override):+ """模拟等待数据库响应,在取消时记录 finally 已执行。"""+ try:+ await asyncio.Event().wait()+ finally:+ cancelled.append(engine_override)++ async def expire(awaitable, timeout):+ """缩短测试等待,但断言 CLI 生产配置仍为六十秒。"""+ assert timeout == 60+ return await wait_for(awaitable, timeout=0.01)++ monkeypatch.setattr(config, "get_settings", lambda: SimpleNamespace(database_url="postgresql+asyncpg://test.invalid/schema_test"))+ monkeypatch.setattr(sqlalchemy_asyncio, "create_async_engine", Mock(return_value=engine))+ monkeypatch.setattr(database, "init_db", blocked)+ monkeypatch.setattr(cli.asyncio, "wait_for", expire)+ patches = AsyncMock()+ monkeypatch.setattr(main, "_apply_schema_patches", patches)+ with pytest.raises(TimeoutError):+ await cli.prepare()+ assert cancelled == [engine]+ patches.assert_not_awaited()+ engine.dispose.assert_awaited_once()diff --cc docs/MARKETPLACE.mdindex 0000000,8ef98c4..15f73b6mode 000000,100644..100644--- a/docs/MARKETPLACE.md+++ b/docs/MARKETPLACE.md@@@ -1,0 -1,215 +1,216 @@@+ ## 当前实现规范:作品广场(单视频与短剧)+ 平台投放(2026-10-23)++ 本节是当前产品和接口的准则,优先于本文后面的历史记录。市场保留原有单视频作品,新增独立的短剧系列与分集模型;历史作品不会自动迁移。单视频和每个分集都使用不可变发布版本,修改视频、权属材料、收费类型或价格后必须重新提交审核。作品内容与版权信息在同一次管理员审核中完成,不要求用户先做“版权审核”再做“内容审核”。++ 收费类型只有三种:++ - `free`:审核通过并上架后播放完整时长烧录水印,不公开无水印原片。免费不代表可以任意商用,也不承诺防录屏。+ - `copyright_contact`:参考价大于 0 时只展示最多 15 秒且不超过原片 30% 的原分辨率烧录水印试看;参考价为 0 时按免费处理,播放完整时长水印。购买版权通过真实客服线下协商。+ - `platform_unlock`:单视频或单集单独配置解锁价;未购买看试看,支付成功后永久在线播放,不返回原片地址。++ 平台投放作品必须先由后台配置默认创作者分成比例;作品或分集可以覆盖该比例。没有默认比例时只能保存草稿,提交审核返回 `MARKETPLACE_REVENUE_CONFIG_REQUIRED`。订单、永久权益、收益账本和人工打款使用独立 `marketplace_` 表,不复用原 AI 钱包或订单,不提供退款和自动提现。支付配置缺失返回 `MARKETPLACE_PAYMENT_UNAVAILABLE`。++ 短剧和单视频一起出现在作品广场。作者可以删除自己的作品,删除是软删:记录、文件和审核历史保留,作品从我的作品和作品广场撤下,不能再上架。发布入口有「发布作品」,也可以从 PrintFilm 成片页进入「发布到数字资产市场」。科普成片和明确选中的漫剧分集只提交编号,由市场 Worker 复制到 `marketplace/`;同一成片版本重复点击不会生成第二份草稿,原项目重新生成后用新版本再发布。草稿可以先保存,提交审核前仍要签署账号授权函,管理员一次审核内容和版权,通过后由作者上架。水印不在复制时生成。++ 版权材料按来源简化:PrintFilm 生成只需关联当前有效的签署授权函;其他平台需要证书编号、证书截图/照片和“版权纠纷与平台无关”确认;没有材料时只能联系客服协办,不创建新的登记案件,也不会自动通过。客服购买版权和招募接单均使用后台维护的真实二维码,不使用虚假或社区微信。++ 同一个市场 Worker 负责成片复制、上传后媒体校验、水印播放文件和平台 HLS 播放版本,数据库持久化任务、租约和重试,随 API 自动启动并由看门狗恢复;不修改原项目 Worker、AI 调度、计费、漫剧表或存储目录。免费和零元作品生成完整时长水印,有标价的版权作品只生成短试看,平台投放审核通过后才生成同源分辨率 HLS。共用 OSS 但固定使用 `marketplace/` 前缀,OSS 未配置时上传和依赖媒体的接口返回 503 `MARKETPLACE_STORAGE_UNAVAILABLE`,不回退本地文件。已经上架但没有水印的免费内容会在服务启动时下架并排队生成水印。++ 当前已完成:用户端系列创建/编辑/导入/提交、系列和分集浏览,单视频三种收费类型,管理员系列审核、分成配置、订单/权益查询(支持购买用户和创作者筛选)、收益账本、人工打款和分类配置,市场 Worker 试看/HLS 任务,以及短时签名播放权限。当前仍需真实环境验收:共用 OSS 的分片上传、私有对象与分片签名、FFmpeg/HLS 播放、易支付回调和 App 播放端;本地未配置真实服务时这些接口只能验证错误码和权限边界。++ 核心接口:系列使用 /api/marketplace/series、/series/{id}/episodes、/series/{id}/episodes/import 和 /series/{id}/submit;平台内容使用 /platform/feed、/platform/episodes/{id}、/platform/works/{id} 及对应 /playback;订单使用 /content-orders、/entitlements 和 /payments/epay/notify。播放接口只返回短时签名清单或原片链接,详情接口不会泄露 OSS 密钥。当前不提供 Web 观众端支付/播放页面,App 应按接口接入。+ ## 当前招募规则:联系客服接单(2026-10-21)++ 招募只提供需求展示与客服撮合:需求方保存草稿 → 提交管理员审核 → 招募广场展示;创作者查看需求 → 登录 → 联系客服接单 → 客服线下协调预算、授权、合同与交付。接单咨询不需要上传视频、报价表单或版权材料,咨询不代表已接单或成交。++ 详情保留需求说明、预算、数量、交付要求、授权意向、截止时间及最多6张参考图;作者从“我的发布”进入管理。用户端取消“我的投稿”、视频投稿、审片和选稿入口。后台日常只保留招募审核,旧记录移到“运行维护 → 历史投稿记录”,不删除已有数据。++ 新投稿及选稿接口已停用:`POST /api/marketplace/recruits/{id}/submissions`、`POST /api/marketplace/submissions/{id}/selection` 对已登录调用返回410,`detail.code=MARKETPLACE_SUBMISSIONS_DISABLED`,不修改资产、不创建投稿和审片任务;接口文档不再展示这两个旧入口。详情的旧字段 `can_submit` 固定为false,`can_contact` 表示当前登录创作者可联系开放需求。旧记录读取、撤回和私密文件权限保留兼容,不恢复线上投稿流程。++ 客服沿用“数字资产平台运营 → 客服配置”中的真实二维码、微信及服务时间,弹窗提供招募编号、标题、预算、当前链接的一键复制。无客服配置返回503;关闭、到期、未审核或封禁需求不接受创作者新咨询。本文下方的历史投稿、审片、选稿说明均以本节为准。++ 只需重启后端并刷新前端页面,无数据库迁移或历史数据清理。不影响作品发布、作品试看和原项目业务。++ ## 当前作品试看规则(2026-10-21)++ 本节替代下文历史版本中关于普通作品转码、免费价格、预览时长及双重审核的说明。市场 Worker 现随后端自动启停,异常退出自动恢复,不需另开终端。++ - 发布方式可选择免费(价格为0)或付费。上传、保存草稿不创建水印任务。免费公开播放完整时长水印,不提供无水印原片,也不代表任意商用。+ - 提交作品时一次校验版权信息:PrintFilm 仅关联已签署授权函;其他平台填写证书编号、上传截图/照片并确认版权声明;无材料直接联系客服线下协办,不在作品流程创建登记案件。+ - 提交审核后进入 `processing`,Worker 生成保留原分辨率、原帧率的高保真烧录水印(H.264 CRF16,不保证逐像素无损;奇数尺寸仅补齐偶数)。免费和零元作品为完整时长;有标价的版权作品时长不超过 `min(15秒, 原片时长*30%)`,编码为封装取整预留少量余量。公众播放不回退无水印原片。+ - 水印包含 PRINTFILM、作者名字和「侵权必究」,上下两处烧入画面。不会为普通作品额外生成完整审片或封面;封面由用户上传。+ - 生成成功自动进入 `pending`;管理员查看原片、公众试看及版权材料,一次审核,作者再上架。失败最多自动尝试配置次数,终止后显示 `preview_failed`,作者可点击重试生成并提交。+ - 新增独立表 `marketplace_work_previews`;启动 API/Worker 时通过现有独立 metadata 创建新表,不修改原业务表或现有列。按作品和原片去重,同片修改标题/价格金额复用试看;替换视频创建新任务。结果更新须符合当前作品版本、媒体、付费及提交状态。+ - Worker 单进程串行执行,作品试看使用120秒租约、20秒心跳,进程重启可恢复。每次尝试使用独立 OSS 对象,过期任务不能覆盖新结果。不得启动多个 Worker 来追求并发;当前建议保持一个。+ - 公开媒体接口对付费作品只签发独立试看对象,缺失或失败时拒绝播放,不回退原片和旧版 `Asset.preview_key`。免费转付费先撤下、生成试看并重新审核;已签发原片链接仍最多存活5分钟,已被保存的原片无法收回。+ - 旧版已上架付费作品没有该试看记录时,从公开列表及公开播放中排除。作者需从“我的发布 → 查看与管理”重新提交,生成试看、审核通过后再上架;不自动处理历史文件、不替作者重新上架。+ - 后台“运行维护 → 作品试看任务”查看任务;作品记录可分别打开原片与公众试看。任务数据不包含公开原片下载接口。++ 部署本次更新只需重启后端(前端开发服务刷新即可)。后端自动启动市场 Worker 及其看门狗,停止或热重载时先取消媒体任务;异常退出后约2秒自动拉起。无OSS配置时空闲等待,不影响原项目。原AI调度器不变。以下手动命令仅保留兼容,不是日常启动步骤:++ ```powershell+ cd C:\code\printfilm\backend+ .\.venv\Scripts\python.exe -m app.marketplace.worker+ ```++ 测试:52项下游测试通过,涵盖免费/付费、无OSS、原片权限、重复提交、失败重试、替换视频、租约恢复和版本冲突。真实 FFmpeg 配合 OSS 传输替身验证了10秒原片生成不超过3秒、60秒原片生成不超过15秒的可见水印视频。两端构建通过;这些不代表真实 OSS 上传/播放联调已通过。++ ---+ # 下游作品与招募模块++ ## 边界与入口++ 新增模块位于 `backend/app/marketplace`、`frontend/src/features/marketplace`、`admin/src/features/marketplace`。原项目只增加 FastAPI 模块挂载、页面路由和条件菜单,不修改原作品表、生成、计费、任务调度、存储函数或旧接口。ReelBay 只作参考,未修改。++ 用户端顶部和手机导航统一使用“数字资产市场”一个入口,进入后通过模块内导航访问作品广场、招募广场、发布作品、发布招募及个人业务进度。++ 界面沿用主站的浅灰背景、白色圆角卡片、黑色文字与荧光绿主操作,复用全局颜色变量和 `Button`。广场提供页头、选中态导航、搜索/分类/价格筛选、作品卡片及真实空态;发布页按文件、介绍、授权分组,配合流程指引;工作台突出状态和记录。样式均限定在市场模块内,桌面和手机使用同一套功能。展示卡片只读取真实接口数据,不内置示例作品或虚构统计。++ - 用户端 `/marketplace`:作品广场。+ - 用户端 `/marketplace/recruits`:招募广场。+ - 用户端 `/marketplace/mine`:我的作品、招募、文件、版权信息及站内通知;接单通过招募详情联系客服。+ - 管理端 `/marketplace`:下游审核、登记、投诉、任务与客服配置,区别于原 `/works`。+ - API `/api/marketplace/*`、`/api/admin/marketplace/*`。++ 模块默认关闭。路由始终挂载,关闭时业务接口返回未启用,菜单隐藏,不建新表,不启动 Worker。`GET /api/marketplace/capabilities` 始终可用,只返回开关与配置完整性,**不代表真实 OSS 已验收**。线上在管理端「系统设置 → 站点工具」打开「启用数字资产市场」并保存,写入 `app_settings`,不必准备 `backend/.env`,也不必为了出现菜单而重启。库里保存过该开关后以数据库为准。++ 下游使用独立 SQLAlchemy metadata,启动时创建 `marketplace_` 表,不修改或迁移原表。用户 ID 复用现有身份。PrintFilm 成片可以按项目或分集编号异步复制进市场;没有走这条路径的作品仍由用户自行上传。复制完成后的草稿不自动过审。++ ## 本地启动与功能开关++ 当前本机没有配置真实 OSS,也没有填写虚假凭证。OSS 在现有后台统一配置;后台保存或清除凭证后 API 自动生效,内嵌 Worker 读取现有后台配置缓存,兼容独立命令每轮同步配置。配置示例见 `backend/.env.marketplace.example`。配置可放入部署环境变量,或将需要的 `MARKETPLACE_` 配置项加入后端 `.env`,不要覆盖整份原环境文件。++ 仅查看页面和文字草稿,可以在**启动后端的同一 PowerShell 终端**执行:++ ```powershell+ $env:MARKETPLACE_ENABLED = 'true'+ cd C:\code\printfilm\backend+ .\.venv\Scripts\python.exe -m uvicorn app.main:app --host 127.0.0.1 --port 8000+ ```++ 先停止原先占用8000端口的后端。前端及管理端仍按项目原命令启动,刷新后会显示新菜单。若使用 VS Code F5,可在调试终端的环境或本地 `.env` 设置开关,重启后端。代码默认值仍为 false。已在系统设置里保存过开关时,以数据库中的值为准,改 `.env` 不会盖过它。++ 无 OSS 时支持文字作品草稿和无附件需求的创建、修改、内容审核、招募公开浏览。上传、材料、媒体签名返回503,`detail.code=MARKETPLACE_STORAGE_UNAVAILABLE`,不会回退本地存储、返回 `/static`,也不会产生假就绪视频。++ 停用时在「系统设置 → 站点工具」关闭开关并保存,或在尚未写入数据库前把 `MARKETPLACE_ENABLED=false` 后重启。Worker 会停止。停用不会删除已经存在的新表或 OSS 对象。++ ## 共用 OSS、独立目录与媒体进程++ 下游直接读取后台「系统设置 → 存储 OSS」的启用状态、Endpoint、Bucket 和凭证,与原业务共用 Bucket。固定使用 `marketplace/` 目录,原业务继续使用原 `OSS_FOLDER`(默认 `kepu/`),请勿将原业务目录设置为 `marketplace/`。无需配置 `MARKETPLACE_OSS_*`,旧的同名环境变量不再生效。所有原片、封面、水印预览、版权材料、参考图、客服二维码使用 OSS 对象标识。模块不创建 Bucket,不改 ACL、CORS、生命周期及上游配置。++ 客户端会只读检查 Bucket ACL 和 policy,公开 ACL 或匿名 Allow 策略将阻止市场文件使用。目录不是权限边界:共用 Bucket 仍须保持私有,原业务已通过对象 ACL 显式公开的文件继续遵循原上传逻辑;下游始终显式上传为 private,不调用原公开上传函数、不使用公开域名。不会自动改动现有云端权限,实际兼容性待真实 OSS 联调。RAM 权限需要包括共用 Bucket 的 GetBucketAcl/GetBucketPolicy,以及 `marketplace/*` 下文件读取、上传、multipart 初始化/分片/完成/取消权限。没有 Bucket policy 时允许 `NoSuchBucketPolicy`;元数据检查权限不足时失败关闭。部署方需配置文件保留、备份、日志及未完成 multipart 的兜底生命周期。++ 浏览器播放器通过已鉴权的接口取得短时 GET 链接,不接收 OSS 密钥。默认有效期300秒;下架、撤回后不再签发新链接,旧链接最长5分钟后过期。播放、Range 和二维码图片访问应在真实 Bucket 上验收。原片和证据仅作者或管理员可申请访问,需求方只能获得水印审片。++ 市场 Worker 已随后端自动启动,不需另开终端。仅在确需独立运行时使用兼容命令:++ ```powershell+ cd C:\code\printfilm\backend+ .\.venv\Scripts\python.exe -m app.marketplace.worker+ ```++ Worker 随 API 自动启动和停止,由市场独立看门狗恢复,不接入原 TaskRun、AI 计费或原调度器。通过 PostgreSQL 事务级咨询锁保证多个后端进程或兼容命令之间总媒体并发为1。默认单并发,任务持久化、SKIP LOCKED领取、90秒租约和20秒心跳;最多自动尝试3次,失败可通过作者工作台重试。多进程使用同一租约规则,首版建议只部署一个 Worker。生产需用进程管理器托管并监控失败任务。++ 视频默认最大500MB、最长30分钟,支持MP4/MOV/WebM。8MB分片转发到OSS,会话24小时,重复同一分片和重复完成保持幂等。重新选择同一文件可以恢复已成功的分片,上传中可取消;取消未获云端确认时显示错误并保留恢复信息。完成后校验OSS真实大小,Worker校验文件内容、指纹和媒体信息。++ FFmpeg 在系统临时目录的 `printfilm-marketplace-cache/job-*` 内处理付费试看和平台投放 HLS。版权咨询试看最多 15 秒且不超过原片 30%,保持源分辨率和帧率并烧录水印;平台投放播放版本保持源分辨率,优先无重编码分段。免费作品不生成试看或默认封面,封面由作者上传。临时文件只作缓存,上传到私有 OSS 成功后才标记就绪,任务结束和超时清理。++ ## 业务操作顺序++ ### 单视频与短剧++ 1. 作者上传单视频或创建短剧系列,保存草稿只保存资料,不要求授权材料,也不创建试看任务。+ 2. 单视频提交审核时选择免费、联系客服购买版权或平台投放收益;短剧逐集填写收费类型、价格和权属信息。平台投放还必须已有后台默认分成或单项分成。+ 3. PrintFilm 生成只关联当前有效授权函;其他平台填写证书编号、证书截图/照片并勾选版权纠纷声明;没有材料只能联系客服协办,不创建新登记案件。+ 4. 后端校验媒体、封面、权属和收费信息后,付费内容由同一个市场 Worker 生成试看;管理员在一个审核入口同时检查内容与版权,结果只有待审核、已通过或已驳回。+ 5. 审核通过且版本就绪后作者上架。修改视频、权属、收费类型或价格会创建新版本并重新审核;已购买旧版本继续使用旧播放资产。++ 单视频保留一条视频一张封面;短剧系列要求至少一集、集数连续且每集视频/封面/材料/试看就绪。分集可以手动上传,也可以明确选择本人漫剧项目中已生成的分集导入,导入复制并保存来源快照,不修改原漫剧。++ ### 权属与客服协办++ 作品和版权信息只提交一次、管理员只审核一次。不要向用户展示基础核验、完整核验、私密核验或自行办理登记案件。授权函或证书材料修改会使当前版本重新进入待审核;证书编号本身不代表平台保证无侵权。客服协办不自动通过,服务费或登记机构费用按线下通知处理。+ ### 招募与客服接单++ 需求保存草稿、提交审核,通过后公开;最多6张参考图。创作者浏览需求后先联系平台客服,由客服协调合作,不在线上传视频、报价或选稿。++ 联系客服时提供业务编号、标题、预算和页面链接;具体价格、版权约定、合同及交付在线下确认。未配置真实客服时明确提示不可用,关闭或到期后停止创作者新接单咨询。++ 历史投稿不删除,原私密权限继续生效;曾有投稿的旧需求继续锁定预算、数量、授权、规格、说明和截止条件,重大变更关闭后重新发布。新需求不创建投稿记录。++ ### 客服、投诉与原片交付++ 管理员上传真实二维码、等媒体处理后保存客服配置。没有真实配置时显示不可用,不使用社区微信代替。不创建订单、支付、在线买家下载或授权凭证;客服线下确认合同、收款、原片交付。咨询事件仅用于统计,不能视为扫码或成交证明。++ 举报需要说明和联系方式,可在页面附带本人证明文件。管理员查看证据后可限制作品、需求、权属或投稿,再记录处理结论并通知用户。举报不自动永久封号。投诉人联系方式、证据不公开。敏感材料的读取和审核保留访问记录。下游页面隐藏原站社区入群浮标,业务咨询只使用后台维护的专用客服。++ ## 验收与发布边界++ ```powershell+ cd C:\code\printfilm\backend+ .\.venv\Scripts\python.exe -m pytest tests/test_marketplace.py -q+ ```++ 集成测试复用仓库的隔离测试库与事务回滚机制,OSS传输使用测试替身;测试不存在的材料不进入用户业务环境。FFmpeg 测试覆盖付费试看约束和同源分辨率播放版本,但不是云端验收。++ 本地检查覆盖关闭开关、无OSS错误、草稿、身份权限、一次内容与权属审核、系列分集连续性和漫剧导入边界、平台分成缺失、订单权益幂等、旧版本冲突、私密试看、到期与撤回、举报限制、分片边界与幂等、媒体租约恢复。两端应运行 `npm.cmd run build`。++ 已有市场测试覆盖单视频试看、无OSS、权限、重复提交、失败重试、替换视频、租约恢复和版本冲突;系列、平台订单/权益/账本及分成边界应继续补充接口级回归。两个前端构建及市场目录静态检查通过时,仍需使用可用 Python 环境重跑后端测试。独立浏览器使用仅测试会话内的接口替身,不写入业务数据;测试替身不构成真实上传或云端播放验收。++ 数据库备份需使用整个业务库的 `pg_dump`,不要沿用仅导出原表的白名单;确认备份包含全部 `marketplace_` 表并演练恢复。下游OSS对象、版本和保留策略需单独纳入备份方案,数据库备份不包含OSS文件;本地尚无真实Bucket,因此未设置任何云端策略。首次启用会创建独立表,后续模型变化应为下游单独提供DDL迁移,`create_all`不会修改已有表结构。++ 正式启用前仍须在真实共用OSS环境验收:RAM和Bucket权限、真实分片续传、断线和重启恢复、私有文件无法匿名读取、签名到期/Range播放、水印视频与材料上传、部署字体、进程守护、数据库/OSS备份和投诉流程。**本机未配置OSS,不把这些项目记为通过,也不声称可以立即上线。**+++ ## 来源分流与上传预览补充(2026-10-20)++ - 授权签署入口:`/marketplace/authorization`,个人工作台与发布作品页均有入口,权属页内也可直接签署。+ - 独立依赖安装:在 backend 目录执行 `.\.venv\Scripts\python.exe -m pip install -r requirements-marketplace.txt`。授权函直接生成 PDF,并把仓库内置的 Noto Sans SC 嵌进文件,服务器和下载方都不必另装字体。若 `MARKETPLACE_WATERMARK_FONT` 指向一个真实存在的文件,则仍优先使用该字体。水印预览使用同一套查找。+ - `marketplace_authorizations` 是新增独立表,启用模块启动时创建。签署存储全文、版本、SHA-256 摘要、姓名、时间、账号及必要访问信息;签名与完整授权函 PNG 存到私有 OSS 的 `marketplace/authorizations/`。全文与签名由服务端合成,不信任客户端合成的协议图片。未写入 OSS 不返回签署成功。+ - 授权函按账号与版本唯一,逐件权属档案只能由服务端关联本人的签署记录。重新保存材料会重置核验,模板更新须重签及重新关联。只有本人和管理员能获取短时授权函链接。+ - 协议采用数字资产市场当前范围:非独家展示、处理和客服撮合;没有自动转让、线上付款、分成或买家下载授权。ReelBay 仅参考流程,不复制它的支付或商业分成条款。+ - 选择文件后支持本地视频、图片和 PDF 预览,明确标注不代表上传成功;切换文件或离开组件释放对象 URL。上传失败仍可查看所选本地文件。已有文件、我的文件及证明材料通过本人鉴权链接预览;处理未完成显示状态,链接过期可刷新。浏览器不支持 MOV 编码时提示等待处理后的 MP4 预览。+ - 修复作者的未上架草稿预览权限:允许本人查看水印预览,其他用户和访客仍不可访问。+ - 本轮验证包括中文授权函真实渲染、完整签署/核验/上架流程、外部证明、无证明协办、越权与未就绪文件限制;浏览器通过手写签名、图片/PDF 本地预览、上传失败和 390px 手机布局检查。云端传输采用测试替身,本轮没有执行真实 OSS 签署上传、视频转码或播放验收。++++ ### Windows 媒体命令兼容修复(2026-10-21)++ 后台覆盖配置可能把 FFmpeg 路径设为默认命令 `ffmpeg` / `ffprobe`,但程序不在 PATH。下游执行器在此情况下读取环境配置中的实际安装路径;显式自定义路径不被替换。Windows 的 Uvicorn 热重载使用 Selector 事件循环时,执行器改用可取消、有超时并负责回收子进程的线程方式,不修改原项目事件循环。`NoSuchBucketPolicy` 表示不存在额外 Bucket policy,现有私有 ACL 校验允许该情况,不是试看任务失败的原因。++ 本轮59项市场与运行时测试通过,并对当前失败作品执行实际转码和私有 OSS 上传重试,任务完成、作品恢复待审核;没有自动通过审核或上架。+++ ### 试看保真调整(2026-10-21)++ 付费作品试看取消720p缩放和固定30帧,保留源画面尺寸和帧时间,改用H.264 CRF16高保真编码与192kbps音频。仅奇数画幅补至偶数以兼容yuv420p,不拉伸或缩小。烧录水印必须重新编码,不能宣称逐像素无损;HDR、色深与色彩管理不在本轮保真验收范围。时长仍不超过15秒/原片30%。新版对象位于 marketplace/work-previews-hq/,旧低清对象不能作为新版任务的就绪结果复用。++ 59项测试通过,真实测试确认1920x1080、24fps素材生成后尺寸与帧率保持不变。当前作品的旧试看已在原片与内容版本未变的前提下替换为高保真对象,保留审核及上架状态;原片未改动。++ ### 管理员配置作品分类与版权购买提示(2026-10-21)++ 后台「业务 → 数字资产平台运营 → 作品分类」配置分类名称,一行一个,按行排序。配置持久化到独立表 marketplace_category_config,初始配置为短片、广告、动画、文旅、科普、其他。新表随后端启动自动创建;管理员保存采用版本校验及事务锁,防止并发覆盖。公开接口 GET /api/marketplace/categories,管理接口 GET/PUT /api/admin/marketplace/categories。发布作品采用下拉选择、广场分类标签读取同一配置,服务端拒绝任意新分类;移除分类不改历史作品,历史编辑可保留原分类。++ 用户页面将“授权参考价”统一改为“参考价”。作品/投稿购买咨询弹窗增加版权购买须知:使用授权不等同于版权转让,购买著作财产权须签订书面转让合同并按约定办理相关手续,可能产生办理、登记或服务等费用,页面参考价不默认包含这些费用,费用及承担方须先与客服确认。本次不新增支付、订单、自动授权或版权转让接口。++ ### 招募公开详情与作者管理分离(2026-10-21)++ 招募广场 /marketplace/recruits/:id 始终显示招募内容与联系客服接单入口,不因当前账号是作者/管理员而切换管理界面;编辑、提交审核及关闭在 /marketplace/recruits/:id/manage 展示,由“我的发布 → 查看与管理”或保存招募草稿后进入。本人看到管理招募链接,创作者登录后联系客服;关闭/到期停止新接单咨询。详情不请求私密投稿列表,不提供视频投稿和独立公开评论系统。++ ### 漫剧完整分集直接发布(2026-10-24)++ 漫剧列表卡片菜单「发布到数字资产市场」、分集编辑页和市场编辑页使用同一个发布弹窗。选择当前项目的完整分集,新建或选择本人市场系列后同步并进入 `/marketplace/series/{id}/edit`。新系列带入项目名称和简介;已有系列保留介绍、封面及收费配置,按原集数排序后从下一集接续编号。没有可用封面时需补充上传。++ - `GET /api/marketplace/printfilm/dramas/{project_id}/publish-context`:完整度、不可发布原因、源版本、本人目标系列和既有同步关系,不返回来源地址或对象键。+ - `POST /api/marketplace/printfilm/dramas/{project_id}/publish`:提交选中编号、源版本、新建/已有目标、明确确认的更新及幂等键。独立 `marketplace_drama_publish_batches` 记录原子批次;同一账号的同一幂等键不能创建第二个系列。旧的分集导入 URL 也使用相同的整集逻辑。+ - 原漫剧仅供读取。缺失任一分镜、视频生成或重新分镜尚未结束、跨账号选择均阻止发布。按 `(sort_order,id)` 冻结完整分镜清单、源文件指纹/ETag、标题、封面及源集号;不再把最后一个分镜当整集。++- 团队漫剧来源仍限原创建者导入,并在每次请求实时校验团队成员资格;已离队的旧创建者无法导入,也不会在来源列表中看到该项目。+ - 使用原有市场 Worker 及看门狗,不增加进程。阶段为排队、同步素材、拼接整集、校验、就绪/失败;兼容编码优先无损封装,不兼容时按最高来源画幅使用高质量编码,比例不一致直接阻断。非公开临时目录只作缓存,视频写入私有 OSS `marketplace/series/` 并校验后才绑定。+ - 同步期间可以填写表单,保存与提交暂时禁用;失败提供原因和重试,源变化或目标冲突要求重新选择并确认。租约丢失会取消处理;过期租约由同一个 Worker 恢复。源或目标已变化的旧任务不能回填新结果,未成功前保留旧资产。+ - PrintFilm 分集统一引用账号当前有效授权函,可先同步及保存草稿,再签署一次并提交。自动关联只表示材料齐备;内容和版权仍由管理员一起审核,不自动批准。+ - 明确更新使系列退回草稿并关闭所有历史发布版本的新销售;旧发布快照、HLS、价格及永久权益保留。已有买家通过 `GET /api/marketplace/platform/publications/{publication_id}/playback` 播放购买时版本,每次仍鉴权并检查封禁/权属限制。在途有效付款回调按冻结版本与金额确认,不因作者编辑或下架丢失权益。分成在提交时按单集、系列、后台默认优先顺序冻结。++ 新增独立表随启用后的后端启动创建,不修改 `drama_*` 或原生成、下载、AI 计费任务。部署更新后需重启后端以加载接口和创建该表。没有真实 OSS 配置时发布返回 `503 MARKETPLACE_STORAGE_UNAVAILABLE`,不创建空系列,不提供本地媒体回退。++ 专项回归文件:`tests/test_marketplace_drama_publish.py`、`tests/test_marketplace_drama_media.py`、`tests/test_marketplace_publication_access.py`,覆盖整集顺序和时长、权限、状态、防重、版本回填、租约恢复、旧权益和付款幂等。媒体测试使用真实 FFmpeg、OSS 使用传输测试替身;仍须在真实 OSS 环境单独验证复制、合成上传、私有播放及部署重启,不能将替身结果视为云端验收通过。diff --cc docs/PLACEHOLDER_BACKLOG.mdindex e33dae4,6a8d186..e641dba--- a/docs/PLACEHOLDER_BACKLOG.md+++ b/docs/PLACEHOLDER_BACKLOG.md@@@ -8,11 -8,11 +8,13 @@@## 1. 文档与代码入口一览+ 2026-10-23:数字资产市场已扩展为单视频 + 短剧剧集 + 平台投放收益。系列/分集管理、一次内容与权属审核、订单/永久权益/收益账本/人工打款接口及市场 Worker 已接入;招募继续仅做客服撮合。真实私有 OSS、易支付回调和 App 播放端仍待配置后验收。该模块不替换原创作与历史作品入口,参见 [MARKETPLACE.md](./MARKETPLACE.md)。+| 区域 | 主要文件 ||------|----------|-| 顶栏 | `frontend/src/components/layout/SiteNav.tsx` |+| 左侧主导航 / 窄屏抽屉 | `frontend/src/components/layout/SiteNav.tsx`、`AppShell.tsx` |+| 漫剧 / 自由画布列表 | `frontend/src/pages/drama/DramaListPage.tsx`、`CanvasListPage.tsx` |+| 共享项目卡片 / 新建弹窗 | `frontend/src/components/projects/ProjectCard.tsx`、`ProjectCreateDialog.tsx`、`frontend/src/lib/projectCreateForm.ts` || 帮助抽屉 | `frontend/src/components/ui/HelpCenter.tsx`、`Modal.tsx`(`variant=drawer`) || 新建 | `frontend/src/pages/studio/CreateProjectPage.tsx` || 风格 | `frontend/src/pages/studio/StyleConfigPage.tsx` |diff --cc frontend/src/App.tsxindex 2ff5f81,1932829..6f5e4d1--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@@ -1,5 -1,5 +1,5 @@@-import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'-import { lazy, Suspense } from 'react'+import { BrowserRouter, Navigate, Route, Routes, useLocation } from 'react-router-dom'- import { useLayoutEffect, useSyncExternalStore } from 'react'++import { lazy, Suspense, useLayoutEffect, useSyncExternalStore } from 'react'import DialogHost from './components/ui/DialogHost'import BillingAlertHost from './components/billing/BillingAlertHost'import { DramaGenQueuePanel } from './components/drama/DramaGenQueuePanel'@@@ -40,20 -31,14 +40,23 @@@ import { TeamPreviewProvider } from './import './styles/printfilm.css'import './App.css'-// 下游页面按需加载,不将媒体业务接入原工作台。+ const Marketplace = lazy(() => import('./features/marketplace/Marketplace'))++/** 生成队列支持个人和团队空间,余额引导仅在个人业务空间展示。 */+function PersonalBusinessOverlays() {+ const { pathname } = useLocation()+ const teamId = useSyncExternalStore(subscribeWorkspace, () => workspaceScope.teamId)+ useLayoutEffect(() => { if (!/^\/teams\/\d+/.test(pathname) && !/^\/drama\/projects\/\d+/.test(pathname)) setWorkspaceTeam(null) }, [pathname])+ const personal = teamId === null && pathname !== '/teams' && !pathname.startsWith('/teams/') && pathname !== '/team-invitations'+ return <><DramaGenQueuePanel />{personal && <BillingAlertHost />}</>+}++/** 用户端路由及全局交互宿主,团队界面使用真实认证服务。 */export default function App() {return (- <BrowserRouter>+ <TeamPreviewProvider><BrowserRouter><Routes>+ <Route path="/marketplace/*" element={<Suspense fallback={<p>正在加载作品与招募…</p>}><Marketplace /></Suspense>} /><Route path="/" element={<HomePage />} /><Route path="/method" element={<MethodPage />} /><Route path="/auth" element={<AuthPage />} />diff --cc frontend/src/components/layout/SiteNav.tsxindex 12f0df2,b89fbfe..63b2328--- a/frontend/src/components/layout/SiteNav.tsx+++ b/frontend/src/components/layout/SiteNav.tsx@@@ -1,46 -1,45 +1,48 @@@-import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom'-import { useEffect, useState } from 'react'+import { Link, useLocation, useNavigate } from 'react-router-dom'+import { useEffect, useRef, useState } from 'react'+import {+ ArrowUpRight, ChevronRight, CircleHelp, Clapperboard, CreditCard,- Image, Images, LayoutDashboard, ListTodo, Menu, Plus, Settings2, UserRound, UsersRound,++ Image, Images, LayoutDashboard, ListTodo, Menu, Plus, Settings2, Store, UserRound, UsersRound,+ Video, WandSparkles, Workflow, X,+} from 'lucide-react'import { api } from '../../api'import type { User } from '../../api'import UserAvatar from '../UserAvatar'import BrandMark from '../BrandMark'-import { IconGithub, IconHelp } from '../ui/Icons'-import Button from '../ui/Button'+import { IconGithub } from '../ui/Icons'import CreateChoiceModal from '../ui/CreateChoiceModal'import { USER_UPDATED_EVENT } from '../../lib/userEvents'+import { loadSessionUser } from '../../lib/sessionUser'import { GITHUB_REPO_URL } from '../../lib/siteLinks'+import { CREATION_NAV, RESOURCE_NAV, resolveNavActive, type NavActive } from '../../lib/siteNavigation'import { useI18n } from '../../i18n'import LanguageSwitch from './LanguageSwitch'+import WorkspaceSwitcher from '../../features/teams/WorkspaceSwitcher'+import { useTeamPreview } from '../../features/teams/useTeamPreview'+ import { useMarketplace } from '../../features/marketplace/hooks'-export type NavActive = 'home' | 'drama' | 'kepu' | 'tools' | 'assets' | 'pricing' | 'templates' | 'studio' | 'history'+export type { NavActive } from '../../lib/siteNavigation'-type Props = {- active?: NavActive-}+type Props = { active?: NavActive }+type NavItem = (typeof CREATION_NAV)[number] | (typeof RESOURCE_NAV)[number]-// 将旧 active 别名归一到新 IA-function normalizeActive(active: NavActive | undefined, pathname: string): NavActive | undefined {- if (active === 'studio' || active === 'templates' || active === 'history') return 'kepu'- if (active) return active- if (pathname.startsWith('/drama/assets') || pathname.startsWith('/assets')) return 'assets'- if (pathname.startsWith('/drama')) return 'drama'- if (- pathname.startsWith('/studio') ||- pathname.startsWith('/templates') ||- pathname.startsWith('/history')- ) {- return 'kepu'- }- if (pathname.startsWith('/tools')) return 'tools'- if (pathname.startsWith('/pricing')) return 'pricing'- if (pathname === '/') return 'home'- return undefined+const NAV_ICONS = {+ home: LayoutDashboard,+ drama: Clapperboard,+ canvas: Workflow,+ kepu: Video,+ video: Video,+ image: Image,+ tools: WandSparkles,+ tasks: ListTodo,+ assets: Images,+ team: UsersRound,+ pricing: CreditCard,}+/** 应用主侧栏及窄屏导航抽屉,共用路由与会话状态。 */export default function SiteNav({ active }: Props) {+ const { capabilities: marketplace } = useMarketplace()const nav = useNavigate()const location = useLocation()const { t } = useI18n()@@@ -48,97 -51,29 +50,98 @@@const [user, setUser] = useState<User | null>(null)const [menuOpen, setMenuOpen] = useState(false)const [createOpen, setCreateOpen] = useState(false)-- const current = normalizeActive(active, location.pathname)-- useEffect(() => {- if (!localStorage.getItem('token')) return- api.me().then(setUser).catch(() => localStorage.removeItem('token'))- }, [])+ const sidebarRef = useRef<HTMLElement>(null)+ const menuButtonRef = useRef<HTMLButtonElement>(null)+ const closeButtonRef = useRef<HTMLButtonElement>(null)+ const current = resolveNavActive(location.pathname, active)++ const inMarketplace = location.pathname === '/marketplace' || location.pathname.startsWith('/marketplace/')+ const currentItem = [...CREATION_NAV, ...RESOURCE_NAV].find((item) => item.key === current)- const currentLabel = currentItem ? t(currentItem.label) : current === 'settings' ? t('nav.profile') : current === 'help' ? t('nav.help') : t('nav.workbench')++ const currentLabel = inMarketplace ? '数字资产市场' : currentItem ? t(currentItem.label) : current === 'settings' ? t('nav.profile') : current === 'help' ? t('nav.help') : t('nav.workbench')useEffect(() => {+ let active = true+ let generation = 0+ /** 只有当前请求的明确 401 可以清理会话,切空间导致的取消不会登出。 */+ function refreshUser() {+ const currentGeneration = ++generation+ if (!localStorage.getItem('token')) { setUser(null); return }+ void loadSessionUser({+ loadUser: () => api.me(),+ getToken: () => localStorage.getItem('token'),+ isCurrent: () => active && currentGeneration === generation,+ onUser: setUser,+ onUnauthorized: () => {+ localStorage.removeItem('token')+ setUser(null)+ window.dispatchEvent(new Event(USER_UPDATED_EVENT))+ },+ })+ }+ /** 用户事件先废弃旧请求,避免旧账号覆盖新登录或最新资料。 */const onUserUpdated = (event: Event) => {+ generation += 1const detail = (event as CustomEvent<User>).detail- if (detail) setUser(detail)+ if (detail && localStorage.getItem('token')) setUser(detail)+ else refreshUser()}window.addEventListener(USER_UPDATED_EVENT, onUserUpdated)- return () => window.removeEventListener(USER_UPDATED_EVENT, onUserUpdated)+ refreshUser()+ return () => { active = false; generation += 1; window.removeEventListener(USER_UPDATED_EVENT, onUserUpdated) }}, [])+ useEffect(() => { setMenuOpen(false) }, [location.pathname, location.search])+useEffect(() => {- setMenuOpen(false)- }, [location.pathname])+ const desktop = window.matchMedia('(min-width: 1001px)')+ function closeOnDesktop() { if (desktop.matches) setMenuOpen(false) }+ desktop.addEventListener('change', closeOnDesktop)+ return () => desktop.removeEventListener('change', closeOnDesktop)+ }, [])++ useEffect(() => {+ if (!menuOpen) return+ const previousOverflow = document.body.style.overflow+ document.body.style.overflow = 'hidden'+ // 等抽屉解除 visibility:hidden 后再移动焦点。+ const focusFrame = window.requestAnimationFrame(() => closeButtonRef.current?.focus())++ function keepFocusInside(event: KeyboardEvent) {+ // 独立弹窗接管自己的键盘事件;普通下拉仍归属当前抽屉。+ const modal = document.querySelector<HTMLElement>('[role="dialog"][aria-modal="true"]:not(#pf-app-sidebar)')+ if (modal && !sidebarRef.current?.contains(modal)) return+ if (event.key === 'Escape') {+ event.preventDefault()+ setMenuOpen(false)+ return+ }+ if (event.key !== 'Tab' || !sidebarRef.current) return+ const focusable = Array.from(sidebarRef.current.querySelectorAll<HTMLElement>(+ 'a[href], button:not(:disabled), summary, input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])',+ )).filter((element) => element.getClientRects().length > 0 && !element.closest('[inert]'))+ const first = focusable[0]+ const last = focusable[focusable.length - 1]+ if (!first || !last) { event.preventDefault(); return }+ const focused = document.activeElement+ if (!sidebarRef.current.contains(focused) || (event.shiftKey && focused === first)) {+ event.preventDefault()+ ;(event.shiftKey ? last : first).focus()+ } else if (!event.shiftKey && focused === last) {+ event.preventDefault()+ first.focus()+ }+ }++ document.addEventListener('keydown', keepFocusInside)+ return () => {+ window.cancelAnimationFrame(focusFrame)+ document.body.style.overflow = previousOverflow+ document.removeEventListener('keydown', keepFocusInside)+ menuButtonRef.current?.focus()+ }+ }, [menuOpen])- // 未登录去登录;已登录弹出漫剧/科普选择function goCreate() {+ setMenuOpen(false)if (!user && !localStorage.getItem('token')) {nav('/auth?next=/')return@@@ -146,59 -81,97 +149,65 @@@setCreateOpen(true)}- const isActive = (key: NavActive) => (current === key ? 'active' : undefined)-- const centerLinks = (- <>- {marketplace?.enabled && <NavLink to="/marketplace">数字资产市场</NavLink>}- <NavLink to="/" end className={() => isActive('home')}>- {t('nav.workbench')}- </NavLink>- <NavLink to="/drama" className={() => isActive('drama')}>- {t('nav.drama')}- </NavLink>- <NavLink to="/history" className={() => isActive('kepu')}>- {t('nav.kepu')}- </NavLink>- <NavLink to="/tools" className={() => isActive('tools')}>- {t('nav.tools')}- </NavLink>- <NavLink to="/assets" className={() => isActive('assets')}>- {t('nav.assets')}- </NavLink>- <NavLink to="/pricing" className={() => isActive('pricing')}>- {t('nav.pricing')}- </NavLink>- </>- )+ function renderLink(item: NavItem) {+ const Icon = NAV_ICONS[item.key]+ const selected = current === item.key+ return <Link+ key={item.key}+ to={item.path}+ className={`pf-sidebar-link${selected ? ' is-active' : ''}`}+ aria-current={selected ? 'page' : undefined}+ onClick={() => {+ if (item.key !== 'team' && item.key !== 'home') selectTeam(null)+ setMenuOpen(false)+ }}+ >+ <Icon size={19} strokeWidth={1.8} aria-hidden />+ <span>{t(item.label)}</span>+ {selected && <ChevronRight size={15} className="pf-sidebar-link-arrow" aria-hidden />}+ </Link>+ }- return (- <header className="pf-nav">- <div className="pf-nav-left">- <BrandMark />+ return <>+ <header className="pf-app-mobile-header">+ <button ref={menuButtonRef} type="button" className="pf-sidebar-icon-button" aria-label={t('nav.openMenu')} aria-controls="pf-app-sidebar" aria-expanded={menuOpen} onClick={() => setMenuOpen(true)}><Menu size={21} aria-hidden /></button>+ <BrandMark />+ <span className="pf-mobile-current">{currentLabel}</span>+ <button type="button" className="pf-mobile-create" aria-label={t('nav.startCreate')} onClick={goCreate}><Plus size={20} aria-hidden /></button>+ </header>+ {menuOpen && <button type="button" className="pf-sidebar-backdrop" aria-label={t('nav.closeMenu')} tabIndex={-1} onClick={() => setMenuOpen(false)} />}+ <aside ref={sidebarRef} id="pf-app-sidebar" className={`pf-app-sidebar${menuOpen ? ' is-open' : ''}`} role={menuOpen ? 'dialog' : undefined} aria-modal={menuOpen ? true : undefined} aria-label={t('nav.main')}+ onTransitionEnd={(event) => {+ if (menuOpen && event.target === event.currentTarget && event.propertyName === 'transform') closeButtonRef.current?.focus()+ }}>+ <div className="pf-sidebar-top">+ <div className="pf-sidebar-brand"><BrandMark /><button ref={closeButtonRef} type="button" className="pf-sidebar-icon-button pf-sidebar-close" aria-label={t('nav.closeMenu')} onClick={() => setMenuOpen(false)}><X size={19} aria-hidden /></button></div>+ <div className="pf-sidebar-workspace"><WorkspaceSwitcher /></div>+ <button type="button" className="pf-sidebar-create" onClick={goCreate}><Plus size={19} aria-hidden /><span>{t('nav.startCreate')}</span><ArrowUpRight size={17} aria-hidden /></button></div>- <nav className="pf-nav-center" aria-label={t('nav.main')}>- {centerLinks}+ <nav className="pf-sidebar-navigation" aria-label={t('nav.main')}>+ <div className="pf-sidebar-group"><span className="pf-sidebar-group-label">{t('nav.creation')}</span>{CREATION_NAV.map(renderLink)}</div>- <div className="pf-sidebar-group"><span className="pf-sidebar-group-label">{t('nav.resources')}</span>{RESOURCE_NAV.map(renderLink)}</div>++ <div className="pf-sidebar-group"><span className="pf-sidebar-group-label">{t('nav.resources')}</span>{RESOURCE_NAV.map(renderLink)}++ {marketplace?.enabled && <Link to="/marketplace" className={`pf-sidebar-link${inMarketplace ? ' is-active' : ''}`} aria-current={inMarketplace ? 'page' : undefined} onClick={() => { selectTeam(null); setMenuOpen(false) }}>++ <Store size={19} strokeWidth={1.8} aria-hidden />++ <span>数字资产市场</span>++ {inMarketplace && <ChevronRight size={15} className="pf-sidebar-link-arrow" aria-hidden />}++ </Link>}++ </div></nav>- <div className="pf-nav-right">- <LanguageSwitch />- <a- className="pf-nav-github"- href={GITHUB_REPO_URL}- target="_blank"- rel="noopener noreferrer"- title={t('nav.githubTitle')}- aria-label={t('nav.githubTitle')}- >- <IconGithub size={18} />- <span>{t('nav.github')}</span>- </a>- <button type="button" className="pf-nav-help-btn" title={t('nav.helpCenter')} onClick={() => nav('/help')}>- <IconHelp size={18} className="pf-nav-help-icon" />- <span>{t('nav.help')}</span>- </button>- {user ? (- <button- type="button"- className="pf-avatar"- title={`${user.nickname} · ${t('nav.profile')}`}- onClick={() => nav('/settings')}- >- <UserAvatar user={user} size="sm" />- </button>- ) : (- <Link to="/auth?next=/" className="pf-link pf-nav-login">- {t('nav.login')}- </Link>- )}- <Button variant="lime" size="sm" icon onClick={goCreate}>- {t('nav.startCreate')}- </Button>- <button- type="button"- className="pf-nav-burger"- aria-label={menuOpen ? t('nav.closeMenu') : t('nav.openMenu')}- aria-expanded={menuOpen}- onClick={() => setMenuOpen((v) => !v)}- >- <span />- <span />- <span />- </button>- </div>- {menuOpen ? (- <div className="pf-nav-drawer" role="dialog" aria-label={t('nav.mobileNav')}>- <nav className="pf-nav-drawer-links">- {centerLinks}- <a href={GITHUB_REPO_URL} target="_blank" rel="noopener noreferrer">- {t('nav.github')}- </a>- </nav>+ <div className="pf-sidebar-bottom">+ <div className="pf-sidebar-utilities">+ <Link to="/help" className={current === 'help' ? 'is-active' : undefined} aria-current={current === 'help' ? 'page' : undefined} onClick={() => setMenuOpen(false)}><CircleHelp size={17} aria-hidden /><span>{t('nav.help')}</span></Link>+ <a href={GITHUB_REPO_URL} target="_blank" rel="noopener noreferrer" title={t('nav.githubTitle')} onClick={() => setMenuOpen(false)}><IconGithub size={17} /><span>{t('nav.github')}</span></a></div>- ) : null}- <CreateChoiceModal open={createOpen} onClose={() => setCreateOpen(false)} />- </header>- )+ <div className="pf-sidebar-language"><span>{t('nav.language')}</span><LanguageSwitch /></div>+ <Link to={user ? '/settings' : '/auth?next=/'} className={`pf-sidebar-account${current === 'settings' ? ' is-active' : ''}`} aria-current={current === 'settings' ? 'page' : undefined} onClick={() => setMenuOpen(false)}>+ {user ? <UserAvatar user={user} size="sm" /> : <span className="pf-sidebar-account-guest"><UserRound size={19} aria-hidden /></span>}+ <span><strong>{user?.nickname || t('nav.login')}</strong><small>{user ? t('nav.profile') : t('nav.loginHint')}</small></span>+ <Settings2 size={17} aria-hidden />+ </Link>+ </div>+ </aside>+ <CreateChoiceModal open={createOpen} onClose={() => setCreateOpen(false)} />+ </>}diff --cc frontend/src/pages/HistoryPage.tsxindex 0481b7e,bb3c8da..2bd82b6--- a/frontend/src/pages/HistoryPage.tsx+++ b/frontend/src/pages/HistoryPage.tsx@@@ -13,7 -14,9 +13,8 @@@ importIconEdit,IconEye,IconPlus,- IconRefresh,IconSearch,+ IconSend,IconTrash,} from '../components/ui/Icons'import { dialog } from '../lib/dialog'@@@ -322,58 -361,147 +323,59 @@@ export default function HistoryPage()</div></div>- <div className="pf-history-batch">- <button- type="button"- className="pf-btn-text"- disabled={!selectedDownloadable.length || packing}- onClick={packSelected}- >+ {selectedDownloadable.length > 0 ? <div className="pf-short-video-batch">+ <button type="button" className="pf-btn-text" disabled={packing} onClick={packSelected}><IconDownload size={15} />- {packing- ? t('history.packing', { progress: packProgress })- : t('history.packDownload', { count: selectedDownloadable.length })}+ {packing ? t('history.packing', { progress: packProgress }) : t('history.packDownload', { count: selectedDownloadable.length })}</button>- </div>+ <button type="button" className="pf-btn-text" disabled={packing} onClick={() => setSelected(new Set())}>{t('common.cancel')}</button>+ </div> : null}{error ? <BillingErrorNotice message={error} /> : null}- {loading ? <p className="pf-muted">{t('common.loading')}</p> : null}- {!loading && total === 0 ? (- <div className="pf-history-empty">{t('history.empty')}</div>- ) : null}-- <div className="pf-project-list">- {pageItems.map((p) => {- const badge = statusBadgeClass(p.status)- const ratio =- p.output_ratio || (p.pipeline_mode === 'image_text' ? '9:16' : '16:9')- const tplName = templates[p.template_id] || p.template_id- return (- <article key={p.id} className="pf-project-card">- <label className="pf-project-check">- <input- type="checkbox"- checked={selected.has(p.id)}- disabled={!canDownload(p)}- onChange={() => toggle(p.id)}- />- </label>- <button- type="button"- className="pf-project-thumb"- onClick={() => continueEdit(p)}- >- {p.cover_url ? (- <img src={api.assetUrl(p.cover_url, p.updated_at)} alt="" />- ) : (- <div className="ph">{t('history.noCover')}</div>- )}- {isRunning(p.status) ? (- <span className="pf-thumb-progress">{p.progress}%</span>- ) : null}- </button>- <div className="pf-project-info">- <h3>- {p.title}- {p.published ? <span className="pf-badge ok" style={{ marginLeft: 8 }}>{t('history.published')}</span> : null}- </h3>- <div className="pf-project-meta">- <span className={`pf-badge ${badge}`}>- {STATUS_CN[p.status] || p.status}- </span>- <span className="pf-muted">- {t('history.templateMeta', {- name: tplName,- when: formatDateTime(p.updated_at || p.created_at, locale),- })}- </span>- </div>- {isRunning(p.status) ? (- <div className="pf-inline-meter">- <i style={{ width: `${Math.min(100, p.progress)}%` }} />- </div>- ) : null}- {p.error_msg ? <p className="pf-error pf-project-err">{p.error_msg}</p> : null}- </div>- <div className="pf-project-ratio">{ratio}</div>- <div className="pf-project-actions">- <button type="button" className="pf-btn-text" onClick={() => continueEdit(p)}>- <IconEdit size={14} />- {t('history.continueEdit')}- </button>- <button- type="button"- className="pf-btn-text"- disabled={!p.final_video_url}- onClick={() =>- p.final_video_url &&- setPreview({- url: api.assetUrl(p.final_video_url, p.updated_at),- title: p.title,- projectId: p.id,- })- }- >- <IconEye size={14} />- {t('common.preview')}- </button>- <button- type="button"- className="pf-btn-text"- disabled={!canDownload(p) || busyId === p.id || packing}- onClick={() => downloadOne(p)}- >- <IconDownload size={14} />- {busyId === p.id ? t('common.downloading') : t('common.download')}- </button>- <button- type="button"- className="pf-btn-text"- disabled={!p.final_video_url}- onClick={() => nav(`/marketplace/from-printfilm?project=${p.id}`)}- >- <IconSend size={14} />- 发布到市场- </button>- <button- type="button"- className="pf-icon-btn danger"- disabled={busyId === p.id}- title={t('common.delete')}- onClick={() => remove(p.id)}- >- <IconTrash size={16} />- </button>- </div>- </article>- )- })}- </div>-+ {loading ? (+ <div aria-busy="true" aria-label={t('common.loading')}><ProjectGrid>{Array.from({ length: 6 }, (_, i) => <div key={i} className="pf-project-list-skeleton" aria-hidden />)}</ProjectGrid></div>+ ) : total === 0 ? (+ <div className="pf-empty-state">+ <div className="pf-empty-illust" aria-hidden><IconClapper size={42} /></div>+ <p className="pf-muted">{t('history.empty')}</p>+ <button type="button" className="pf-btn pf-btn-lime" onClick={() => nav(SHORT_VIDEO_CREATE_PATH)}><IconPlus size={17} />{t('history.newKepu')}</button>+ </div>+ ) : (+ <ProjectGrid>+ {pageItems.map((p) => {+ const running = isRunning(p.status) || hasActiveTasks(p)+ const ratio = p.output_ratio || (p.pipeline_mode === 'image_text' ? '9:16' : '16:9')+ const tplName = templates[p.template_id] || p.template_id+ return <ProjectCard+ key={p.id}+ kind="short-video"+ title={p.title}+ coverUrl={p.cover_url ? api.assetUrl(p.cover_url, p.updated_at) : undefined}+ category={`${tplName} · ${ratio}`}+ status={{ label: STATUS_CN[p.status] || p.status, tone: p.status === 'DONE' ? 'completed' : running ? 'producing' : p.status === 'DRAFT' ? 'draft' : 'neutral' }}+ description={p.source_text || t('history.workflowHint')}+ progress={running ? { label: t('history.progress'), value: Math.max(0, Math.min(100, p.progress)), total: 100 } : undefined}+ meta={p.error_msg ? <span className="pf-error" role="status">{p.error_msg}</span> : undefined}+ footer={<>+ <span>{p.published ? t('history.published') : (p.pipeline_mode === 'image_text' ? t('history.typeImageText') : t('history.typeFull'))}</span>+ <time dateTime={p.updated_at || p.created_at}>{formatDateTime(p.updated_at || p.created_at, locale)}</time>+ </>}+ selection={canDownload(p) ? { checked: selected.has(p.id), visible: selected.size > 0, onChange: () => toggle(p.id), label: t('history.selectProject', { title: p.title }) } : undefined}+ onOpen={() => continueEdit(p)}+ openLabel={`${t('history.continueEdit')} ${p.title}`}+ menu={<button type="button" className="pf-icon-btn danger" disabled={busyId === p.id} title={t('common.delete')} aria-label={`${t('common.delete')} ${p.title}`} onClick={() => remove(p.id)}><IconTrash size={16} /></button>}+ actions={<>+ <button type="button" className="pf-btn-text" onClick={() => continueEdit(p)}><IconEdit size={14} />{t('history.continueEdit')}</button>+ <button type="button" className="pf-btn-text" disabled={!p.final_video_url} onClick={() => p.final_video_url && setPreview({ url: api.assetUrl(p.final_video_url, p.updated_at), title: p.title, projectId: p.id })}><IconEye size={14} />{t('common.preview')}</button>+ <button type="button" className="pf-btn-text" disabled={!canDownload(p) || busyId === p.id || packing} onClick={() => downloadOne(p)}><IconDownload size={14} />{busyId === p.id ? t('common.downloading') : t('common.download')}</button>++ <button type="button" className="pf-btn-text" disabled={!p.final_video_url} onClick={() => nav(`/marketplace/from-printfilm?project=${p.id}`)}><IconSend size={14} />发布到市场</button>+ </>}+ />+ })}+ </ProjectGrid>+ )}{total > 0 ? (- <Pagination- page={page}- pageCount={pageCount}- total={total}- pageSize={pageSize}- onPageSizeChange={(size) => {- setPageSize(size)- setPage(1)- }}- onChange={setPage}- ariaLabel={t('history.pagination')}- />+ <Pagination page={page} pageCount={pageCount} total={total} pageSize={pageSize} pageSizeOptions={PAGE_SIZE_OPTIONS} onPageSizeChange={(size) => { setPageSize(size); setPage(1) }} onChange={setPage} ariaLabel={t('history.pagination')} />) : null}</section></div>diff --cc frontend/src/pages/drama/DramaListPage.tsxindex 6af88ef,ca29872..e7989e0--- a/frontend/src/pages/drama/DramaListPage.tsx+++ b/frontend/src/pages/drama/DramaListPage.tsx@@@ -21,19 -22,18 +21,21 @@@ importdramaProjectEntryPath,formatDramaCardMeta,isCanvasWorkflow,+ type DramaProjectFilter,+ type DramaWorkflow,} from '../../lib/dramaWorkflow'+import { pageCountOf } from '../../lib/pagination'+import Pagination from '../../components/ui/Pagination'import RequireAuth from './RequireAuth'import { useI18n } from '../../i18n'-import { DramaEpisodeCountPopover } from './DramaEpisodeCountPopover'-import { DramaImageStyleModal } from './DramaImageStyleModal'import { DramaProjectCardMenu } from './DramaProjectCardMenu'+import { ProjectCard, ProjectGrid } from '../../components/projects/ProjectCard'+import ProjectCreateDialog, { type ProjectCreateValues } from '../../components/projects/ProjectCreateDialog'+ import DramaPublishModal from '../../features/marketplace/DramaPublishModal'+ import { useMarketplace } from '../../features/marketplace/hooks'import './drama.css'+import './project-list.css'-const CREATIVE_MIN_LENGTH = 20-const CREATIVE_MAX_LENGTH = 2000const CANVAS_PLACEHOLDER ='自由画布创作项目,稍后在画布中完善故事与资产。'@@@ -61,24 -68,41 +63,26 @@@ export default function DramaListPage(}// 渲染 Agent 首页内容-function DramaListInner() {+function DramaListInner({ workflow }: { workflow: DramaWorkflow }) {const navigate = useNavigate()+ const { capabilities } = useMarketplace()+ const [publishProjectId, setPublishProjectId] = useState<number | null>(null)const { t, m } = useI18n()- const filterOptions = useMemo<PillOption<ProjectFilter>[]>(+ const canvasMode = workflow === 'canvas'+ const createLabel = canvasMode ? t('canvasList.newCanvas') : t('dramaList.newProject')+ const filterOptions = useMemo<PillOption<DramaProjectFilter>[]>(() =>- FILTER_KEYS.map((value) => ({+ FILTER_KEYS.filter((value) => !canvasMode || value !== 'done').map((value) => ({value,- label: m.dramaList.filters[value],+ label: canvasMode && value === 'draft' ? t('canvasList.emptyFilter') : m.dramaList.filters[value],})),- [m],+ [m, t, canvasMode],)- /*- * storyText AI 创意输入- * episodeCount 目标集数- * imageStyleId 画面风格- * items 我的项目列表- * loading 列表加载中- * busy 创建中- * canvasBusy 画布创建中- * error 错误文案- * selected 多选 id- * deleting 批量删除中- * filter 列表筛选- * query 搜索- * showCreate 是否展开新建面板- */- const [storyText, setStoryText] = useState('')- const [episodeCount, setEpisodeCount] = useState(12)- const [imageStyleId, setImageStyleId] = useState<ImageStyleId | ''>('')const [items, setItems] = useState<DramaProjectListItem[]>([])+ const [total, setTotal] = useState(0)+ const [page, setPage] = useState(1)+ const [pageSize, setPageSize] = useState<number>(PAGE_SIZE_DEFAULT)const [loading, setLoading] = useState(true)- const [busy, setBusy] = useState(false)- const [canvasBusy, setCanvasBusy] = useState(false)const [error, setError] = useState('')const [selected, setSelected] = useState<Set<number>>(new Set())const [deleting, setDeleting] = useState(false)@@@ -281,70 -342,184 +285,74 @@@/></label></div>- </header>- {showCreate ? (- <section className="drama-agent-panel pf-drama-create-panel" aria-label={t('dramaList.createAria')}>- <div className="drama-agent-panel-head">- <div className="drama-agent-tabs" role="tablist">- <button type="button" role="tab" aria-selected className="active">- <PenLine size={15} strokeWidth={1.75} aria-hidden />- {t('dramaList.aiScript')}- </button>- </div>- <button type="button" className="pf-link pf-drama-collapse" onClick={() => setShowCreate(false)}>- {t('dramaList.collapse')}- </button>+ {error ? <BillingErrorNotice message={error} className="drama-error" /> : null}+ {loading ? (+ <div aria-busy="true" aria-label="正在加载项目">+ <ProjectGrid>{Array.from({ length: pageSize }).map((_, i) => <div key={i} className="pf-project-list-skeleton" aria-hidden />)}</ProjectGrid></div>- <div className="drama-agent-tips" role="note">- <Sparkles size={15} strokeWidth={1.75} aria-hidden />- <span>- {t('dramaList.tipRest', {- a: t('dramaList.tipStrong1'),- b: t('dramaList.tipStrong2'),- c: t('dramaList.tipStrong3'),- })}- </span>+ ) : pristineEmpty ? (+ <div className="pf-empty-state">+ <div className="pf-empty-illust" aria-hidden><FolderOpen size={48} strokeWidth={1.2} /></div>+ <h2>{t(canvasMode ? 'canvasList.emptyTitle' : 'dramaList.emptyTitle')}</h2>+ <p className="pf-muted">{t(canvasMode ? 'canvasList.emptyDescription' : 'dramaList.emptyDescription')}</p>+ <Button variant="lime" onClick={() => setShowCreate(true)}><Plus size={17} />{createLabel}</Button></div>- <div className="drama-agent-ai">- <label className="drama-agent-ai-label" htmlFor="drama-agent-story">- {t('dramaList.storyLabel')}- </label>- <div className={`drama-agent-ai-field${storyText.trim() ? ' has-value' : ''}`}>- <textarea- id="drama-agent-story"- value={storyText}- onChange={(e) => setStoryText(e.target.value.slice(0, CREATIVE_MAX_LENGTH + 50))}- disabled={busy}- placeholder="在此输入你构想的故事内容:故事设定、主角特征、剧情脉络、最终结局等"- rows={7}- maxLength={CREATIVE_MAX_LENGTH + 50}- />- <span- className={`drama-agent-char-count${charCountClass}`}- aria-live="polite"- >- {storyLen}- <span className="drama-agent-char-sep">/</span>- {CREATIVE_MAX_LENGTH}- </span>- </div>- <div className="drama-agent-ai-footer">- <div className="drama-agent-ai-options">- <DramaImageStyleModal value={imageStyleId} onChange={setImageStyleId} disabled={busy} />- <span className="drama-agent-opt-divider" aria-hidden />- <DramaEpisodeCountPopover value={episodeCount} onChange={setEpisodeCount} disabled={busy} />- </div>- <Button- variant="lime"- size="md"- className="drama-agent-generate-btn"- disabled={!canGenerate}- onClick={() => void handleGenerate()}- >- <Sparkles size={16} strokeWidth={1.75} aria-hidden />- {busy ? '创建中…' : '立即生成'}- </Button>- </div>+ ) : items.length === 0 ? (+ <div className="pf-empty-state is-compact">+ <p className="pf-muted">没有符合筛选的项目</p>+ <Button variant="ghost" size="sm" onClick={() => { setFilter('all'); setQuery('') }}>清除筛选</Button></div>- </section>- ) : null}-- {error ? <BillingErrorNotice message={error} className="drama-error drama-agent-error" /> : null}-- {loading ? (- <div className="pf-drama-card-grid" aria-busy="true">- {Array.from({ length: 6 }).map((_, i) => (- <div key={i} className="pf-drama-card is-skeleton" />- ))}- </div>- ) : items.length === 0 ? (- <div className="pf-empty-state">- <div className="pf-empty-illust" aria-hidden>- <FolderOpen size={48} strokeWidth={1.2} />- </div>- <h2>还没有项目</h2>- <p className="pf-muted">用 AI 生剧本或自由画布,创建你的第一部漫剧</p>- <Button- variant="lime"- onClick={() => {- setShowCreate(true)- handleTabClick('ai')- }}- >- 新建项目- </Button>- </div>- ) : filteredItems.length === 0 ? (- <div className="pf-empty-state is-compact">- <p className="pf-muted">没有符合筛选的项目</p>- <Button variant="ghost" size="sm" onClick={() => { setFilter('all'); setQuery('') }}>- 清除筛选- </Button>- </div>- ) : (- <div className="pf-drama-card-grid">- <button- type="button"- className="pf-drama-card pf-drama-card-new"- onClick={() => {- setShowCreate(true)- handleTabClick('ai')- }}- >- <span className="pf-drama-card-plus" aria-hidden>- +- </span>- <strong>新建项目</strong>- </button>- {filteredItems.map((item) => {- const isSelected = selected.has(item.id)- const coverSrc = item.cover_url ? resolveDramaMediaUrl(item.cover_url) : ''- const canvas = isCanvasWorkflow(item)- return (- <article+ ) : (+ <>+ <ProjectGrid>+ {items.map((item) => {+ const canvas = isCanvasWorkflow(item)+ const active = canvas ? item.asset_count > 0 : item.has_script+ const status = item.cover_pending && !canvas ? '封面生成中' : active ? (canvas ? '创作中' : '已写剧本') : (canvas ? '空画布' : '构思中')+ return <ProjectCardkey={item.id}- className={`pf-drama-card${isSelected ? ' is-selected' : ''}${canvas ? ' is-canvas' : ''}`}- >- <button- type="button"- className="pf-drama-card-cover"- onClick={() => openProject(item)}- aria-label={`打开 ${item.title}`}- >- {coverSrc ? (- <img- src={coverSrc}- alt=""- className="pf-drama-card-cover-img"- loading="lazy"- decoding="async"- />- ) : (- <span className="pf-drama-card-cover-fallback">{verticalTitleLabel(item.title)}</span>- )}- {canvas ? <span className="pf-drama-card-cover-badge is-canvas">自由画布</span> : null}- {!canvas && item.cover_pending ? (- <span className="pf-drama-card-cover-badge">封面生成中</span>- ) : null}- {!canvas && !coverSrc && !item.cover_pending && item.asset_count > 0 ? (- <span className="pf-drama-card-cover-badge is-muted">待出图</span>- ) : null}- <label- className={`drama-project-row-check${isSelected || selectionMode ? ' is-visible' : ''}`}- onClick={(e) => e.stopPropagation()}- >- <input type="checkbox" checked={isSelected} onChange={() => toggleSelect(item.id)} />- </label>- </button>- <div className="pf-drama-card-body">- <div className="pf-drama-card-top">- <button type="button" className="pf-drama-card-title" onClick={() => openProject(item)}>- {item.title}- </button>- <DramaProjectCardMenu- onRename={() => void handleRename(item)}- onDelete={() => void handleDeleteOne(item)}- onPublish={capabilities?.enabled ? () => setPublishProjectId(item.id) : undefined}- />- </div>- <p className="pf-drama-card-meta">{formatDramaCardMeta(item)}</p>- <p className="pf-drama-card-usage" title="本剧累计费用与生成次数">- {formatDramaUsageBrief(item.usage)}- </p>- <p className="pf-drama-card-time">{formatUpdatedAt(item.updated_at || item.created_at)}</p>- </div>- </article>- )- })}- </div>- )}+ title={item.title}+ kind={canvas ? 'canvas' : 'drama'}+ coverUrl={item.cover_url ? resolveDramaMediaUrl(item.cover_url) : undefined}+ category={canvas ? '自由画布' : `漫剧项目 · ${item.episode_count} 集`}+ status={{ label: status, tone: active || item.cover_pending ? 'producing' : 'draft' }}+ description={item.description || (canvas ? '在画布中添加图片、视频与灵感,展开自由创作。' : '从故事到分镜,在项目中继续完善你的作品。')}+ meta={<>+ <span className="pf-project-list-card-meta"><Layers size={14} aria-hidden />{formatDramaCardMeta(item)}</span>+ <span title={canvasMode ? t('canvasList.usageTitle') : '本剧累计费用与生成次数'}>{formatDramaUsageBrief(item.usage)}</span>+ </>}+ footer={<>+ <span><UserRound size={13} aria-hidden />个人项目</span>+ <time dateTime={item.updated_at || item.created_at}>{formatUpdatedAt(item.updated_at || item.created_at)}</time>+ </>}- menu={<DramaProjectCardMenu onRename={() => void handleRename(item)} onDelete={() => void handleDeleteOne(item)} />}++ menu={<DramaProjectCardMenu++ onRename={() => void handleRename(item)}++ onDelete={() => void handleDeleteOne(item)}++ onPublish={capabilities?.enabled ? () => setPublishProjectId(item.id) : undefined}++ />}+ selection={{ checked: selected.has(item.id), visible: selectionMode, onChange: () => toggleSelect(item.id), label: `选择 ${item.title}` }}+ onOpen={() => openProject(item)}+ openLabel={selectionMode ? `切换选择 ${item.title}` : `打开 ${item.title}`}+ />+ })}+ </ProjectGrid>+ <Pagination+ page={page}+ pageCount={pageCount}+ total={total}+ pageSize={pageSize}+ pageSizeOptions={PAGE_SIZE_OPTIONS}+ onPageSizeChange={(size) => {+ setPageSize(size)+ setPage(1)+ }}+ onChange={setPage}+ />+ </>+ )}+ </section>+ <ProjectCreateDialog open={showCreate} onClose={() => setShowCreate(false)} kind={canvasMode ? 'canvas' : 'drama'} onSubmit={handleCreateProject} />{selected.size > 0 ? (<div className="drama-project-selection-bar">diff --cc frontend/src/pages/drama/EpisodeEditPage.tsxindex 181dc6a,375f5b1..6c984db--- a/frontend/src/pages/drama/EpisodeEditPage.tsx+++ b/frontend/src/pages/drama/EpisodeEditPage.tsx@@@ -1771,7 -1728,9 +1771,8 @@@ function EpisodeEditInner()onPlayingFragmentChange={handlePlayingFragmentChange}aspectRatio={aspectRatio}episodeId={episode?.id}+ projectId={projectId}episodeName={episode?.name || '本集'}- subtitleMode={subtitleMode}onOpenStoryboard={openEpisodeStoryboard}previewVideoUrl={previewVideoUrl}previewPosterUrl={previewPosterUrl}diff --cc frontend/src/pages/drama/EpisodeEditSidePane.tsxindex 242bec3,4ff1971..8a176ac--- a/frontend/src/pages/drama/EpisodeEditSidePane.tsx+++ b/frontend/src/pages/drama/EpisodeEditSidePane.tsx@@@ -1,7 -1,10 +1,9 @@@/** 分集编辑右侧:分段视频预览 + 入口打开全屏分镜画布 */import { useState } from 'react'import { Download, Loader2 } from 'lucide-react'+ import DramaPublishModal from '../../features/marketplace/DramaPublishModal'+ import { useMarketplace } from '../../features/marketplace/hooks'import type { DramaFragment } from '../../api/drama'-import { DramaSubtitleBoard } from '../../components/drama/DramaSubtitleBoard'import { DramaFragmentSegmentedVideoPlayer } from '../../components/drama/DramaFragmentSegmentedVideoPlayer'import { triggerBlobDownload } from '../../lib/clientDownload'import {@@@ -18,7 -22,9 +20,8 @@@ type Props =onPlayingFragmentChange: (fragmentId: number) => voidaspectRatio: stringepisodeId?: number+ projectId?: stringepisodeName?: string- subtitleMode: DramaSubtitleModeonOpenStoryboard: () => void/** 预览历史版本时覆盖当前镜 video src */previewVideoUrl?: string | null@@@ -44,7 -50,9 +47,8 @@@ export function EpisodeEditSidePane(onPlayingFragmentChange,aspectRatio,episodeId,+ projectId,episodeName = '本集',- subtitleMode,onOpenStoryboard,previewVideoUrl = null,previewPosterUrl = null,@@@ -144,22 -163,30 +159,23 @@@{!hasSelection || fragments.length === 0 ? (<p className="drama-ep-empty">请选择底部分镜</p>) : (- <>- <div className="drama-ep-preview-inner">- <DramaFragmentSegmentedVideoPlayer- fragments={fragments}- playingFragmentId={playingFragmentId}- onPlayingFragmentChange={onPlayingFragmentChange}- aspectRatio={aspectRatio}- overrideVideoUrl={previewVideoUrl}- overridePosterUrl={previewPosterUrl}- />- {!fragments.some((f) => f.video) && (- <button type="button" className="drama-ep-open-canvas" onClick={onOpenStoryboard}>- 打开分镜画布- </button>- )}- </div>- <DramaSubtitleBoard+ <div className="drama-ep-preview-inner">+ <DramaFragmentSegmentedVideoPlayerfragments={fragments}- episodeName={episodeName}- subtitleMode={subtitleMode}+ playingFragmentId={playingFragmentId}+ onPlayingFragmentChange={onPlayingFragmentChange}+ aspectRatio={aspectRatio}+ overrideVideoUrl={previewVideoUrl}+ overridePosterUrl={previewPosterUrl}/>- </>+ {!fragments.some((f) => f.video) && (+ <button type="button" className="drama-ep-open-canvas" onClick={onOpenStoryboard}>+ 打开分镜画布+ </button>+ )}+ </div>)}+ {publishOpen && capabilities?.enabled && projectId && <DramaPublishModal projectId={Number(projectId)} initialEpisodeId={episodeId} onClose={() => setPublishOpen(false)} />}</aside>)}