PRINTFILM: AI short-video marketing and AI short-drama creation platform
feat(team): 团队空间后端——成员邀请、编辑锁、团队计费与任务隔离
yif066b39a7cf9
diff --git a/backend/app/api/admin/teams.py b/backend/app/api/admin/teams.pynew file mode 100644index 0000000..58a56a0--- /dev/null+++ b/backend/app/api/admin/teams.py@@ -0,0 +1,109 @@+"""平台管理员团队查询和可审计的钱包调账。"""+from datetime import date+from typing import Literal++from fastapi import APIRouter, Depends, HTTPException, Path, Query+from sqlalchemy.ext.asyncio import AsyncSession++from app.database import get_db+from app.deps import get_current_admin+from app.models import User+from app.schemas_admin_teams import AdminTeamBudgetInput, AdminTeamMemberPage, AdminTeamOut, AdminTeamPage, AdminTeamUsagePage+from app.schemas_admin_teams import AdminTeamBalanceAdjustmentInput, AdminTeamBalanceAdjustmentOut, AdminTeamWalletLedgerPage+from app.services.teams import admin_queries, admin_wallet++router = APIRouter(prefix="/teams", dependencies=[Depends(get_current_admin)])++[email protected]("", response_model=AdminTeamPage)+async def list_teams(+ q: str = Query("", max_length=180),+ owner_id: int | None = Query(None, ge=1, le=2_147_483_647),+ page: int = Query(1, ge=1),+ page_size: int = Query(20, ge=1, le=100),+ db: AsyncSession = Depends(get_db),+) -> AdminTeamPage:+ """按团队或所有者搜索并分页返回钱包与消费快照。"""+ return await admin_queries.list_teams(db, q=q, owner_id=owner_id, page=page, page_size=page_size)++[email protected]("/{team_id}", response_model=AdminTeamOut)+async def team_detail(+ team_id: int = Path(ge=1, le=2_147_483_647),+ db: AsyncSession = Depends(get_db),+) -> AdminTeamOut:+ """查看指定团队基本资料。"""+ return await admin_queries.team_detail(db, team_id)++[email protected]("/{team_id}/members", response_model=AdminTeamMemberPage)+async def list_members(+ team_id: int = Path(ge=1, le=2_147_483_647),+ q: str = Query("", max_length=180),+ role: Literal["owner", "admin", "member"] | None = None,+ state: Literal["all", "active", "removed"] = "all",+ period: str | None = Query(None, pattern=r"^\d{4}-(0[1-9]|1[0-2])$"),+ page: int = Query(1, ge=1),+ page_size: int = Query(20, ge=1, le=100),+ db: AsyncSession = Depends(get_db),+) -> AdminTeamMemberPage:+ """查看有效或已退出成员及指定月份的实际消费、预留和额度。"""+ return await admin_queries.list_members(db, team_id, q=q, role=role, state=state, period=period, page=page, page_size=page_size)++[email protected]("/{team_id}/usage-events", response_model=AdminTeamUsagePage)+async def list_usage(+ team_id: int = Path(ge=1, le=2_147_483_647),+ q: str = Query("", max_length=180),+ user_id: int | None = Query(None, ge=1, le=2_147_483_647),+ settled: bool | None = None,+ date_from: date | None = None,+ date_to: date | None = None,+ page: int = Query(1, ge=1),+ page_size: int = Query(20, ge=1, le=100),+ db: AsyncSession = Depends(get_db),+) -> AdminTeamUsagePage:+ """按成员、模型/项目关键词、结算状态和上海日期范围查看团队消费。"""+ return await admin_queries.list_usage(db, team_id, q=q, user_id=user_id, settled=settled, date_from=date_from, date_to=date_to, page=page, page_size=page_size)++[email protected]("/{team_id}/balance-adjustments", response_model=AdminTeamBalanceAdjustmentOut)+async def adjust_balance(+ body: AdminTeamBalanceAdjustmentInput,+ team_id: int = Path(ge=1, le=2_147_483_647),+ admin: User = Depends(get_current_admin),+ db: AsyncSession = Depends(get_db),+) -> AdminTeamBalanceAdjustmentOut:+ """按金额增减团队可用余额,并将操作者和备注同事务写入钱包流水。"""+ raise HTTPException(410, "团队已改为所有者个人账户付费,请在用户管理调整所有者余额")++[email protected]("/{team_id}/wallet-ledger", response_model=AdminTeamWalletLedgerPage)+async def wallet_ledger(+ team_id: int = Path(ge=1, le=2_147_483_647),+ q: str = Query("", max_length=180),+ adjustments_only: bool = False,+ page: int = Query(1, ge=1),+ page_size: int = Query(20, ge=1, le=100),+ db: AsyncSession = Depends(get_db),+) -> AdminTeamWalletLedgerPage:+ """分页查看团队钱包流水及后台调账审计记录。"""+ return await admin_wallet.list_wallet_ledger(db, team_id, q=q, adjustments_only=adjustments_only, page=page, page_size=page_size)++[email protected]("/{team_id}/budget")+async def update_budget(body: AdminTeamBudgetInput, team_id: int = Path(ge=1), admin: User = Depends(get_current_admin), db: AsyncSession = Depends(get_db)) -> dict:+ """平台管理员设置团队月总额度,保留已有消费和在途任务。"""+ from app.services.teams.budgets import set_budget+ await set_budget(db, team_id, admin.id, body.monthly_limit_fen)+ await db.commit()+ return {"monthly_limit_fen": body.monthly_limit_fen}++[email protected]("/{team_id}/members/{user_id}/budget")+async def update_member_budget(body: AdminTeamBudgetInput, team_id: int = Path(ge=1), user_id: int = Path(ge=1), admin: User = Depends(get_current_admin), db: AsyncSession = Depends(get_db)) -> dict:+ """平台管理员设置有效成员月额度,包含所有者。"""+ from app.services.teams.budgets import set_budget+ await set_budget(db, team_id, admin.id, body.monthly_limit_fen, user_id=user_id)+ await db.commit()+ return {"monthly_limit_fen": body.monthly_limit_fen}diff --git a/backend/app/api/team_billing.py b/backend/app/api/team_billing.pynew file mode 100644index 0000000..cbe6448--- /dev/null+++ b/backend/app/api/team_billing.py@@ -0,0 +1,119 @@+"""所有者统一付款的团队用量;旧钱包、旧订单只读兼容。"""+from __future__ import annotations+from fastapi import APIRouter, Depends, HTTPException, Query, Request+from sqlalchemy import func, or_, select+from sqlalchemy.ext.asyncio import AsyncSession+from app.api.billing import CreateOrderBody+from app.config import get_settings+from app.database import get_db+from app.deps import get_current_user+from app.models import Order, UsageEvent, User+from app.models_drama import DramaProject+from app.models_tasks import TaskRun+from app.models_team_billing import TeamMonthlyUsage, TeamWalletLedger+from app.services import billing+from app.services.billing.team import billing_period+from app.services.teams.access import get_team++router = APIRouter(prefix="/teams/{team_id}", tags=["team-billing"])+++def order_out(order: Order) -> dict:+ sku = billing.sku_by_id(order.sku_id) or {}+ return {"out_trade_no": order.out_trade_no, "sku_id": order.sku_id, "sku_name": str(sku.get("name") or order.sku_id), "amount_fen": order.amount_fen, "credit_fen": order.credit_fen, "pay_type": order.pay_type, "status": order.status, "trade_no": order.trade_no, "paid_at": order.paid_at.isoformat() if order.paid_at else None, "created_at": order.created_at.isoformat() if order.created_at else None}++[email protected]("/wallet")+async def wallet(team_id: int, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ await get_team(db, team_id, user.id, roles={"owner"})+ row = await db.get(User, user.id)+ if row is None:+ raise HTTPException(404, "团队钱包不存在")+ return {"balance_fen": int(row.balance_fen or 0), "frozen_fen": int(row.frozen_fen or 0), "balance_yuan": round(int(row.balance_fen or 0) / 100, 2), "frozen_yuan": round(int(row.frozen_fen or 0) / 100, 2), "billing_enabled": bool(get_settings().billing_enabled), "billing_source": "owner_personal"}++[email protected]("/wallet/ledger")+async def wallet_ledger(team_id: int, page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ await get_team(db, team_id, user.id, roles={"owner"})+ filters = [TeamWalletLedger.team_id == team_id]+ total = int((await db.execute(select(func.count()).select_from(TeamWalletLedger).where(*filters))).scalar_one() or 0)+ rows = (await db.execute(select(TeamWalletLedger).where(*filters).order_by(TeamWalletLedger.id.desc()).offset((page - 1) * page_size).limit(page_size))).scalars().all()+ return {"items": [{"id": r.id, "member_id": r.actor_user_id, "delta_fen": r.delta_fen, "balance_after_fen": r.balance_after_fen, "kind": r.kind, "note": r.note, "created_at": r.created_at.isoformat() if r.created_at else None} for r in rows], "meta": {"page": page, "page_size": page_size, "total": total}}++[email protected]("/usage/summary")+async def usage_summary(team_id: int, period: str | None = Query(None, pattern=r"^\d{4}-(0[1-9]|1[0-2])$"), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ team, member = await get_team(db, team_id, user.id)+ period = period or billing_period()+ filters = [TeamMonthlyUsage.team_id == team_id, TeamMonthlyUsage.period == period]+ owner = team.owner_user_id == user.id+ if not owner:+ filters.append(TeamMonthlyUsage.user_id == user.id)+ spent, reserved = (await db.execute(select(func.coalesce(func.sum(TeamMonthlyUsage.spent_fen), 0), func.coalesce(func.sum(TeamMonthlyUsage.reserved_fen), 0)).where(*filters))).one()+ data = {"spent_fen": int(spent), "reserved_fen": int(reserved), "monthly_limit_fen": member.monthly_limit_fen, "period": period, "billing_source": "owner_personal", "billing_enabled": bool(get_settings().billing_enabled)}+ if owner:+ row = await db.get(User, user.id)+ data.update(balance_fen=int(row.balance_fen or 0) if row else 0, frozen_fen=int(row.frozen_fen or 0) if row else 0, team_monthly_limit_fen=team.monthly_limit_fen)+ return data++[email protected]("/usage/records")+async def usage_records(team_id: int, page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100), q: str | None = Query(None, max_length=100), member_id: int | None = Query(None, ge=1), project_id: int | None = Query(None, ge=1), period: str | None = Query(None, pattern=r"^\d{4}-(0[1-9]|1[0-2])$"), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ team, member = await get_team(db, team_id, user.id)+ filters = [UsageEvent.team_id == team_id]+ if team.owner_user_id != user.id:+ if member_id is not None and member_id != user.id:+ raise HTTPException(403, "只能查看本人的消费记录")+ member_id = user.id+ if member_id is not None:+ filters.append(UsageEvent.user_id == member_id)+ if project_id is not None:+ filters.append(UsageEvent.drama_project_id == project_id)+ if period:+ filters.append(TaskRun.billing_period == period)+ if q:+ text = f"%{q}%"+ filters.append(or_(UsageEvent.model.ilike(text), UsageEvent.billing_key.ilike(text), DramaProject.title.ilike(text)))+ base = select(UsageEvent, DramaProject.title).outerjoin(TaskRun, UsageEvent.task_run_id == TaskRun.id).outerjoin(DramaProject, UsageEvent.drama_project_id == DramaProject.id).where(*filters)+ total = int((await db.execute(select(func.count()).select_from(base.subquery()))).scalar_one() or 0)+ rows = (await db.execute(base.order_by(UsageEvent.id.desc()).offset((page - 1) * page_size).limit(page_size))).all()+ return {"items": [{"id": r.id, "member_id": r.user_id, "project_id": r.drama_project_id, "project_title": title, "label": billing.billing_key_label(r.billing_key), "billing_key": r.billing_key, "model": r.model or "", "amount_fen": int(r.charge_fen or 0), "total_tokens": int(r.total_tokens or 0), "created_at": r.created_at.isoformat() if r.created_at else None} for r, title in rows], "meta": {"page": page, "page_size": page_size, "total": total}}++[email protected]("/orders")+async def list_orders(team_id: int, limit: int = Query(50, ge=1, le=100), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ await get_team(db, team_id, user.id, roles={"owner"})+ await billing.close_expired_pending_orders(db, team_id=team_id)+ rows = (await db.execute(select(Order).where(Order.team_id == team_id).order_by(Order.id.desc()).limit(limit))).scalars().all()+ return {"orders": [order_out(row) for row in rows]}++[email protected]("/orders")+async def create_order(team_id: int, body: CreateOrderBody, request: Request, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ await get_team(db, team_id, user.id, roles={"owner"})+ raise HTTPException(410, "团队费用由所有者个人余额支付,请在个人账户充值")+++async def owner_order(db, team_id: int, no: str, user: User) -> Order:+ await get_team(db, team_id, user.id, roles={"owner"})+ order = (await db.execute(select(Order).where(Order.team_id == team_id, Order.out_trade_no == no).with_for_update())).scalar_one_or_none()+ if order is None:+ raise HTTPException(404, "订单不存在")+ return order++[email protected]("/orders/{out_trade_no}")+async def get_order(team_id: int, out_trade_no: str, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ await get_team(db, team_id, user.id, roles={"owner"})+ await billing.close_expired_pending_orders(db, team_id=team_id, out_trade_no=out_trade_no)+ return order_out(await owner_order(db, team_id, out_trade_no, user))++[email protected]("/orders/{out_trade_no}/close")+async def close_order(team_id: int, out_trade_no: str, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ order = await owner_order(db, team_id, out_trade_no, user)+ if order.status == "paid":+ raise HTTPException(400, "已支付订单无法关闭")+ order.status = "closed"+ await db.commit()+ return {"out_trade_no": out_trade_no, "status": "closed"}diff --git a/backend/app/api/team_content.py b/backend/app/api/team_content.pynew file mode 100644index 0000000..5a970cf--- /dev/null+++ b/backend/app/api/team_content.py@@ -0,0 +1,101 @@+"""团队项目列表、个人项目迁入与团队资产副本接口。"""+from typing import Literal++from fastapi import APIRouter, Depends, Query, Request+from pydantic import BaseModel, ConfigDict, Field+from sqlalchemy.ext.asyncio import AsyncSession++from app.database import get_db+from app.deps import get_current_user+from app.models import User+from app.schemas_drama import DramaAssetOut, DramaProjectCreate, DramaProjectOut+from app.services.teams import content++router = APIRouter(prefix="/teams/{team_id}", tags=["team-content"])+personal_router = APIRouter(prefix="/drama", tags=["drama-assets"])+++class TeamProjectCreate(BaseModel):+ """真实项目创意由用户提供,不以占位文本冒充。"""+ model_config = ConfigDict(str_strip_whitespace=True, extra="forbid")+ title: str = Field(min_length=1, max_length=200)+ description: str = Field(default="", max_length=512)+ source: str = Field(min_length=20, max_length=100000)+ episode_count: int = Field(default=12, strict=True, ge=1, le=120)+ workflow: Literal["script", "canvas"] = "script"+++class TeamAssetCopy(BaseModel):+ """只接收目标项目,源内容和来源标记完全由数据库取得。"""+ model_config = ConfigDict(extra="forbid")+ project_id: int = Field(strict=True, gt=0)++[email protected]("/projects")+async def list_projects(team_id: int, page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100), q: str = Query("", max_length=200), status: Literal["draft", "producing", "completed"] | None = None, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ """团队项目服务端搜索、状态筛选和分页。"""+ return await content.list_projects(db, team_id, user.id, page, page_size, q, status)++[email protected]("/assets")+async def list_assets(team_id: int, page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100), q: str = Query("", max_length=200), type: Literal["character", "scene", "prop", "voice"] | None = None, project_id: int | None = Query(None, gt=0), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ """仅返回当前团队可访问项目的角色、场景、道具和音色。"""+ return await content.list_assets(db, team_id, user.id, page, page_size, q, type, project_id)++[email protected]("/projects", response_model=DramaProjectOut, status_code=201)+async def create_project(team_id: int, body: TeamProjectCreate, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> DramaProjectOut:+ """复用已有漫剧创建流程,绑定团队但不自动开始收费生成。"""+ from app.api.drama.projects import create_project as create_drama_project+ return await create_drama_project(DramaProjectCreate(team_id=team_id, **body.model_dump()), db=db, user=user, scope_team_id=team_id)++[email protected]("/transferable-projects")+async def transferable_projects(team_id: int, page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ """列出本人个人项目及当前不能迁入的具体原因。"""+ return await content.transferable_projects(db, team_id, user.id, page, page_size)++[email protected]("/projects/{project_id}/transfer", response_model=DramaProjectOut)+async def transfer_project(team_id: int, project_id: int, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> DramaProjectOut:+ """迁入不改变原项目 ID 和任何历史计费账户。"""+ from app.api.drama.projects import get_project+ project, copier = await content.transfer_project(db, team_id, user.id, project_id)+ try:+ await db.commit()+ except Exception:+ await db.rollback()+ if copier:+ copier.cleanup()+ raise+ return await get_project(project.id, db=db, user=user)++[email protected]("/assets/{asset_id}/copy", response_model=DramaAssetOut, status_code=201)+async def copy_asset(team_id: int, asset_id: int, body: TeamAssetCopy, request: Request, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> DramaAssetOut:+ """目标 asset:0 租约通过后创建独立副本,不下载任意公网地址。"""+ from fastapi import HTTPException+ try:+ version = int(request.headers.get("X-Edit-Version", "0"))+ except ValueError as exc:+ raise HTTPException(422, "无效的编辑版本") from exc+ asset, copier = await content.copy_asset(db, team_id, user.id, asset_id, body.project_id, request.headers.get("X-Edit-Session", ""), request.headers.get("X-Edit-Token", ""), version)+ try:+ await db.commit()+ except Exception:+ await db.rollback()+ copier.cleanup()+ raise+ return DramaAssetOut.model_validate(asset)+++@personal_router.post("/assets/{asset_id}/copy", response_model=DramaAssetOut, status_code=201)+async def copy_owned_asset(asset_id: int, body: TeamAssetCopy, request: Request, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> DramaAssetOut:+ """个人副本兼容入口;团队源目标仍必须同队并持目标编辑租约。"""+ from fastapi import HTTPException+ from app.models_drama import DramaProject++ target = await db.get(DramaProject, body.project_id)+ if not target:+ raise HTTPException(404, "目标项目不存在")+ return await copy_asset(target.team_id, asset_id, body, request, db=db, user=user)diff --git a/backend/app/api/team_edit_locks.py b/backend/app/api/team_edit_locks.pynew file mode 100644index 0000000..5990b88--- /dev/null+++ b/backend/app/api/team_edit_locks.py@@ -0,0 +1,59 @@+"""团队编辑占用 HTTP 接口。"""+from typing import Literal++from fastapi import APIRouter, Depends, Query+from pydantic import BaseModel, Field+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.database import get_db+from app.deps import get_current_user+from app.models import User+from app.models_team_locks import TeamEditLock+from app.services.teams.access import get_team+from app.services.teams.edit_locks import acquire_lock, lock_view, renew_lock++router = APIRouter(prefix="/teams/{team_id}/edit-locks", tags=["teams"])+++class LockAcquire(BaseModel):+ """会话标识属于当前标签页,真实用户来自认证凭证。"""+ project_id: int = Field(gt=0)+ resource_type: Literal["structure", "script", "episode", "asset", "canvas"]+ resource_id: int = Field(default=0, ge=0)+ session_id: str = Field(min_length=1, max_length=80)+ force: bool = False+++class LockToken(BaseModel):+ """续租与释放都要证明持有原始凭证。"""+ token: str = Field(min_length=20, max_length=100)+ session_id: str = Field(min_length=1, max_length=80)++[email protected]("/acquire")+async def acquire(team_id: int, body: LockAcquire, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ """获取资源租约或由负责人接管人工占用。"""+ return await acquire_lock(db, team_id, user.id, body.project_id, body.resource_type, body.resource_id, body.session_id, force=body.force)++[email protected]("/renew")+async def renew(team_id: int, body: LockToken, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ """续租保持原 token/版本,过期后需重新获取。"""+ return await renew_lock(db, team_id, user.id, body.token, body.session_id)++[email protected]("/release")+async def release(team_id: int, body: LockToken, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ """释放当前标签页持有的人工资源占用。"""+ return await renew_lock(db, team_id, user.id, body.token, body.session_id, release=True)+++async def list_locks(team_id: int, project_id: int = Query(gt=0), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> dict:+ """查看团队项目当前人工占用,不暴露其他会话凭证。"""+ from datetime import UTC, datetime++ await get_team(db, team_id, user.id)+ rows = (await db.execute(select(TeamEditLock).where(TeamEditLock.team_id == team_id, TeamEditLock.project_id == project_id, TeamEditLock.expires_at > datetime.now(UTC)))).scalars().all()+ return {"items": [await lock_view(db, row) for row in rows]}diff --git a/backend/app/api/teams.py b/backend/app/api/teams.pynew file mode 100644index 0000000..4683cee--- /dev/null+++ b/backend/app/api/teams.py@@ -0,0 +1,199 @@+"""团队核心路由:身份来自现有认证,权限与变更交由团队服务。"""+from __future__ import annotations++from typing import Literal++from fastapi import APIRouter, Depends, Query, Request, Response+from sqlalchemy.ext.asyncio import AsyncSession++from app.database import get_db+from app.deps import get_current_user+from app.models import User+from app.schemas_teams import (+ TeamActivityOut, TeamCreate, TeamInvitationCreated, TeamInvitationInspect,+ TeamInvitationOut, TeamInvitationToken, TeamInviteCreate, TeamMemberOut,+ TeamMemberPatch, TeamPage, TeamSummary, TeamTransfer, TeamUpdate,+)+from app.services.teams import invitations, management, queries+from app.services.teams.access import get_team++router = APIRouter(prefix="/teams", tags=["teams"])+invitation_router = APIRouter(prefix="/team-invitations", tags=["team-invitations"])++[email protected]("", response_model=TeamPage[TeamSummary])+async def list_teams(+ page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100),+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamPage[TeamSummary]:+ """分页列出当前用户有效加入的团队。"""+ return await queries.list_teams(db, user.id, page, page_size)++[email protected]("", response_model=TeamSummary, status_code=201)+async def create_team(+ body: TeamCreate, response: Response,+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamSummary:+ """创建由所有者个人账户支付费用的团队。"""+ team = await management.create_team(db, user.id, body)+ await db.commit()+ response.headers["Location"] = f"/api/teams/{team.id}"+ return await queries.team_summary(db, team.id, user.id)++[email protected]("/{team_id}", response_model=TeamSummary)+async def get_team_summary(+ team_id: int, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamSummary:+ """团队摘要不暴露其他空间的数据。"""+ return await queries.team_summary(db, team_id, user.id)++[email protected]("/{team_id}", response_model=TeamSummary)+async def update_team(+ team_id: int, body: TeamUpdate,+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamSummary:+ """所有者修改团队资料或月度消费上限。"""+ await management.update_team(db, team_id, user.id, body)+ await db.commit()+ return await queries.team_summary(db, team_id, user.id)++[email protected]("/{team_id}", status_code=204)+async def delete_team(+ team_id: int, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> Response:+ """仅所有者解散团队,历史作品与账单保留归档。"""+ await management.delete_team(db, team_id, user.id)+ await db.commit()+ return Response(status_code=204)++[email protected]("/{team_id}/members", response_model=TeamPage[TeamMemberOut])+async def list_members(+ team_id: int, q: str = Query("", max_length=254), role: Literal["owner", "admin", "member"] | None = None,+ page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100),+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamPage[TeamMemberOut]:+ """成员列表由服务端筛选、分页并遮蔽不可见财务字段。"""+ return await queries.list_members(db, team_id, user.id, page, page_size, q, role)++[email protected]("/{team_id}/members/{user_id}", response_model=TeamMemberOut)+async def update_member(+ team_id: int, user_id: int, body: TeamMemberPatch,+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamMemberOut:+ """所有者调整成员月额度或非所有者角色。"""+ await management.update_member(db, team_id, user.id, user_id, body)+ await db.commit()+ team, viewer = await get_team(db, team_id, user.id)+ member = await management.active_member(db, team_id, user_id)+ target = await db.get(User, user_id)+ return (await queries.member_outputs(db, team, viewer, [(member, target)]))[0]++[email protected]("/{team_id}/members/{user_id}")+async def remove_member(+ team_id: int, user_id: int,+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> dict[str, bool]:+ """软移除成员,同事务清理未开始任务与人工编辑锁。"""+ await management.remove_member(db, team_id, user.id, user_id)+ await db.commit()+ return {"ok": True}++[email protected]("/{team_id}/leave")+async def leave_team(+ team_id: int, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> dict[str, bool]:+ """当前成员退出团队,内容和历史消费继续保留。"""+ await management.leave_team(db, team_id, user.id)+ await db.commit()+ return {"ok": True}++[email protected]("/{team_id}/transfer-ownership", response_model=TeamSummary)+async def transfer_ownership(+ team_id: int, body: TeamTransfer,+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamSummary:+ """事务内转移唯一所有权,原所有者成为管理员。"""+ await management.transfer_ownership(db, team_id, user.id, body.user_id)+ await db.commit()+ return await queries.team_summary(db, team_id, user.id)++[email protected]("/{team_id}/invitations", response_model=TeamPage[TeamInvitationOut])+async def list_invitations(+ team_id: int, page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100),+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamPage[TeamInvitationOut]:+ """管理者分页查看邀请状态,列表不包含可使用的令牌。"""+ return await invitations.list_invitations(db, team_id, user.id, page, page_size)++[email protected]("/{team_id}/invitations", response_model=TeamInvitationCreated, status_code=201)+async def create_invitation(+ team_id: int, body: TeamInviteCreate, request: Request,+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamInvitationCreated:+ """签发七天邀请,提交后尝试邮件;失败仍返回可复制链接。"""+ team, invite, token = await invitations.create_invitation(db, team_id, user.id, str(body.email))+ await db.commit()+ return await invitations.invitation_result(team, invite, token, frontend_base=invitations.invitation_frontend_base(request.headers.get("origin")))++[email protected]("/{team_id}/invitations/{invite_id}/revoke")+async def revoke_invitation(+ team_id: int, invite_id: int,+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> dict[str, bool]:+ """撤回未被消费的邀请。"""+ await invitations.revoke_invitation(db, team_id, user.id, invite_id)+ await db.commit()+ return {"ok": True}++[email protected]("/{team_id}/invitations/{invite_id}/resend", response_model=TeamInvitationCreated)+async def resend_invitation(+ team_id: int, invite_id: int, request: Request,+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamInvitationCreated:+ """重发时旧令牌立即失效,新令牌从本次起有效七天。"""+ team, invite, token = await invitations.resend_invitation(db, team_id, user.id, invite_id)+ await db.commit()+ return await invitations.invitation_result(team, invite, token, frontend_base=invitations.invitation_frontend_base(request.headers.get("origin")))++[email protected]("/{team_id}/activities", response_model=TeamPage[TeamActivityOut])+async def list_activities(+ team_id: int, page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100),+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamPage[TeamActivityOut]:+ """分页读取团队操作动态。"""+ return await queries.list_activities(db, team_id, user.id, page, page_size)+++@invitation_router.post("/inspect", response_model=TeamInvitationInspect)+async def inspect_invitation(+ body: TeamInvitationToken,+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamInvitationInspect:+ """邮箱匹配的登录用户检查邀请,不提前消费令牌。"""+ team, invite = await invitations.check_invitation(db, body.token, user)+ return TeamInvitationInspect(team_name=team.name, email=invite.email, expires_at=invite.expires_at)+++@invitation_router.post("/accept", response_model=TeamSummary)+async def accept_invitation(+ body: TeamInvitationToken,+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> TeamSummary:+ """一次性接受邮箱绑定邀请,并激活普通成员身份。"""+ team = await invitations.accept_invitation(db, body.token, user)+ await db.commit()+ return await queries.team_summary(db, team.id, user.id)diff --git a/backend/app/models_team_billing.py b/backend/app/models_team_billing.pynew file mode 100644index 0000000..307fae5--- /dev/null+++ b/backend/app/models_team_billing.py@@ -0,0 +1,42 @@+"""月度成员用量与仅供历史兼容的团队钱包流水。"""+from datetime import datetime+from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint, func, text+from sqlalchemy.orm import Mapped, mapped_column+from app.database import Base+++class TeamWallet(Base):+ __tablename__ = "team_wallets"+ team_id: Mapped[int] = mapped_column(ForeignKey("teams.id"), primary_key=True)+ balance_fen: Mapped[int] = mapped_column(Integer, default=0)+ frozen_fen: Mapped[int] = mapped_column(Integer, default=0)+++class TeamWalletLedger(Base):+ __tablename__ = "team_wallet_ledger"+ __table_args__ = (+ Index("uq_team_admin_adjust_request", "team_id", "ref_id", unique=True,+ postgresql_where=text("ref_type = 'admin_adjust'"),+ sqlite_where=text("ref_type = 'admin_adjust'")),+ )+ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ team_id: Mapped[int] = mapped_column(ForeignKey("teams.id"), index=True)+ actor_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)+ delta_fen: Mapped[int] = mapped_column(Integer)+ balance_after_fen: Mapped[int] = mapped_column(Integer)+ kind: Mapped[str] = mapped_column(String(32))+ ref_type: Mapped[str] = mapped_column(String(32), default="")+ ref_id: Mapped[str] = mapped_column(String(64), default="")+ note: Mapped[str] = mapped_column(String(255), default="")+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())+++class TeamMonthlyUsage(Base):+ __tablename__ = "team_monthly_usage"+ __table_args__ = (UniqueConstraint("team_id", "user_id", "period", name="uq_team_monthly_member"),)+ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ team_id: Mapped[int] = mapped_column(ForeignKey("teams.id"), index=True)+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)+ period: Mapped[str] = mapped_column(String(7), index=True)+ spent_fen: Mapped[int] = mapped_column(Integer, default=0)+ reserved_fen: Mapped[int] = mapped_column(Integer, default=0)diff --git a/backend/app/models_team_locks.py b/backend/app/models_team_locks.pynew file mode 100644index 0000000..4521ea7--- /dev/null+++ b/backend/app/models_team_locks.py@@ -0,0 +1,27 @@+"""团队人工编辑租约;数据库行和递增代次共同阻止失锁页面覆盖内容。"""+from __future__ import annotations++from datetime import datetime++from sqlalchemy import DateTime, ForeignKey, Integer, String, UniqueConstraint+from sqlalchemy.orm import Mapped, mapped_column++from app.database import Base+++class TeamEditLock(Base):+ """资源占用行长期复用,释放后保留 fencing version。"""++ __tablename__ = "team_edit_locks"+ __table_args__ = (UniqueConstraint("project_id", "resource_type", "resource_id", name="uq_team_edit_resource"),)++ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ team_id: Mapped[int] = mapped_column(ForeignKey("teams.id"), index=True)+ project_id: Mapped[int] = mapped_column(ForeignKey("drama_projects.id", ondelete="CASCADE"), index=True)+ resource_type: Mapped[str] = mapped_column(String(16))+ resource_id: Mapped[int] = mapped_column(Integer, default=0)+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))+ session_id: Mapped[str] = mapped_column(String(80))+ token_hash: Mapped[str] = mapped_column(String(64), index=True)+ version: Mapped[int] = mapped_column(Integer, default=1)+ expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)diff --git a/backend/app/models_teams.py b/backend/app/models_teams.pynew file mode 100644index 0000000..d5122b4--- /dev/null+++ b/backend/app/models_teams.py@@ -0,0 +1,74 @@+"""团队、成员、一次性邀请与审计动态的持久化模型。"""+from __future__ import annotations++from datetime import datetime++from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, String, UniqueConstraint, func, text+from sqlalchemy.orm import Mapped, mapped_column++from app.database import Base+++class Team(Base):+ """独立团队空间;owner_user_id 是所有权的权威来源。"""++ __tablename__ = "teams"++ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ name: Mapped[str] = mapped_column(String(40))+ description: Mapped[str] = mapped_column(String(180), default="")+ color: Mapped[str] = mapped_column(String(7), default="#435c4b")+ owner_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)+ monthly_limit_fen: Mapped[int | None] = mapped_column(Integer, nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())+++class TeamMember(Base):+ """成员关系软失效,退出或重新加入不会删除历史预算归属。"""++ __tablename__ = "team_members"+ __table_args__ = (+ UniqueConstraint("team_id", "user_id", name="uq_team_member"),+ CheckConstraint("role IN ('owner', 'admin', 'member')", name="ck_team_member_role"),+ CheckConstraint("monthly_limit_fen IS NULL OR monthly_limit_fen >= 0", name="ck_team_member_limit"),+ Index("uq_team_active_owner", "team_id", unique=True, postgresql_where=text("active = true AND role = 'owner'"), sqlite_where=text("active = 1 AND role = 'owner'")),+ )++ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ team_id: Mapped[int] = mapped_column(ForeignKey("teams.id"), index=True)+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)+ role: Mapped[str] = mapped_column(String(16), default="member")+ active: Mapped[bool] = mapped_column(Boolean, default=True, index=True)+ monthly_limit_fen: Mapped[int | None] = mapped_column(Integer, nullable=True)+ joined_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())+++class TeamInvitation(Base):+ """仅保存高熵邀请令牌的 SHA-256;明文仅在签发响应和邮件中使用。"""++ __tablename__ = "team_invitations"++ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ team_id: Mapped[int] = mapped_column(ForeignKey("teams.id"), index=True)+ email: Mapped[str] = mapped_column(String(255), index=True)+ token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)+ created_by: Mapped[int] = mapped_column(ForeignKey("users.id"))+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())+ expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)+ accepted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+++class TeamActivity(Base):+ """不随项目删除的团队操作记录;不包含邀请令牌或密钥。"""++ __tablename__ = "team_activities"++ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ team_id: Mapped[int] = mapped_column(ForeignKey("teams.id"), index=True)+ actor_user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)+ action: Mapped[str] = mapped_column(String(64))+ subject: Mapped[str] = mapped_column(String(255))+ project_id: Mapped[int | None] = mapped_column(ForeignKey("drama_projects.id", ondelete="SET NULL"), nullable=True, index=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())diff --git a/backend/app/schemas_admin_teams.py b/backend/app/schemas_admin_teams.pynew file mode 100644index 0000000..758dcce--- /dev/null+++ b/backend/app/schemas_admin_teams.py@@ -0,0 +1,139 @@+"""平台管理员团队与钱包契约,金额均以整数分传递。"""+from datetime import datetime+from typing import Literal+from uuid import UUID++from pydantic import BaseModel, ConfigDict, Field, model_validator++from app.schemas_common import PageMeta+++class AdminTeamOut(BaseModel):+ """团队归属、规模及独立钱包的只读快照。"""+ id: int+ name: str+ description: str+ color: str+ owner_user_id: int+ owner_nickname: str+ owner_email: str+ member_count: int+ project_count: int+ balance_fen: int+ frozen_fen: int+ monthly_limit_fen: int | None+ billing_source: Literal["owner_personal"] = "owner_personal"+ month_reserved_fen: int+ month_spent_fen: int+ total_spent_fen: int+ period: str+ created_at: datetime+++class AdminTeamPage(BaseModel):+ """服务端筛选后的团队分页。"""+ items: list[AdminTeamOut]+ meta: PageMeta+++class AdminTeamMemberOut(BaseModel):+ """成员关系及选定自然月消费,包括已退出的历史成员。"""+ user_id: int+ nickname: str+ email: str+ role: Literal["owner", "admin", "member"]+ active: bool+ monthly_limit_fen: int | None+ spent_fen: int+ reserved_fen: int+ joined_at: datetime+++class AdminTeamMemberPage(BaseModel):+ """成员分页与消费统计月份。"""+ items: list[AdminTeamMemberOut]+ meta: PageMeta+ period: str+++class AdminTeamUsageOut(BaseModel):+ """团队模型调用明细;明确区分已结算与待结算。"""+ id: int+ user_id: int+ user_nickname: str+ user_email: str+ project_id: int | None+ project_title: str | None+ task_run_id: int | None+ billing_key: str+ billing_label: str+ model: str+ total_tokens: int+ charge_fen: int+ settled: bool+ created_at: datetime+++class AdminTeamUsageSummary(BaseModel):+ """全部筛选结果的统计,排除待结算金额,不受当前页影响。"""+ record_count: int+ settled_charge_fen: int+++class AdminTeamUsagePage(BaseModel):+ """消费分页与相同筛选条件下的合计。"""+ items: list[AdminTeamUsageOut]+ meta: PageMeta+ summary: AdminTeamUsageSummary+++class AdminTeamBalanceAdjustmentInput(BaseModel):+ """按增减金额调账;请求标识用于安全重试,不接受零金额或隐式类型转换。"""+ model_config = ConfigDict(str_strip_whitespace=True, extra="forbid")+ delta_fen: int = Field(strict=True, ge=-100_000_000, le=100_000_000)+ note: str = Field(min_length=1, max_length=180)+ request_id: UUID++ @model_validator(mode="after")+ def nonzero_amount(self) -> "AdminTeamBalanceAdjustmentInput":+ """零金额不能产生无意义的财务流水。"""+ if self.delta_fen == 0:+ raise ValueError("调账金额不能为零")+ return self+++class AdminTeamBalanceAdjustmentOut(BaseModel):+ """原调账流水与当前可用余额;重试不会重复记账。"""+ ledger_id: int+ delta_fen: int+ balance_after_fen: int+ balance_fen: int+ frozen_fen: int+ replayed: bool+++class AdminTeamWalletLedgerOut(BaseModel):+ """独立团队钱包流水,明确记录平台调账操作人。"""+ id: int+ actor_user_id: int+ operator_nickname: str+ operator_email: str+ delta_fen: int+ balance_after_fen: int+ kind: str+ ref_type: str+ ref_id: str+ note: str+ created_at: datetime+++class AdminTeamWalletLedgerPage(BaseModel):+ """钱包流水服务端分页。"""+ items: list[AdminTeamWalletLedgerOut]+ meta: PageMeta+++class AdminTeamBudgetInput(BaseModel):+ """空值不限额,0 停止新消费;严格整数分。"""+ model_config = ConfigDict(extra="forbid")+ monthly_limit_fen: int | None = Field(strict=True, ge=0, le=100_000_000)diff --git a/backend/app/schemas_teams.py b/backend/app/schemas_teams.pynew file mode 100644index 0000000..a25f632--- /dev/null+++ b/backend/app/schemas_teams.py@@ -0,0 +1,150 @@+"""团队核心 API 数据契约;所有金额使用整数分。"""+from __future__ import annotations++from datetime import datetime+from typing import Generic, Literal, TypeVar++from pydantic import BaseModel, ConfigDict, EmailStr, Field, model_validator++from app.schemas_common import PageMeta++TeamRole = Literal["owner", "admin", "member"]+T = TypeVar("T")+++class TeamInput(BaseModel):+ """输入统一去除首尾空格,拒绝未知字段。"""++ model_config = ConfigDict(str_strip_whitespace=True, extra="forbid")+++class TeamCreate(TeamInput):+ """创建独立团队空间。"""++ name: str = Field(min_length=1, max_length=40)+ description: str = Field(default="", max_length=180)+ color: str = Field(default="#435c4b", pattern=r"^#[0-9a-fA-F]{6}$")+++class TeamUpdate(TeamInput):+ """部分修改团队资料;显式 null 不是有效资料值。"""++ name: str | None = Field(default=None, min_length=1, max_length=40)+ description: str | None = Field(default=None, max_length=180)+ color: str | None = Field(default=None, pattern=r"^#[0-9a-fA-F]{6}$")+ monthly_limit_fen: int | None = Field(default=None, strict=True, ge=0, le=100_000_000)++ @model_validator(mode="after")+ def validate_patch(self) -> "TeamUpdate":+ """防止 null 擦除非空字段或空补丁写入无意义动态。"""+ if not self.model_fields_set or any(getattr(self, key) is None for key in self.model_fields_set if key != "monthly_limit_fen"):+ raise ValueError("请提供有效的团队资料")+ return self+++class TeamSummary(BaseModel):+ """当前用户可见的团队摘要。"""++ id: int+ name: str+ description: str+ color: str+ created_at: datetime+ updated_at: datetime+ my_role: TeamRole+ viewer_id: int+ member_count: int = 0+ project_count: int = 0+ asset_count: int = 0+++class TeamPage(BaseModel, Generic[T]):+ """团队所有列表共用服务端分页形态。"""++ items: list[T]+ meta: PageMeta+++class TeamMemberOut(BaseModel):+ """非所有者查看他人时,财务字段返回 null。"""++ id: int+ nickname: str+ email: str+ avatar_url: str+ role: TeamRole+ monthly_limit_fen: int | None+ spent_fen: int | None+ reserved_fen: int | None+ joined_at: datetime+++class TeamMemberPatch(TeamInput):+ """仅所有者可修改非所有者角色和月度上限。"""++ role: Literal["admin", "member"] | None = None+ monthly_limit_fen: int | None = Field(default=None, strict=True, ge=0, le=100_000_000)++ @model_validator(mode="after")+ def validate_patch(self) -> "TeamMemberPatch":+ """null 额度表示不限额;null 角色和空补丁均无效。"""+ if not self.model_fields_set or ("role" in self.model_fields_set and self.role is None):+ raise ValueError("请提供有效的成员角色或额度")+ return self+++class TeamTransfer(TeamInput):+ """所有权只能转移给仍在团队内的其他成员。"""++ user_id: int = Field(strict=True, gt=0)+++class TeamInviteCreate(TeamInput):+ """邮箱绑定的普通成员邀请。"""++ email: EmailStr = Field(max_length=254)+++class TeamInvitationOut(BaseModel):+ """邀请列表不暴露原始令牌或哈希。"""++ id: int+ email: str+ created_at: datetime+ expires_at: datetime+ status: Literal["pending", "accepted", "revoked", "expired"]+++class TeamInvitationCreated(BaseModel):+ """签发或轮换后一次性返回明文供管理员复制。"""++ invitation: TeamInvitationOut+ token: str+ accept_url: str+ email_sent: bool+++class TeamInvitationToken(TeamInput):+ """令牌置于 POST 正文,避免落入接口 URL 日志。"""++ token: str = Field(min_length=20, max_length=256)+++class TeamInvitationInspect(BaseModel):+ """匹配邮箱的已登录用户可看到加入前必要信息。"""++ team_name: str+ email: str+ expires_at: datetime+++class TeamActivityOut(BaseModel):+ """团队动态保留实际操作者,允许原项目已删除。"""++ id: int+ actor_user_id: int+ actor_nickname: str+ action: str+ subject: str+ project_id: int | None+ created_at: datetimediff --git a/backend/app/services/billing/team.py b/backend/app/services/billing/team.pynew file mode 100644index 0000000..e042d0c--- /dev/null+++ b/backend/app/services/billing/team.py@@ -0,0 +1,142 @@+"""Team reservations use the same estimate/freeze/actual settlement lifecycle."""+from __future__ import annotations+from datetime import UTC, datetime, timedelta, timezone+from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession+from app.config import get_settings+from app.models import UsageEvent+from app.models_tasks import TaskRun+from app.models_team_billing import TeamMonthlyUsage++SHANGHAI = timezone(timedelta(hours=8))+ACTIVE = ("pending", "leased", "running", "awaiting_poll", "awaiting_review", "cancel_requested")+++def billing_period(now: datetime | None = None) -> str:+ return (now or datetime.now(UTC)).astimezone(SHANGHAI).strftime("%Y-%m")+++async def monthly_usage(db: AsyncSession, team_id: int, user_id: int, period: str) -> TeamMonthlyUsage:+ # Wallet row must already be locked, serializing creation of the first monthly row.+ row = (await db.execute(select(TeamMonthlyUsage).where(TeamMonthlyUsage.team_id == team_id, TeamMonthlyUsage.user_id == user_id, TeamMonthlyUsage.period == period).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()+ if row is None:+ row = TeamMonthlyUsage(team_id=team_id, user_id=user_id, period=period, spent_fen=0, reserved_fen=0)+ db.add(row)+ await db.flush()+ return row+++async def check_team_budget(db: AsyncSession, task: TaskRun, estimate: int, *, count: int = 1, reserve: bool = False) -> dict:+ """锁定所有者钱包,跨团队及个人任务共享余额承诺;检查两级月额度。"""+ from app.services.teams.access import get_team+ from app.services.billing.settlement import _lock_user, pending_task_commitment_fen+ team, member = await get_team(db, int(task.team_id), int(task.requested_by), lock=True)+ wallet = await _lock_user(db, team.owner_user_id)+ if wallet is None:+ raise ValueError("团队所有者不存在")+ period = billing_period()+ task.billing_payer_user_id = team.owner_user_id+ task.billing_enabled_snapshot = bool(get_settings().billing_enabled)+ task.billing_period = period+ if not task.billing_enabled_snapshot or task.task_type == "episode_compose":+ task.billing_status = "skipped"+ return {"unit_estimate_fen": 0, "requested_total_fen": 0, "pending_commitment_fen": 0, "required_total_fen": 0, "balance_fen": int(wallet.balance_fen or 0)}+ additional = max(0, int(estimate)) * max(1, int(count))+ pending = await pending_task_commitment_fen(db, wallet.id, exclude_task_id=task.id)+ if int(wallet.balance_fen or 0) < pending + additional:+ raise ValueError("团队所有者余额不足,请联系所有者为个人账户充值")+ spent, reserved = (await db.execute(select(func.coalesce(func.sum(TeamMonthlyUsage.spent_fen), 0), func.coalesce(func.sum(TeamMonthlyUsage.reserved_fen), 0)).where(TeamMonthlyUsage.team_id == task.team_id, TeamMonthlyUsage.period == period))).one()+ if team.monthly_limit_fen is not None and (team.monthly_limit_fen == 0 or spent + reserved + additional > team.monthly_limit_fen):+ raise ValueError("已达到团队月度消费额度,请联系所有者调整额度")+ usage = await monthly_usage(db, int(task.team_id), int(task.requested_by), period)+ limit = member.monthly_limit_fen+ if limit is not None and (int(limit) == 0 or int(usage.spent_fen or 0) + int(usage.reserved_fen or 0) + additional > int(limit)):+ raise ValueError("已达到成员月度消费额度,请联系团队所有者调整额度")+ visible_pending = pending if team.owner_user_id == task.requested_by else int(usage.reserved_fen or 0)+ if reserve:+ usage.reserved_fen = int(usage.reserved_fen or 0) + additional+ task.billing_status = "reserved"+ return {"unit_estimate_fen": int(estimate), "requested_total_fen": additional, "pending_commitment_fen": visible_pending, "required_total_fen": visible_pending + additional, "balance_fen": int(wallet.balance_fen or 0)}+++async def freeze_team_task(db: AsyncSession, task: TaskRun) -> int:+ """使用受理时的钱包;历史任务继续原钱包生命周期。"""+ if task.billing_payer_user_id is None:+ from app.services.billing.team_legacy import freeze_team_task as legacy_freeze+ return await legacy_freeze(db, task)+ if task.billing_status in ("frozen", "settled"):+ return int(task.billing_estimate_fen or 0)+ if task.billing_enabled_snapshot is False or task.billing_status == "skipped":+ task.billing_status = "skipped"+ task.billing_estimate_fen = 0+ await db.flush()+ return 0+ from app.services.billing.settlement import _lock_user+ wallet = await _lock_user(db, int(task.billing_payer_user_id))+ if wallet is None:+ raise ValueError("付款所有者不存在")+ need = int(task.billing_estimate_fen or 0)+ if int(wallet.balance_fen or 0) < need:+ raise ValueError("团队所有者余额不足,请联系所有者为个人账户充值")+ wallet.frozen_fen = int(wallet.frozen_fen or 0) + need+ task.billing_status = "frozen"+ await owner_ledger(db, wallet, task, -need, "freeze", ref_type="task_run", ref_id=str(task.id), note=f"freeze:{task.domain}/{task.task_type}")+ await db.flush()+ return need+++async def settle_team_task(db: AsyncSession, task: TaskRun) -> dict[str, int]:+ """按实际用量扣费退冻结,操作者与付款所有者分别留痕。"""+ if task.billing_payer_user_id is None:+ from app.services.billing.team_legacy import settle_team_task as legacy_settle+ return await legacy_settle(db, task)+ if task.billing_status == "settled":+ return {"charged": int(task.billing_charged_fen or 0), "refunded": int(task.billing_refunded_fen or 0)}+ events = list((await db.execute(select(UsageEvent).where(UsageEvent.task_run_id == task.id, UsageEvent.settled.is_(False)))).scalars().all())+ if events:+ from app.services.billing.newapi_bill import apply_newapi_bills+ # Match personal settlement: failed upstream reconciliation does not lose recorded costs.+ try:+ await apply_newapi_bills(events)+ except Exception:+ import logging+ logging.getLogger(__name__).exception("Team upstream reconciliation failed task=%s", task.id)+ from app.services.billing.settlement import _lock_user+ wallet = await _lock_user(db, int(task.billing_payer_user_id))+ if wallet is None:+ raise ValueError("付款所有者不存在")+ disabled = task.billing_enabled_snapshot is False or task.billing_status == "skipped"+ charged = 0 if disabled else sum(int(e.charge_fen or 0) for e in events)+ for event in events:+ event.user_id = int(task.requested_by)+ event.team_id = int(task.team_id)+ event.billing_payer_user_id = task.billing_payer_user_id+ if disabled:+ event.charge_fen = 0+ event.settled = True+ reserved = int(task.billing_estimate_fen or 0)+ if not disabled:+ usage = await monthly_usage(db, int(task.team_id), int(task.requested_by), task.billing_period or billing_period(task.created_at))+ usage.reserved_fen = max(0, int(usage.reserved_fen or 0) - reserved)+ usage.spent_fen = int(usage.spent_fen or 0) + charged+ frozen = reserved if task.billing_status == "frozen" else 0+ refund = max(0, frozen - charged)+ wallet.frozen_fen = max(0, int(wallet.frozen_fen or 0) - frozen)+ if refund:+ await owner_ledger(db, wallet, task, refund, "unfreeze", ref_type="task_run", ref_id=str(task.id), note="refund_unused_freeze")+ extra = max(0, charged - frozen)+ if extra:+ await owner_ledger(db, wallet, task, -extra, "settle", ref_type="task_run", ref_id=str(task.id), note="settle_overage" if frozen else "settle_direct")+ if not disabled:+ await owner_ledger(db, wallet, task, 0, "settle", ref_type="task_run", ref_id=str(task.id), note=f"charged={charged} freeze={frozen} refund={refund}")+ task.billing_status = "settled"+ task.billing_charged_fen = charged+ task.billing_refunded_fen = refund+ await db.flush()+ return {"charged": charged, "refunded": refund}+++async def owner_ledger(db, wallet, task, delta, kind, *, ref_type, ref_id, note=""):+ """个人流水注明团队和实际操作成员。"""+ from app.services.billing.settlement import _ledger+ await _ledger(db, wallet, delta, kind, ref_type=ref_type, ref_id=ref_id, note=f"team:{task.team_id} actor:{task.requested_by} {note}")diff --git a/backend/app/services/billing/team_legacy.py b/backend/app/services/billing/team_legacy.pynew file mode 100644index 0000000..56db38f--- /dev/null+++ b/backend/app/services/billing/team_legacy.py@@ -0,0 +1,102 @@+"""Team reservations use the same estimate/freeze/actual settlement lifecycle."""+from __future__ import annotations+from datetime import UTC, datetime, timedelta, timezone+from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession+from app.config import get_settings+from app.models import UsageEvent+from app.models_tasks import TaskRun+from app.models_team_billing import TeamMonthlyUsage, TeamWallet, TeamWalletLedger++SHANGHAI = timezone(timedelta(hours=8))+ACTIVE = ("pending", "leased", "running", "awaiting_poll", "awaiting_review", "cancel_requested")+++def billing_period(now: datetime | None = None) -> str:+ return (now or datetime.now(UTC)).astimezone(SHANGHAI).strftime("%Y-%m")+++async def lock_wallet(db: AsyncSession, team_id: int) -> TeamWallet:+ wallet = (await db.execute(select(TeamWallet).where(TeamWallet.team_id == team_id).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()+ if wallet is None:+ raise ValueError("团队钱包不存在")+ return wallet+++async def monthly_usage(db: AsyncSession, team_id: int, user_id: int, period: str) -> TeamMonthlyUsage:+ # Wallet row must already be locked, serializing creation of the first monthly row.+ row = (await db.execute(select(TeamMonthlyUsage).where(TeamMonthlyUsage.team_id == team_id, TeamMonthlyUsage.user_id == user_id, TeamMonthlyUsage.period == period).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()+ if row is None:+ row = TeamMonthlyUsage(team_id=team_id, user_id=user_id, period=period, spent_fen=0, reserved_fen=0)+ db.add(row)+ await db.flush()+ return row+++async def ledger(db: AsyncSession, wallet: TeamWallet, actor: int, delta: int, kind: str, *, ref_type: str, ref_id: str, note: str = "") -> None:+ wallet.balance_fen = int(wallet.balance_fen or 0) + int(delta)+ db.add(TeamWalletLedger(team_id=wallet.team_id, actor_user_id=actor, delta_fen=int(delta), balance_after_fen=wallet.balance_fen, kind=kind, ref_type=ref_type, ref_id=ref_id, note=note[:255]))+++async def freeze_team_task(db: AsyncSession, task: TaskRun) -> int:+ if task.billing_status in ("frozen", "settled"):+ return int(task.billing_estimate_fen or 0)+ if task.billing_enabled_snapshot is False or task.billing_status == "skipped":+ task.billing_status = "skipped"+ task.billing_estimate_fen = 0+ await db.flush()+ return 0+ wallet = await lock_wallet(db, int(task.team_id))+ need = int(task.billing_estimate_fen or 0)+ if int(wallet.balance_fen or 0) < need:+ raise ValueError("团队余额不足,请联系所有者充值")+ wallet.frozen_fen = int(wallet.frozen_fen or 0) + need+ task.billing_status = "frozen"+ await ledger(db, wallet, int(task.requested_by), -need, "freeze", ref_type="task_run", ref_id=str(task.id), note=f"freeze:{task.domain}/{task.task_type}")+ await db.flush()+ return need+++async def settle_team_task(db: AsyncSession, task: TaskRun) -> dict[str, int]:+ if task.billing_status == "settled":+ return {"charged": int(task.billing_charged_fen or 0), "refunded": int(task.billing_refunded_fen or 0)}+ wallet = await lock_wallet(db, int(task.team_id))+ events = list((await db.execute(select(UsageEvent).where(UsageEvent.task_run_id == task.id, UsageEvent.settled.is_(False)))).scalars().all())+ if events:+ from app.services.billing.newapi_bill import apply_newapi_bills+ # Match personal settlement: failed upstream reconciliation does not lose recorded costs.+ try:+ await apply_newapi_bills(events)+ except Exception:+ import logging+ logging.getLogger(__name__).exception("Team upstream reconciliation failed task=%s", task.id)+ disabled = task.billing_enabled_snapshot is False or task.billing_status == "skipped"+ charged = 0 if disabled else sum(int(e.charge_fen or 0) for e in events)+ for event in events:+ event.user_id = int(task.requested_by)+ event.team_id = int(task.team_id)+ if disabled:+ event.charge_fen = 0+ event.settled = True+ reserved = int(task.billing_estimate_fen or 0)+ if not disabled:+ usage = await monthly_usage(db, int(task.team_id), int(task.requested_by), task.billing_period or billing_period(task.created_at))+ usage.reserved_fen = max(0, int(usage.reserved_fen or 0) - reserved)+ usage.spent_fen = int(usage.spent_fen or 0) + charged+ frozen = reserved if task.billing_status == "frozen" else 0+ refund = max(0, frozen - charged)+ wallet.frozen_fen = max(0, int(wallet.frozen_fen or 0) - frozen)+ if refund:+ await ledger(db, wallet, int(task.requested_by), refund, "unfreeze", ref_type="task_run", ref_id=str(task.id), note="refund_unused_freeze")+ extra = max(0, charged - frozen)+ if extra:+ await ledger(db, wallet, int(task.requested_by), -extra, "settle", ref_type="task_run", ref_id=str(task.id), note="settle_overage" if frozen else "settle_direct")+ if not disabled:+ await ledger(db, wallet, int(task.requested_by), 0, "settle", ref_type="task_run", ref_id=str(task.id), note=f"charged={charged} freeze={frozen} refund={refund}")+ task.billing_status = "settled"+ task.billing_charged_fen = charged+ task.billing_refunded_fen = refund+ await db.flush()+ return {"charged": charged, "refunded": refund}++diff --git a/backend/app/services/tasks/team_scope.py b/backend/app/services/tasks/team_scope.pynew file mode 100644index 0000000..f087168--- /dev/null+++ b/backend/app/services/tasks/team_scope.py@@ -0,0 +1,80 @@+"""Membership-aware task cancellation without interrupting submitted upstream work."""+from datetime import UTC, datetime+from sqlalchemy import select+from app.models_tasks import TaskRun+++async def prepare_background_task(db, project_id: int, fallback_user):+ """A server-side child inherits its active parent actor; the lock layer checks coverage."""+ from app.models import User+ from app.models_drama import DramaProject+ from app.services.billing.context import get_current_task_run_id+ from app.services.tasks.service import ACTIVE_TASK_STATUSES++ parent_id = get_current_task_run_id()+ if parent_id is None:+ return fallback_user+ parent = await db.get(TaskRun, parent_id)+ project = await db.get(DramaProject, project_id)+ if parent is None or parent.team_id is None:+ return fallback_user+ if (+ project is None+ or parent.domain != "drama"+ or parent.drama_project_id != project.id+ or parent.team_id != project.team_id+ or parent.status not in ACTIVE_TASK_STATUSES+ or parent.cancel_requested+ ):+ raise ValueError("后台派生任务与父任务范围不匹配")+ actor = await db.get(User, int(parent.requested_by))+ if actor is None:+ raise ValueError("任务发起人不存在")+ await ensure_task_may_submit(db, parent)+ from app.services.teams.edit_locks import task_resource++ db.info["team_parent_task_id"] = int(parent.id)+ db.info["team_parent_resource"] = await task_resource(db, parent)+ return actor+++async def ensure_task_may_submit(db, task: TaskRun) -> None:+ if task.team_id is None:+ return+ from app.services.teams.access import get_team+ await get_team(db, int(task.team_id), int(task.requested_by))+ if task.cancel_requested:+ raise ValueError("任务已请求取消,不能提交新的生成")+++async def ensure_upstream_submission_allowed(db, task_id: int) -> None:+ task = await db.get(TaskRun, task_id)+ if task is not None:+ await ensure_task_may_submit(db, task)+++async def cancel_removed_member_tasks(db, team_id: int, user_id: int) -> int:+ """Caller owns the membership transaction. Only unstarted tasks terminate immediately."""+ from app.services.billing.settlement import settle_task+ from app.services.tasks.service import ACTIVE_TASK_STATUSES, append_task_event+ tasks = list((await db.execute(select(TaskRun).where(TaskRun.team_id == team_id, TaskRun.requested_by == user_id, TaskRun.status.in_(tuple(ACTIVE_TASK_STATUSES))).with_for_update())).scalars().all())+ changed = 0+ for task in tasks:+ payload = task.payload if isinstance(task.payload, dict) else {}+ submitted = bool(task.provider_task_id or payload.get("provider_task_id") or task.started_at)+ if submitted:+ # Membership is checked before every new upstream POST. Existing GET polling and+ # download continue, preserving delivered output and charging its original wallet.+ continue+ task.cancel_requested = True+ task.status = "cancelled"+ task.error_code = "team_member_removed"+ task.error_message = "成员已退出团队,尚未开始的任务已取消"+ task.finished_at = datetime.now(UTC)+ task.next_action_at = None+ task.lease_token = None+ task.lease_until = None+ await append_task_event(db, task.id, event_type="task.cancelled", status="cancelled", message=task.error_message)+ await settle_task(db, task.id)+ changed += 1+ return changeddiff --git a/backend/app/services/teams/__init__.py b/backend/app/services/teams/__init__.pynew file mode 100644index 0000000..d19a34f--- /dev/null+++ b/backend/app/services/teams/__init__.py@@ -0,0 +1 @@+"""团队空间核心服务:实时成员权限、团队管理和邮箱邀请。"""diff --git a/backend/app/services/teams/access.py b/backend/app/services/teams/access.pynew file mode 100644index 0000000..a298ef6--- /dev/null+++ b/backend/app/services/teams/access.py@@ -0,0 +1,39 @@+"""团队授权统一入口,成员变更后每次请求实时读取数据库。"""+from __future__ import annotations++from fastapi import HTTPException+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models_teams import Team, TeamMember+++def member_role(team: Team, member: TeamMember) -> str:+ """权威所有者字段优先,错误的 owner 成员标记不能产生越权。"""+ if team.owner_user_id == member.user_id:+ return "owner"+ return "admin" if member.role == "admin" else "member"+++async def get_team(+ db: AsyncSession, team_id: int, user_id: int, *,+ roles: tuple[str, ...] | None = None, lock: bool = False,+) -> tuple[Team, TeamMember]:+ """先锁团队再锁成员;不在团队内返回 404,角色不足返回 403。"""+ team_stmt = select(Team).where(Team.id == team_id).execution_options(populate_existing=True)+ if lock:+ team_stmt = team_stmt.with_for_update()+ team = (await db.execute(team_stmt)).scalar_one_or_none()+ if not team:+ raise HTTPException(404, "团队不存在")+ member_stmt = select(TeamMember).where(+ TeamMember.team_id == team_id, TeamMember.user_id == user_id, TeamMember.active.is_(True),+ ).execution_options(populate_existing=True)+ if lock:+ member_stmt = member_stmt.with_for_update()+ member = (await db.execute(member_stmt)).scalar_one_or_none()+ if not member:+ raise HTTPException(404, "团队不存在或已退出")+ if roles is not None and member_role(team, member) not in roles:+ raise HTTPException(403, "没有团队操作权限")+ return team, memberdiff --git a/backend/app/services/teams/activity.py b/backend/app/services/teams/activity.pynew file mode 100644index 0000000..d65867d--- /dev/null+++ b/backend/app/services/teams/activity.py@@ -0,0 +1,17 @@+"""与业务变更同事务写入团队动态。"""+from __future__ import annotations++from sqlalchemy.ext.asyncio import AsyncSession++from app.models_teams import TeamActivity+++async def record_activity(+ db: AsyncSession, team_id: int, actor_user_id: int, action: str,+ subject: str, project_id: int | None = None,+) -> TeamActivity:+ """追加不含凭据的操作记录,不自行提交调用方事务。"""+ activity = TeamActivity(team_id=team_id, actor_user_id=actor_user_id, action=action[:64], subject=subject[:255], project_id=project_id)+ db.add(activity)+ await db.flush()+ return activitydiff --git a/backend/app/services/teams/admin_queries.py b/backend/app/services/teams/admin_queries.pynew file mode 100644index 0000000..991597f--- /dev/null+++ b/backend/app/services/teams/admin_queries.py@@ -0,0 +1,136 @@+"""平台团队只读查询;集合聚合避免一对多联接重复金额或逐行查询。"""+from datetime import date, datetime, time, timedelta++from fastapi import HTTPException+from sqlalchemy import case, func, or_, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models import UsageEvent, User+from app.models_drama import DramaProject+from app.models_teams import Team, TeamMember+from app.models_team_billing import TeamMonthlyUsage, TeamWallet+from app.schemas_admin_teams import (+ AdminTeamMemberOut, AdminTeamMemberPage, AdminTeamOut, AdminTeamPage,+ AdminTeamUsageOut, AdminTeamUsagePage, AdminTeamUsageSummary,+)+from app.schemas_common import PageMeta+from app.services import billing+from app.services.billing.team import SHANGHAI, billing_period+++async def require_team(db: AsyncSession, team_id: int) -> None:+ """统一不存在团队的详情/子列表行为,不创建钱包或成员关系。"""+ if await db.scalar(select(Team.id).where(Team.id == team_id)) is None:+ raise HTTPException(404, "团队不存在")+++def _team_statement(period: str):+ """先分别按团队聚合,再与团队主体联接,保证钱包与消费不会倍增。"""+ # members/projects/usage 分别为有效成员数、项目数、实际已结算月度金额。+ members = select(TeamMember.team_id, func.count().label("member_count")).where(TeamMember.active.is_(True)).group_by(TeamMember.team_id).subquery()+ projects = select(DramaProject.team_id, func.count().label("project_count")).where(DramaProject.team_id.is_not(None)).group_by(DramaProject.team_id).subquery()+ usage = select(+ TeamMonthlyUsage.team_id,+ func.sum(TeamMonthlyUsage.spent_fen).label("total_spent_fen"),+ func.sum(case((TeamMonthlyUsage.period == period, TeamMonthlyUsage.spent_fen), else_=0)).label("month_spent_fen"),+ func.sum(case((TeamMonthlyUsage.period == period, TeamMonthlyUsage.reserved_fen), else_=0)).label("month_reserved_fen"),+ ).group_by(TeamMonthlyUsage.team_id).subquery()+ return select(+ Team.id, Team.name, Team.description, Team.color, Team.owner_user_id, Team.created_at, Team.monthly_limit_fen,+ User.nickname.label("owner_nickname"), User.email.label("owner_email"),+ func.coalesce(members.c.member_count, 0).label("member_count"),+ func.coalesce(projects.c.project_count, 0).label("project_count"),+ func.coalesce(User.balance_fen, 0).label("balance_fen"),+ func.coalesce(User.frozen_fen, 0).label("frozen_fen"),+ func.coalesce(usage.c.month_spent_fen, 0).label("month_spent_fen"),+ func.coalesce(usage.c.month_reserved_fen, 0).label("month_reserved_fen"),+ func.coalesce(usage.c.total_spent_fen, 0).label("total_spent_fen"),+ ).join(User, User.id == Team.owner_user_id).outerjoin(TeamWallet, TeamWallet.team_id == Team.id).outerjoin(+ members, members.c.team_id == Team.id,+ ).outerjoin(projects, projects.c.team_id == Team.id).outerjoin(usage, usage.c.team_id == Team.id)+++async def list_teams(db: AsyncSession, *, q: str, owner_id: int | None, page: int, page_size: int) -> AdminTeamPage:+ """搜索团队名称、ID或所有者,列表与总数共用筛选条件。"""+ # period 固定本次请求的上海自然月;filters 避免总数与列表口径漂移。+ period, filters = billing_period(), []+ if q.strip():+ raw = q.strip()+ match = or_(Team.name.ilike(f"%{raw}%"), User.email.ilike(f"%{raw}%"), User.nickname.ilike(f"%{raw}%"))+ if raw.isdecimal() and len(raw) <= 10 and int(raw) <= 2_147_483_647:+ match = or_(match, Team.id == int(raw))+ filters.append(match)+ if owner_id is not None:+ filters.append(Team.owner_user_id == owner_id)+ total = int(await db.scalar(select(func.count()).select_from(Team).join(User, User.id == Team.owner_user_id).where(*filters)) or 0)+ rows = (await db.execute(_team_statement(period).where(*filters).order_by(Team.id.desc()).offset((page - 1) * page_size).limit(page_size))).mappings().all()+ return AdminTeamPage(items=[AdminTeamOut(**row, period=period) for row in rows], meta=PageMeta(page=page, page_size=page_size, total=total))+++async def team_detail(db: AsyncSession, team_id: int) -> AdminTeamOut:+ """读取任意团队快照,平台管理员无需加入团队。"""+ period = billing_period()+ row = (await db.execute(_team_statement(period).where(Team.id == team_id))).mappings().one_or_none()+ if row is None:+ raise HTTPException(404, "团队不存在")+ return AdminTeamOut(**row, period=period)+++async def list_members(db: AsyncSession, team_id: int, *, q: str, role: str | None, state: str, period: str | None, page: int, page_size: int) -> AdminTeamMemberPage:+ """分页查看当前及历史成员;消费记录按选定月份而非当前资格保留。"""+ await require_team(db, team_id)+ month = period or billing_period()+ filters = [TeamMember.team_id == team_id]+ if state != "all":+ filters.append(TeamMember.active.is_(state == "active"))+ if role:+ filters.append(TeamMember.role == role)+ if q.strip():+ filters.append(or_(User.nickname.ilike(f"%{q.strip()}%"), User.email.ilike(f"%{q.strip()}%")))+ total = int(await db.scalar(select(func.count()).select_from(TeamMember).join(User, User.id == TeamMember.user_id).where(*filters)) or 0)+ rows = (await db.execute(select(+ TeamMember, User.nickname, User.email,+ func.coalesce(TeamMonthlyUsage.spent_fen, 0), func.coalesce(TeamMonthlyUsage.reserved_fen, 0),+ ).join(User, User.id == TeamMember.user_id).outerjoin(TeamMonthlyUsage, (+ (TeamMonthlyUsage.team_id == team_id) & (TeamMonthlyUsage.user_id == User.id) & (TeamMonthlyUsage.period == month)+ )).where(*filters).order_by(TeamMember.id).offset((page - 1) * page_size).limit(page_size))).all()+ return AdminTeamMemberPage(items=[AdminTeamMemberOut(+ user_id=m.user_id, nickname=nickname, email=email, role=m.role, active=m.active,+ monthly_limit_fen=m.monthly_limit_fen, spent_fen=spent, reserved_fen=reserved, joined_at=m.joined_at,+ ) for m, nickname, email, spent, reserved in rows], meta=PageMeta(page=page, page_size=page_size, total=total), period=month)+++async def list_usage(db: AsyncSession, team_id: int, *, q: str, user_id: int | None, settled: bool | None, date_from: date | None, date_to: date | None, page: int, page_size: int) -> AdminTeamUsagePage:+ """按团队账务归属查消费,退出成员和删除项目的历史记录仍可查看。"""+ await require_team(db, team_id)+ if date_from and date_to and date_from > date_to:+ raise HTTPException(422, "开始日期不能晚于结束日期")+ filters = [UsageEvent.team_id == team_id]+ if user_id is not None:+ filters.append(UsageEvent.user_id == user_id)+ if settled is not None:+ filters.append(UsageEvent.settled.is_(settled))+ if date_from:+ filters.append(UsageEvent.created_at >= datetime.combine(date_from, time.min, SHANGHAI))+ if date_to == date.max:+ filters.append(UsageEvent.created_at <= datetime.combine(date_to, time.max, SHANGHAI))+ elif date_to:+ # 使用次日排他边界,包含结束日最后一秒的全部小数精度。+ filters.append(UsageEvent.created_at < datetime.combine(date_to, time.min, SHANGHAI) + timedelta(days=1))+ if q.strip():+ raw = f"%{q.strip()}%"+ filters.append(or_(User.email.ilike(raw), User.nickname.ilike(raw), DramaProject.title.ilike(raw), UsageEvent.model.ilike(raw), UsageEvent.billing_key.ilike(raw)))+ base = select(UsageEvent).outerjoin(User, User.id == UsageEvent.user_id).outerjoin(DramaProject, DramaProject.id == UsageEvent.drama_project_id).where(*filters)+ filtered = base.subquery()+ summary = (await db.execute(select(func.count(), func.coalesce(func.sum(case((filtered.c.settled.is_(True), filtered.c.charge_fen), else_=0)), 0)).select_from(filtered))).one()+ rows = (await db.execute(base.with_only_columns(+ UsageEvent, User.nickname, User.email, DramaProject.title,+ ).order_by(UsageEvent.id.desc()).offset((page - 1) * page_size).limit(page_size))).all()+ return AdminTeamUsagePage(items=[AdminTeamUsageOut(+ id=ev.id, user_id=ev.user_id, user_nickname=nickname or "", user_email=email or "",+ project_id=ev.drama_project_id, project_title=title, task_run_id=ev.task_run_id,+ billing_key=ev.billing_key, billing_label=billing.billing_key_label(ev.billing_key),+ model=ev.model or "", total_tokens=int(ev.total_tokens or 0), charge_fen=int(ev.charge_fen or 0),+ settled=ev.settled, created_at=ev.created_at,+ ) for ev, nickname, email, title in rows], meta=PageMeta(page=page, page_size=page_size, total=summary[0]),+ summary=AdminTeamUsageSummary(record_count=summary[0], settled_charge_fen=summary[1]))diff --git a/backend/app/services/teams/admin_wallet.py b/backend/app/services/teams/admin_wallet.pynew file mode 100644index 0000000..7fa8d91--- /dev/null+++ b/backend/app/services/teams/admin_wallet.py@@ -0,0 +1,35 @@+"""历史团队钱包流水只读查询。"""+from sqlalchemy import func, or_, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models import User+from app.models_team_billing import TeamWalletLedger+from app.schemas_admin_teams import (+ AdminTeamWalletLedgerOut, AdminTeamWalletLedgerPage,+)+from app.schemas_common import PageMeta+from app.services.teams.admin_queries import require_team+++async def list_wallet_ledger(+ db: AsyncSession, team_id: int, *, q: str, adjustments_only: bool, page: int, page_size: int,+) -> AdminTeamWalletLedgerPage:+ """查看全部钱包流水或仅后台调账,按备注/操作者/关联号搜索。"""+ await require_team(db, team_id)+ filters = [TeamWalletLedger.team_id == team_id]+ if adjustments_only:+ filters.append(TeamWalletLedger.ref_type == "admin_adjust")+ if q.strip():+ raw = f"%{q.strip()}%"+ filters.append(or_(TeamWalletLedger.note.ilike(raw), TeamWalletLedger.ref_id.ilike(raw),+ User.email.ilike(raw), User.nickname.ilike(raw)))+ base = select(TeamWalletLedger, User.nickname, User.email).outerjoin(+ User, User.id == TeamWalletLedger.actor_user_id,+ ).where(*filters)+ total = int(await db.scalar(select(func.count()).select_from(base.subquery())) or 0)+ rows = (await db.execute(base.order_by(TeamWalletLedger.id.desc()).offset((page - 1) * page_size).limit(page_size))).all()+ return AdminTeamWalletLedgerPage(items=[AdminTeamWalletLedgerOut(+ id=row.id, actor_user_id=row.actor_user_id, operator_nickname=nickname or "", operator_email=email or "",+ delta_fen=row.delta_fen, balance_after_fen=row.balance_after_fen, kind=row.kind, ref_type=row.ref_type,+ ref_id=row.ref_id, note=row.note, created_at=row.created_at,+ ) for row, nickname, email in rows], meta=PageMeta(page=page, page_size=page_size, total=total))diff --git a/backend/app/services/teams/budgets.py b/backend/app/services/teams/budgets.pynew file mode 100644index 0000000..47e852e--- /dev/null+++ b/backend/app/services/teams/budgets.py@@ -0,0 +1,16 @@+"""平台额度设置沿用团队写锁并记录操作者,不修改任何钱包。"""+from fastapi import HTTPException+from sqlalchemy import select+from app.models_teams import Team+from app.services.teams.activity import record_activity+from app.services.teams.management import active_member+++async def set_budget(db, team_id: int, actor_id: int, limit: int | None, *, user_id: int | None = None) -> None:+ """串行化额度设置与入队;降低额度只阻止后续任务。"""+ team = (await db.execute(select(Team).where(Team.id == team_id).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()+ if team is None:+ raise HTTPException(404, "团队不存在")+ target = team if user_id is None else await active_member(db, team_id, user_id)+ target.monthly_limit_fen = limit+ await record_activity(db, team_id, actor_id, "budget.updated", f"{'团队' if user_id is None else '成员 #' + str(user_id)} 月上限:{'不限额' if limit is None else str(limit) + ' 分'}")diff --git a/backend/app/services/teams/content.py b/backend/app/services/teams/content.pynew file mode 100644index 0000000..872d15d--- /dev/null+++ b/backend/app/services/teams/content.py@@ -0,0 +1,212 @@+"""团队项目/资产查询、个人项目整体迁入和资产独立副本。"""+from __future__ import annotations++from datetime import UTC, datetime++from fastapi import HTTPException+from sqlalchemy import Integer, and_, case, cast, func, or_, select+from sqlalchemy.orm import selectinload++from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProject, DramaScript+from app.models_tasks import TaskRun+from app.models_team_locks import TeamEditLock+from app.services.drama.project_cover import resolve_drama_project_cover+from app.services.teams.access import get_team+from app.services.teams.activity import record_activity+from app.services.teams.content_media import copier_for++ACTIVE_STATUSES = ("pending", "leased", "running", "awaiting_poll", "awaiting_review", "cancel_requested", "finalizing")+++def task_scope(project_id):+ """覆盖项目及历史仅挂子资源的任务,避免在途任务被漏判为空闲。"""+ episodes = select(DramaEpisode.id).where(DramaEpisode.project_id == project_id).correlate(DramaProject)+ return or_(TaskRun.drama_project_id == project_id,+ TaskRun.script_id.in_(select(DramaScript.id).where(DramaScript.project_id == project_id).correlate(DramaProject)),+ TaskRun.episode_id.in_(episodes),+ TaskRun.asset_id.in_(select(DramaAsset.id).where(DramaAsset.project_id == project_id).correlate(DramaProject)),+ TaskRun.fragment_id.in_(select(DramaEpisodeFragment.id).where(DramaEpisodeFragment.episode_id.in_(episodes)).correlate(DramaProject)))+++def card_query():+ """项目状态由真实在途任务和分集视频就绪情况计算,筛选可直接在 SQL 执行。"""+ episode_count = select(func.count()).where(DramaEpisode.project_id == DramaProject.id).correlate(DramaProject).scalar_subquery()+ has_fragment = select(DramaEpisodeFragment.id).where(DramaEpisodeFragment.episode_id == DramaEpisode.id).correlate(DramaEpisode).exists()+ missing_video = select(DramaEpisodeFragment.id).where(DramaEpisodeFragment.episode_id == DramaEpisode.id, or_(DramaEpisodeFragment.video.is_(None), DramaEpisodeFragment.video == "")).correlate(DramaEpisode).exists()+ completed = select(func.count()).where(DramaEpisode.project_id == DramaProject.id, has_fragment, ~missing_video).correlate(DramaProject).scalar_subquery()+ active = select(TaskRun.id).where(task_scope(DramaProject.id), TaskRun.status.in_(ACTIVE_STATUSES)).correlate(DramaProject).exists()+ planned_text = DramaProject.params["episode_count"].as_string()+ planned = case((planned_text.op("~")(r"^[0-9]{1,3}$"), cast(planned_text, Integer)), else_=0)+ status = case((active, "producing"), (and_(episode_count > 0, completed == episode_count, episode_count >= planned), "completed"), else_="draft")+ return select(DramaProject, status.label("card_status"), episode_count.label("episode_count"), completed.label("completed_count")).options(selectinload(DramaProject.script), selectinload(DramaProject.assets), selectinload(DramaProject.episodes).selectinload(DramaEpisode.fragments)), status+++async def cards(db, rows):+ """批量补充真实协作者和当前占用者,不从客户端 params 推断权限。"""+ ids = [project.id for project, *_ in rows]+ participants = (await db.execute(select(TaskRun.drama_project_id, TaskRun.requested_by).where(TaskRun.drama_project_id.in_(ids)).distinct())).all() if ids else []+ locks = (await db.execute(select(TeamEditLock).where(TeamEditLock.project_id.in_(ids), TeamEditLock.expires_at > datetime.now(UTC)).order_by(TeamEditLock.expires_at.desc()))).scalars().all() if ids else []+ result = []+ for project, status, count, completed in rows:+ params = project.params if isinstance(project.params, dict) else {}+ cover, _ = resolve_drama_project_cover(project)+ planned = params.get("episode_count")+ planned = planned if isinstance(planned, int) and planned >= 0 else 0+ result.append(dict(id=project.id, title=project.title, description=project.description or "", genre=str(params.get("genre") or "漫剧项目"), cover=cover or "", status=status, episodes=max(count, planned), completed_episodes=completed, updated_at=project.updated_at, collaborators=sorted({project.user_id, *(user_id for pid, user_id in participants if pid == project.id)}), editing_by=next((lock.user_id for lock in locks if lock.project_id == project.id), None)))+ return result+++async def list_projects(db, team_id: int, user_id: int, page: int, page_size: int, q: str, status: str | None):+ """项目搜索和状态筛选均在分页之前执行。"""+ await get_team(db, team_id, user_id)+ stmt, status_expr = card_query()+ filters = [DramaProject.team_id == team_id]+ if q.strip():+ filters.append(or_(DramaProject.title.ilike(f"%{q.strip()}%"), DramaProject.description.ilike(f"%{q.strip()}%")))+ if status:+ filters.append(status_expr == status)+ total = int(await db.scalar(select(func.count()).select_from(DramaProject).where(*filters)) or 0)+ rows = (await db.execute(stmt.where(*filters).order_by(DramaProject.updated_at.desc(), DramaProject.id.desc()).offset((page - 1) * page_size).limit(page_size))).all()+ return dict(items=await cards(db, rows), meta=dict(page=page, page_size=page_size, total=total))+++def asset_card(asset: DramaAsset) -> dict:+ """团队资产展示只返回必要字段,完整副本响应走现有 DramaAssetOut。"""+ params = asset.params if isinstance(asset.params, dict) else {}+ return dict(id=asset.id, name=asset.name or "未命名资产", type=asset.type, cover=asset.cover or "", url=asset.url or "", project_id=asset.project_id, description=str(params.get("description") or params.get("prompt") or ""), updated_at=asset.updated_at)+++async def list_assets(db, team_id: int, user_id: int, page: int, page_size: int, q: str, asset_type: str | None, project_id: int | None):+ """仅聚合当前团队项目资产,跨团队 project_id 不得用于探测资源。"""+ await get_team(db, team_id, user_id)+ if project_id is not None and not await db.scalar(select(DramaProject.id).where(DramaProject.id == project_id, DramaProject.team_id == team_id)):+ raise HTTPException(404, "团队项目不存在")+ filters = [DramaProject.team_id == team_id, DramaAsset.type.in_(("character", "scene", "prop", "voice"))]+ if q.strip():+ filters.append(DramaAsset.name.ilike(f"%{q.strip()}%"))+ if asset_type:+ filters.append(DramaAsset.type == asset_type)+ if project_id is not None:+ filters.append(DramaAsset.project_id == project_id)+ stmt = select(DramaAsset).join(DramaProject, DramaProject.id == DramaAsset.project_id).where(*filters)+ total = int(await db.scalar(select(func.count()).select_from(DramaAsset).join(DramaProject, DramaProject.id == DramaAsset.project_id).where(*filters)) or 0)+ rows = (await db.execute(stmt.order_by(DramaAsset.updated_at.desc(), DramaAsset.id.desc()).offset((page - 1) * page_size).limit(page_size))).scalars().all()+ return dict(items=[asset_card(row) for row in rows], meta=dict(page=page, page_size=page_size, total=total))+++async def busy_reasons(db, project_ids: list[int]) -> dict[int, str]:+ """一次批量判断个人项目的任务和存活租约。"""+ if not project_ids:+ return {}+ busy = (await db.execute(select(DramaProject.id).where(DramaProject.id.in_(project_ids), select(TaskRun.id).where(task_scope(DramaProject.id), TaskRun.status.in_(ACTIVE_STATUSES)).correlate(DramaProject).exists()))).scalars().all()+ leased = (await db.execute(select(TeamEditLock.project_id).where(TeamEditLock.project_id.in_(project_ids), TeamEditLock.expires_at > datetime.now(UTC)))).scalars().all()+ return {**{pid: "仍有编辑占用,请释放后再迁入" for pid in leased}, **{pid: "仍有生成任务,请等待结束后再迁入" for pid in busy}}+++async def transferable_projects(db, team_id: int, user_id: int, page: int, page_size: int):+ """仅列出本人个人项目,附上可迁入状态和明确原因。"""+ await get_team(db, team_id, user_id)+ stmt, _ = card_query()+ filters = (DramaProject.user_id == user_id, DramaProject.team_id.is_(None))+ total = int(await db.scalar(select(func.count()).select_from(DramaProject).where(*filters)) or 0)+ rows = (await db.execute(stmt.where(*filters).order_by(DramaProject.updated_at.desc(), DramaProject.id.desc()).offset((page - 1) * page_size).limit(page_size))).all()+ items = await cards(db, rows)+ reasons = await busy_reasons(db, [item["id"] for item in items])+ return dict(items=[{**item, "transferable": item["id"] not in reasons, "reason": reasons.get(item["id"], "")} for item in items], meta=dict(page=page, page_size=page_size, total=total))+++def normalize_episode_numbers(script: DramaScript | None, episodes: list[DramaEpisode]) -> None:+ """保留有效集号与所有正文,仅为缺号/重号分配空闲编号。"""+ content = script.episode_content if script else None+ rows = content.get("episodes", []) if isinstance(content, dict) else content+ rows = [dict(row) for row in (rows or []) if isinstance(row, dict)]+ reserved = {row["episodeNumber"] for row in rows if isinstance(row.get("episodeNumber"), int) and row["episodeNumber"] > 0}+ used = set()+ for row in rows:+ number = row.get("episodeNumber")+ if not isinstance(number, int) or number < 1 or number in used:+ number = 1+ while number in used or number in reserved:+ number += 1+ row["episodeNumber"] = number+ used.add(number)+ if script and content is not None:+ script.episode_content = {**content, "episodes": rows} if isinstance(content, dict) else rows+ used = set()+ for index, episode in enumerate(sorted(episodes, key=lambda item: item.id)):+ params = dict(episode.params or {})+ number = params.get("episodeNumber")+ if not isinstance(number, int) or number < 1 or number in used:+ number = rows[index]["episodeNumber"] if index < len(rows) and rows[index]["episodeNumber"] not in used else 1+ while number in used:+ number += 1+ used.add(number)+ episode.params = {**params, "episodeNumber": number}+++async def transfer_project(db, team_id: int, user_id: int, project_id: int):+ """整体原地迁入本人空闲项目,历史任务/用量的个人计费归属不变。"""+ await get_team(db, team_id, user_id, lock=True)+ project = (await db.execute(select(DramaProject).where(DramaProject.id == project_id, DramaProject.user_id == user_id).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()+ if not project:+ raise HTTPException(404, "个人项目不存在")+ if project.team_id == team_id:+ return project, None+ if project.team_id is not None:+ raise HTTPException(409, "项目已属于其他团队,不能再次迁入")+ reasons = await busy_reasons(db, [project_id])+ if project_id in reasons:+ raise HTTPException(409, reasons[project_id])+ script = (await db.execute(select(DramaScript).where(DramaScript.project_id == project_id).with_for_update())).scalar_one_or_none()+ episodes = list((await db.execute(select(DramaEpisode).where(DramaEpisode.project_id == project_id).with_for_update())).scalars().all())+ assets = list((await db.execute(select(DramaAsset).where(DramaAsset.project_id == project_id).with_for_update())).scalars().all())+ fragments = list((await db.execute(select(DramaEpisodeFragment).where(DramaEpisodeFragment.episode_id.in_([episode.id for episode in episodes])).with_for_update())).scalars().all()) if episodes else []+ copier = await copier_for(db, project, transfer=True)+ try:+ project.content, project.params = await copier.rewrite(project.content), await copier.rewrite(project.params)+ if script:+ script.summary, script.episode_content, script.params = await copier.rewrite(script.summary), await copier.rewrite(script.episode_content), await copier.rewrite(script.params)+ for asset in assets:+ asset.cover, asset.url, asset.params = await copier.rewrite(asset.cover), await copier.rewrite(asset.url), await copier.rewrite(asset.params)+ for episode in episodes:+ episode.params = await copier.rewrite(episode.params)+ for fragment in fragments:+ fragment.cover, fragment.video, fragment.params = await copier.rewrite(fragment.cover), await copier.rewrite(fragment.video), await copier.rewrite(fragment.params)+ normalize_episode_numbers(script, episodes)+ project.team_id = team_id+ await record_activity(db, team_id, user_id, "project.transferred", project.title, project_id=project_id)+ return project, copier+ except Exception:+ copier.cleanup()+ raise+++async def copy_asset(db, team_id: int | None, user_id: int, asset_id: int, target_id: int, session_id: str = "", token: str = "", version: int = 0):+ """源目标都按当前团队授权;持目标新资产租约后独立复制内容与本地文件。"""+ from app.services.teams.edit_locks import _task_conflicts, validate_lock++ if team_id is not None:+ await get_team(db, team_id, user_id, lock=True)+ scope = DramaProject.team_id == team_id if team_id is not None else and_(DramaProject.team_id.is_(None), DramaProject.user_id == user_id)+ asset = (await db.execute(select(DramaAsset).join(DramaProject, DramaProject.id == DramaAsset.project_id).where(DramaAsset.id == asset_id, scope))).scalar_one_or_none()+ target = (await db.execute(select(DramaProject).where(DramaProject.id == target_id, scope).with_for_update())).scalar_one_or_none()+ if not asset or not target:+ raise HTTPException(404, "团队资产或目标项目不存在")+ if team_id is not None:+ if not session_id or not token:+ raise HTTPException(428, "请先获取目标项目的资产编辑权限")+ await validate_lock(db, target, user_id, "asset", 0, session_id, token, version)+ await _task_conflicts(db, target_id, ("asset", 0))+ copier = await copier_for(db, target)+ try:+ params = await copier.rewrite(asset.params or {}, clean=True)+ params["copy_origin"] = {"asset_id": asset.id, "project_id": asset.project_id}+ clone = DramaAsset(project_id=target_id, type=asset.type, asset_type=asset.asset_type, name=asset.name, cover=await copier.rewrite(asset.cover), url=await copier.rewrite(asset.url), params=params, derive_id=None)+ db.add(clone)+ await db.flush()+ if team_id is not None:+ await record_activity(db, team_id, user_id, "asset.copied", asset.name or "资产", project_id=target_id)+ return clone, copier+ except Exception:+ copier.cleanup()+ raisediff --git a/backend/app/services/teams/content_media.py b/backend/app/services/teams/content_media.pynew file mode 100644index 0000000..1114568--- /dev/null+++ b/backend/app/services/teams/content_media.py@@ -0,0 +1,92 @@+"""团队媒体副本:只复制已鉴权项目的本地文件,绝不请求任意外部 URL。"""+from __future__ import annotations++import asyncio+import re+import shutil+import uuid+from pathlib import Path+from urllib.parse import unquote, urlsplit++from fastapi import HTTPException+from sqlalchemy import select++from app.models_drama import DramaProject+from app.services import oss, storage+from app.config import get_settings++# 暂态、画布实例和强关联 id 不进入独立资产副本;来源标记单独由服务生成。+DROP_COPY_KEYS = frozenset({"generation", "generation_attempts", "canvas", "canvas_node_id", "project_id", "projectId", "asset_id", "assetId", "asset_ids", "assetIds", "reference_asset_ids", "referenceAssetIds", "character_ids", "sourceAssetId", "sourceCharacterAssetId", "characterAssetId", "episode_id", "episode_ids", "fragment_id", "fragment_ids", "derive_id", "task_id", "task_run_id", "copy_origin", "_team_edit_session_id", "_team_edit_resource"})+++class MediaCopier:+ """记录本次新建文件以便失败清理,不触碰来源文件。"""++ def __init__(self, target_id: int, allowed_ids: set[int], *, transfer: bool = False):+ """迁入保持本项目目录不变;独立资产复制总是生成新文件名。"""+ self.target_id, self.allowed_ids, self.transfer = target_id, allowed_ids, transfer+ self.created: list[Path] = []+ self.cache: dict[Path, str] = {}++ def cleanup(self) -> None:+ """仅移除本次创建且仍位于目标项目目录中的具体文件。"""+ root = (storage.GENERATED_ROOT / f"p{self.target_id}").resolve()+ for path in self.created:+ if path.resolve().is_relative_to(root):+ path.unlink(missing_ok=True)++ async def rewrite(self, value, *, clean: bool = False):+ """递归改写媒体 URL;对象中的扩展字段和历史图片版本保持独立内容。"""+ if isinstance(value, dict):+ return {key: await self.rewrite(item, clean=clean) for key, item in value.items() if not clean or key not in DROP_COPY_KEYS}+ if isinstance(value, list):+ return [await self.rewrite(item, clean=clean) for item in value]+ if not isinstance(value, str) or not value.startswith(("/static/", "http://", "https://", "file:")):+ return value+ try:+ parts = urlsplit(value)+ except ValueError as exc:+ raise HTTPException(409, "媒体地址无效,无法复制") from exc+ path = unquote(parts.path)+ base = str(get_settings().public_base_url).rstrip("/")+ local = not parts.netloc or value.startswith(base + "/static/")+ controlled = oss.oss_enabled() and value.startswith(oss.public_base().rstrip("/") + "/")+ if controlled:+ marker = f"/{oss.folder_prefix()}/"+ path = "/static/" + path.split(marker, 1)[1] if marker in path else ""+ if (local or controlled) and path.startswith("/static/generated/"):+ candidate = (storage.STATIC_ROOT / path.removeprefix("/static/")).resolve()+ root = storage.GENERATED_ROOT.resolve()+ if not candidate.is_relative_to(root):+ raise HTTPException(409, "媒体文件路径无效,无法复制")+ relative = candidate.relative_to(root)+ match = re.fullmatch(r"p(\d+)", relative.parts[0]) if relative.parts else None+ if not match or int(match[1]) not in self.allowed_ids:+ raise HTTPException(409, "媒体引用了无权访问的项目文件")+ if self.transfer and int(match[1]) == self.target_id:+ return value+ if candidate.is_file():+ if candidate not in self.cache:+ dest = storage.project_dir(self.target_id) / f"copy_{uuid.uuid4().hex}{candidate.suffix}"+ if not dest.resolve().is_relative_to(root):+ raise HTTPException(409, "目标媒体目录无效,无法复制")+ self.created.append(dest)+ try:+ await asyncio.to_thread(shutil.copy2, candidate, dest)+ except OSError as exc:+ raise HTTPException(409, "媒体文件暂时无法复制,请稍后重试") from exc+ self.cache[candidate] = "/static/" + dest.relative_to(storage.STATIC_ROOT).as_posix()+ return self.cache[candidate]+ if not controlled:+ raise HTTPException(409, "本地媒体文件已不存在,无法复制")+ # 已知 OSS 对象是稳定引用;现有项目/资产删除仅删数据库行,不删除对象。+ if controlled or (local and path.startswith("/static/templates/")) or (self.transfer and parts.scheme in {"http", "https"}):+ return value+ raise HTTPException(409, "请先将外部媒体保存为项目素材,再复制到其他项目")+++async def copier_for(db, project: DramaProject, *, transfer: bool = False) -> MediaCopier:+ """由数据库真实归属推导可访问的源项目集合,不信任客户端来源标记。"""+ condition = (DramaProject.user_id == project.user_id) & DramaProject.team_id.is_(None) if transfer or project.team_id is None else DramaProject.team_id == project.team_id+ allowed = set((await db.execute(select(DramaProject.id).where(condition))).scalars().all())+ return MediaCopier(project.id, allowed, transfer=transfer)diff --git a/backend/app/services/teams/edit_locks.py b/backend/app/services/teams/edit_locks.pynew file mode 100644index 0000000..9678453--- /dev/null+++ b/backend/app/services/teams/edit_locks.py@@ -0,0 +1,221 @@+"""团队资源租约与统一任务的写入占用,个人项目沿用既有行为。"""+from __future__ import annotations++import hashlib+import secrets+from datetime import UTC, datetime, timedelta++from fastapi import HTTPException+from sqlalchemy import select, update+from sqlalchemy.ext.asyncio import AsyncSession++from app.models import User+from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProject+from app.models_team_locks import TeamEditLock+from app.models_tasks import TaskRun+from app.services.teams.access import get_team++# 持久任务状态来自统一任务平台,不能随发起人断线释放。+ACTIVE_STATUSES = ("pending", "leased", "running", "awaiting_poll", "awaiting_review", "cancel_requested", "finalizing")+RESOURCE_TYPES = frozenset({"structure", "script", "episode", "asset", "canvas"})+LEASE_SECONDS = 120+++def token_digest(token: str) -> str:+ """数据库仅存随机凭证的摘要,接口不返回别人的原始 token。"""+ return hashlib.sha256(token.encode()).hexdigest()+++def resources_conflict(left: tuple[str, int], right: tuple[str, int]) -> bool:+ """结构改写与整个项目互斥,其他资源仅同类同目标互斥。"""+ return left[0] == "structure" or right[0] == "structure" or left == right+++async def episode_resource_id(db: AsyncSession, episode_id: int) -> int:+ """分集确认前后均使用稳定集号;历史缺号时以数据库 id 兜底。"""+ episode = await db.get(DramaEpisode, episode_id)+ if not episode:+ raise HTTPException(status_code=404, detail="分集不存在")+ return int((episode.params or {}).get("episodeNumber") or episode.id)+++async def task_resource(db: AsyncSession, task: TaskRun) -> tuple[str, int]:+ """读取受理时固定的写回范围,仅服务端能写入该快照。"""+ snapshot = (task.payload or {}).get("_team_edit_resource")+ if isinstance(snapshot, (list, tuple)) and len(snapshot) == 2 and snapshot[0] in RESOURCE_TYPES:+ return str(snapshot[0]), int(snapshot[1])+ return await derived_task_resource(db, task)+++async def derived_task_resource(db: AsyncSession, task: TaskRun) -> tuple[str, int]:+ """受理时只用真实 FK 与业务参数推导目标,忽略请求会话和旧快照。"""+ if task.asset_id:+ return "asset", int(task.asset_id)+ if task.episode_id:+ return "episode", await episode_resource_id(db, task.episode_id)+ if task.fragment_id:+ fragment = await db.get(DramaEpisodeFragment, task.fragment_id)+ if fragment:+ return "episode", await episode_resource_id(db, fragment.episode_id)+ number = (task.payload or {}).get("episode_number")+ if (task.task_type in {"episode_scripts", "episode_script", "episode_optimize"} or (task.task_type == "seed_assets" and (task.payload or {}).get("confirm_episode"))) and number:+ return "episode", int(number)+ if task.task_type in {"asset_image", "asset_video"}:+ return "asset", 0+ return "structure", 0+++async def _task_conflicts(db: AsyncSession, project_id: int, resource: tuple[str, int], *, ignore_task_id: int | None = None, ignore_task_ids: set[int] | None = None) -> None:+ """任务一经受理即占用写回对象,强制接管不能覆盖在途结果。"""+ tasks = (await db.execute(select(TaskRun).where(TaskRun.drama_project_id == project_id, TaskRun.status.in_(ACTIVE_STATUSES)))).scalars().all()+ for task in tasks:+ if task.task_type in {"agent_chat", "skill_optimize"}:+ continue # 聊天只返回文本,没有生成内容写回。+ if task.id != ignore_task_id and task.id not in (ignore_task_ids or set()) and resources_conflict(resource, await task_resource(db, task)):+ raise HTTPException(status_code=423, detail={"message": "相关内容正在生成,请等待任务结束", "task_id": task.id})+++async def _project(db: AsyncSession, team_id: int, user_id: int, project_id: int) -> DramaProject:+ """使用团队→成员→项目的统一锁顺序,串行检查层级占用。"""+ await get_team(db, team_id, user_id, lock=True)+ project = (await db.execute(select(DramaProject).where(DramaProject.id == project_id, DramaProject.team_id == team_id).with_for_update())).scalar_one_or_none()+ if not project:+ raise HTTPException(status_code=404, detail="团队项目不存在")+ return project+++async def _check_resource(db: AsyncSession, project: DramaProject, kind: str, resource_id: int) -> None:+ """资产 id 必须属于当前项目,分集键限制为有效正整数。"""+ if kind not in RESOURCE_TYPES or resource_id < 0:+ raise HTTPException(status_code=422, detail="无效的编辑目标")+ if kind == "asset" and resource_id:+ asset = await db.get(DramaAsset, resource_id)+ if not asset or asset.project_id != project.id:+ raise HTTPException(status_code=404, detail="资产不存在")+ if kind == "episode" and resource_id < 1:+ raise HTTPException(status_code=422, detail="缺少分集编号")+ if kind in {"structure", "script", "canvas"} and resource_id != 0:+ raise HTTPException(status_code=422, detail="无效的编辑目标编号")+++async def lock_view(db: AsyncSession, lock: TeamEditLock, token: str | None = None) -> dict:+ """对外提供占用者和 fencing 代次,原始凭证仅在获取时提供。"""+ user = await db.get(User, lock.user_id)+ out = {"project_id": lock.project_id, "resource_type": lock.resource_type, "resource_id": lock.resource_id, "version": lock.version, "expires_at": lock.expires_at.isoformat(), "owner_user_id": lock.user_id, "owner_name": user.nickname if user else "团队成员"}+ if token is not None:+ out["token"] = token+ return out+++async def acquire_lock(db: AsyncSession, team_id: int, user_id: int, project_id: int, resource_type: str, resource_id: int, session_id: str, *, force: bool = False) -> dict:+ """获取或接管人工租约,重新发 token 时增加代次使旧凭证失效。"""+ project = await _project(db, team_id, user_id, project_id)+ await _check_resource(db, project, resource_type, resource_id)+ if force:+ await get_team(db, team_id, user_id, roles=("owner", "admin"))+ if not session_id or len(session_id) > 80:+ raise HTTPException(status_code=422, detail="无效的编辑会话")+ await _task_conflicts(db, project_id, (resource_type, resource_id))+ now = datetime.now(UTC)+ locks = list((await db.execute(select(TeamEditLock).where(TeamEditLock.project_id == project_id).with_for_update())).scalars().all())+ target = next((lock for lock in locks if (lock.resource_type, lock.resource_id) == (resource_type, resource_id)), None)+ for lock in locks:+ if lock.expires_at <= now or (lock.user_id == user_id and lock.session_id == session_id):+ continue+ if resources_conflict((resource_type, resource_id), (lock.resource_type, lock.resource_id)):+ if not force:+ info = await lock_view(db, lock)+ raise HTTPException(status_code=423, detail={"message": f"{info['owner_name']} 正在编辑此内容", **info})+ lock.expires_at = now+ token = secrets.token_urlsafe(32)+ if target is None:+ target = TeamEditLock(team_id=team_id, project_id=project_id, resource_type=resource_type, resource_id=resource_id, user_id=user_id, session_id=session_id, token_hash=token_digest(token), version=1, expires_at=now + timedelta(seconds=LEASE_SECONDS))+ db.add(target)+ else:+ target.user_id, target.session_id, target.token_hash = user_id, session_id, token_digest(token)+ target.version += 1+ target.expires_at = now + timedelta(seconds=LEASE_SECONDS)+ await db.commit()+ return await lock_view(db, target, token)+++async def validate_lock(db: AsyncSession, project: DramaProject, user_id: int, resource_type: str, resource_id: int, session_id: str, token: str, version: int) -> TeamEditLock | None:+ """提交时复核当前成员、租约与代次;失锁的旧标签页无法覆盖。"""+ if project.team_id is None:+ return None+ await _project(db, project.team_id, user_id, project.id)+ lock = (await db.execute(select(TeamEditLock).where(TeamEditLock.project_id == project.id, TeamEditLock.user_id == user_id, TeamEditLock.session_id == session_id, TeamEditLock.token_hash == token_digest(token)).with_for_update())).scalar_one_or_none()+ if not lock or lock.expires_at <= datetime.now(UTC) or lock.version != version:+ raise HTTPException(status_code=409, detail={"message": "编辑权限已变化,请重新获取后刷新内容"})+ if (lock.resource_type, lock.resource_id) != (resource_type, resource_id) and lock.resource_type != "structure":+ raise HTTPException(status_code=409, detail={"message": "编辑凭证与目标内容不匹配"})+ return lock+++async def renew_lock(db: AsyncSession, team_id: int, user_id: int, token: str, session_id: str, *, release: bool = False) -> dict:+ """只允许持有者续租或释放自己的会话,不凭 user_id 释放另一个标签页。"""+ await get_team(db, team_id, user_id, lock=True)+ lock = (await db.execute(select(TeamEditLock).where(TeamEditLock.team_id == team_id, TeamEditLock.user_id == user_id, TeamEditLock.session_id == session_id, TeamEditLock.token_hash == token_digest(token)).with_for_update())).scalar_one_or_none()+ if not lock or (not release and lock.expires_at <= datetime.now(UTC)):+ raise HTTPException(status_code=409, detail={"message": "编辑占用已失效,请重新获取"})+ lock.expires_at = datetime.now(UTC) + timedelta(seconds=0 if release else LEASE_SECONDS)+ await db.commit()+ return await lock_view(db, lock)+++async def release_member_locks(db: AsyncSession, team_id: int, user_id: int) -> None:+ """退出团队立即使人工租约失效;系统任务由任务状态继续保护。"""+ await db.execute(update(TeamEditLock).where(TeamEditLock.team_id == team_id, TeamEditLock.user_id == user_id).values(expires_at=datetime.now(UTC)))+++async def claim_task_locks(db: AsyncSession, task: TaskRun, user_id: int) -> None:+ """任务受理时固定写入范围,拒绝与其他会话的人工编辑竞争。"""+ if task.team_id is None or not task.drama_project_id:+ return+ if task.task_type in {"agent_chat", "skill_optimize"}:+ return+ project = await _project(db, task.team_id, user_id, task.drama_project_id)+ snapshot = db.info.get("team_edit_resource") if db.info.get("team_edit_project_id") == project.id else None+ actual = await derived_task_resource(db, task)+ resource = tuple(snapshot) if snapshot else actual+ parent_id = db.info.get("team_parent_task_id")+ if parent_id:+ from app.services.billing.context import get_current_task_run_id++ parent = await db.get(TaskRun, int(parent_id))+ if (get_current_task_run_id() != parent_id or not parent or parent.team_id != task.team_id+ or parent.drama_project_id != task.drama_project_id or parent.requested_by != user_id+ or parent.status not in ACTIVE_STATUSES or parent.cancel_requested):+ raise HTTPException(status_code=409, detail="父任务的系统写入权限已失效")+ resource = actual # 系统派生永不采信残留的人工请求资源快照。+ parent_resource = await task_resource(db, parent)+ if parent_resource[0] != "structure" and parent_resource != resource:+ raise HTTPException(status_code=409, detail="后续任务超出了已受理内容的范围")+ task.payload = {**(task.payload or {}), "_team_parent_task_id": parent.id, "_team_edit_resource": list(resource)}+ return+ if resource[0] != "structure" and resource != actual:+ raise HTTPException(status_code=409, detail="任务写入范围与已授权编辑目标不匹配")+ session_id = str(db.info.get("team_edit_session_id") or "")+ token = str(db.info.get("team_edit_token") or "")+ version = int(db.info.get("team_edit_version") or 0)+ if not session_id or not token:+ raise HTTPException(status_code=428, detail="请先获取团队内容的编辑权限")+ await validate_lock(db, project, user_id, *resource, session_id, token, version)+ admitted = set(db.info.get("team_admitted_task_ids") or ())+ await _task_conflicts(db, project.id, resource, ignore_task_id=task.id, ignore_task_ids=admitted)+ if task.id:+ db.info["team_admitted_task_ids"] = admitted | {task.id}+ task.payload = {**(task.payload or {}), "_team_edit_session_id": session_id, "_team_edit_resource": list(resource)}+++async def validate_task_locks(db: AsyncSession, task: TaskRun) -> None:+ """执行前确认仍属于受理时团队;任务自身即为系统占用。"""+ if task.team_id is not None and task.drama_project_id:+ project = await db.get(DramaProject, task.drama_project_id)+ if not project or project.team_id != task.team_id:+ raise ValueError("任务关联项目的团队归属已变化")+++async def release_task_locks(db: AsyncSession, task_id: int) -> None:+ """系统占用由终态自动解除,无人工凭证可被误释放。"""+ return Nonediff --git a/backend/app/services/teams/invitations.py b/backend/app/services/teams/invitations.pynew file mode 100644index 0000000..a2465f1--- /dev/null+++ b/backend/app/services/teams/invitations.py@@ -0,0 +1,161 @@+"""邮箱绑定、七天有效、一次性消费的团队邀请。"""+from __future__ import annotations++import hashlib+import secrets+from datetime import UTC, datetime, timedelta+from urllib.parse import quote, urlsplit++from fastapi import HTTPException+from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.config import get_settings+from app.models import User+from app.models_teams import Team, TeamInvitation, TeamMember+from app.schemas_common import PageMeta+from app.schemas_teams import TeamInvitationCreated, TeamInvitationOut, TeamPage+from app.services.email import send_email+from app.services.teams.access import get_team+from app.services.teams.activity import record_activity+++def hash_token(token: str) -> str:+ """仅高熵令牌的摘要允许进入数据库,避免泄漏可直接使用的邀请。"""+ return hashlib.sha256(token.encode("utf-8")).hexdigest()+++def invitation_out(invite: TeamInvitation) -> TeamInvitationOut:+ """响应只返回邀请状态和必要信息,不包含令牌或哈希。"""+ status = "accepted" if invite.accepted_at else "revoked" if invite.revoked_at else "expired" if invite.expires_at <= datetime.now(UTC) else "pending"+ return TeamInvitationOut(id=invite.id, email=invite.email, created_at=invite.created_at, expires_at=invite.expires_at, status=status)+++async def list_invitations(db: AsyncSession, team_id: int, user_id: int, page: int, page_size: int) -> TeamPage[TeamInvitationOut]:+ """只有所有者和管理员可读取邀请邮箱列表。"""+ await get_team(db, team_id, user_id, roles=("owner", "admin"))+ total = int(await db.scalar(select(func.count()).select_from(TeamInvitation).where(TeamInvitation.team_id == team_id)) or 0)+ rows = (await db.execute(select(TeamInvitation).where(TeamInvitation.team_id == team_id).order_by(TeamInvitation.created_at.desc(), TeamInvitation.id.desc()).offset((page - 1) * page_size).limit(page_size))).scalars().all()+ return TeamPage(items=[invitation_out(row) for row in rows], meta=PageMeta(page=page, page_size=page_size, total=total))+++async def create_invitation(db: AsyncSession, team_id: int, user_id: int, email: str) -> tuple[Team, TeamInvitation, str]:+ """团队行锁串行化同邮箱签发,允许过期或撤回后重新邀请。"""+ team, _ = await get_team(db, team_id, user_id, roles=("owner", "admin"), lock=True)+ email = email.strip().lower()+ await ensure_invitable(db, team_id, email)+ token = secrets.token_urlsafe(32)+ invite = TeamInvitation(team_id=team_id, email=email, token_hash=hash_token(token), created_by=user_id, expires_at=datetime.now(UTC) + timedelta(days=7))+ db.add(invite)+ await record_activity(db, team_id, user_id, "invitation.created", email)+ return team, invite, token+++async def ensure_invitable(db: AsyncSession, team_id: int, email: str, exclude_id: int | None = None) -> None:+ """签发与重发均排除已在团队者和同邮箱其他有效邀请。"""+ existing_member = await db.scalar(select(TeamMember.id).join(User, User.id == TeamMember.user_id).where(TeamMember.team_id == team_id, TeamMember.active.is_(True), func.lower(User.email) == email).limit(1))+ if existing_member:+ raise HTTPException(409, "该邮箱已是团队成员")+ stmt = select(TeamInvitation.id).where(TeamInvitation.team_id == team_id, TeamInvitation.email == email, TeamInvitation.accepted_at.is_(None), TeamInvitation.revoked_at.is_(None), TeamInvitation.expires_at > datetime.now(UTC))+ if exclude_id is not None:+ stmt = stmt.where(TeamInvitation.id != exclude_id)+ pending = await db.scalar(stmt.limit(1))+ if pending:+ raise HTTPException(409, "已存在有效邀请,请勿重复邀请")+++async def managed_invitation(db: AsyncSession, team_id: int, user_id: int, invite_id: int) -> tuple[Team, TeamInvitation]:+ """管理写操作统一先锁团队,再锁所属邀请。"""+ team, _ = await get_team(db, team_id, user_id, roles=("owner", "admin"), lock=True)+ invite = (await db.execute(select(TeamInvitation).where(TeamInvitation.id == invite_id, TeamInvitation.team_id == team_id).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()+ if not invite:+ raise HTTPException(404, "邀请不存在")+ return team, invite+++async def revoke_invitation(db: AsyncSession, team_id: int, user_id: int, invite_id: int) -> None:+ """撤回未消费邀请;重复撤回保持幂等。"""+ _, invite = await managed_invitation(db, team_id, user_id, invite_id)+ if invite.accepted_at:+ raise HTTPException(409, "邀请已被接受,不能撤回")+ if invite.revoked_at is None:+ invite.revoked_at = datetime.now(UTC)+ await record_activity(db, team_id, user_id, "invitation.revoked", invite.email)+++async def resend_invitation(db: AsyncSession, team_id: int, user_id: int, invite_id: int) -> tuple[Team, TeamInvitation, str]:+ """重发轮换哈希使旧链接立即失效;已接受或撤回邀请不能重发。"""+ team, invite = await managed_invitation(db, team_id, user_id, invite_id)+ if invite.accepted_at or invite.revoked_at:+ raise HTTPException(409, "邀请已结束,请重新创建邀请")+ await ensure_invitable(db, team_id, invite.email, exclude_id=invite.id)+ token = secrets.token_urlsafe(32)+ invite.token_hash = hash_token(token)+ invite.expires_at = datetime.now(UTC) + timedelta(days=7)+ await record_activity(db, team_id, user_id, "invitation.resent", invite.email)+ return team, invite, token+++def invitation_frontend_base(origin: str | None) -> str:+ """只信任已配置 CORS 前端源,修正本地前后端分端口邀请链接。"""+ settings = get_settings()+ base = str(settings.public_base_url).rstrip("/")+ candidate = (origin or "").rstrip("/")+ allowed = {item.strip().rstrip("/") for item in str(settings.cors_origins or "").split(",")}+ if candidate not in allowed:+ return base+ try:+ parts = urlsplit(candidate)+ except ValueError:+ return base+ if parts.scheme in {"http", "https"} and parts.netloc and not (parts.username or parts.password or parts.path or parts.query or parts.fragment):+ return candidate+ return base+++async def invitation_result(team: Team, invite: TeamInvitation, token: str, *, frontend_base: str | None = None) -> TeamInvitationCreated:+ """提交签发事务之后尝试 SMTP,失败时仍允许复制有效邀请链接。"""+ base = frontend_base or str(get_settings().public_base_url).rstrip("/")+ link = f"{base}/teams/join?token={quote(token, safe='')}"+ sent = await send_email(to_addrs=[invite.email], subject=f"PRINTFILM 团队邀请:{team.name}", body=f"您受邀加入「{team.name}」。请使用 {invite.email} 登录,并在七天内打开以下链接:\n\n{link}\n\n如非本人操作,请忽略本邮件。")+ return TeamInvitationCreated(invitation=invitation_out(invite), token=token, accept_url=link, email_sent=sent)+++async def check_invitation(db: AsyncSession, token: str, user: User, *, lock: bool = False) -> tuple[Team, TeamInvitation]:+ """登录邮箱必须匹配;接受时按团队→邀请顺序加锁并重新核对令牌。"""+ digest = hash_token(token)+ scope_id = await db.scalar(select(TeamInvitation.team_id).where(TeamInvitation.token_hash == digest))+ if scope_id is None:+ raise HTTPException(404, "邀请链接无效")+ team_stmt = select(Team).where(Team.id == scope_id)+ if lock:+ team_stmt = team_stmt.with_for_update()+ team = (await db.execute(team_stmt.execution_options(populate_existing=True))).scalar_one_or_none()+ stmt = select(TeamInvitation).where(TeamInvitation.token_hash == digest, TeamInvitation.team_id == scope_id)+ if lock:+ stmt = stmt.with_for_update()+ invite = (await db.execute(stmt.execution_options(populate_existing=True))).scalar_one_or_none()+ if not team or not invite:+ raise HTTPException(404, "邀请链接无效")+ if user.email.strip().lower() != invite.email:+ raise HTTPException(403, "请使用受邀邮箱登录")+ if invite.accepted_at or invite.revoked_at:+ raise HTTPException(409, "邀请已被使用或撤回")+ if invite.expires_at <= datetime.now(UTC):+ raise HTTPException(410, "邀请已过期,请联系管理员重新邀请")+ return team, invite+++async def accept_invitation(db: AsyncSession, token: str, user: User) -> Team:+ """一次性加入或激活历史成员,保留月额度及原月消费账本。"""+ team, invite = await check_invitation(db, token, user, lock=True)+ member = (await db.execute(select(TeamMember).where(TeamMember.team_id == team.id, TeamMember.user_id == user.id).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()+ if member and member.active:+ raise HTTPException(409, "你已是团队成员")+ if member:+ member.active, member.role = True, "member"+ else:+ db.add(TeamMember(team_id=team.id, user_id=user.id, role="member", active=True))+ invite.accepted_at = datetime.now(UTC)+ await record_activity(db, team.id, user.id, "member.joined", user.nickname)+ return teamdiff --git a/backend/app/services/teams/management.py b/backend/app/services/teams/management.pynew file mode 100644index 0000000..3e6b0e3--- /dev/null+++ b/backend/app/services/teams/management.py@@ -0,0 +1,125 @@+"""团队与成员变更,所有写操作沿团队锁顺序同事务执行。"""+from __future__ import annotations++from datetime import UTC, datetime+from fastapi import HTTPException+from sqlalchemy import select, update+from sqlalchemy.ext.asyncio import AsyncSession++from app.models import User+from app.models_teams import Team, TeamMember, TeamInvitation+from app.schemas_teams import TeamCreate, TeamMemberPatch, TeamUpdate+from app.services.teams.access import get_team, member_role+from app.services.teams.activity import record_activity+++async def create_team(db: AsyncSession, user_id: int, body: TeamCreate) -> Team:+ """创建团队及唯一所有者,费用直接使用所有者个人余额。"""+ team = Team(owner_user_id=user_id, **body.model_dump())+ db.add(team)+ await db.flush()+ db.add(TeamMember(team_id=team.id, user_id=user_id, role="owner", active=True))+ await record_activity(db, team.id, user_id, "team.created", team.name)+ return team+++async def update_team(db: AsyncSession, team_id: int, user_id: int, body: TeamUpdate) -> None:+ """仅所有者修改团队资料。"""+ team, _ = await get_team(db, team_id, user_id, roles=("owner",), lock=True)+ for key, value in body.model_dump(exclude_unset=True).items():+ setattr(team, key, value)+ await record_activity(db, team_id, user_id, "team.updated", team.name)+++async def delete_team(db: AsyncSession, team_id: int, user_id: int) -> None:+ """所有者解散团队;保留历史归属,撤销所有成员和邀请访问。"""+ from app.models_tasks import TaskRun+ from app.services.tasks.service import TERMINAL_TASK_STATUSES+ from app.services.teams.edit_locks import release_member_locks++ team, _ = await get_team(db, team_id, user_id, roles=("owner",), lock=True)+ active_task = await db.scalar(select(TaskRun.id).where(+ TaskRun.team_id == team_id, TaskRun.status.not_in(TERMINAL_TASK_STATUSES),+ ).limit(1))+ if active_task is not None:+ raise HTTPException(409, "团队还有未结束的生成任务,请等待完成或取消任务后再删除")+ members = (await db.execute(select(TeamMember).where(+ TeamMember.team_id == team_id, TeamMember.active.is_(True),+ ).order_by(TeamMember.id).with_for_update())).scalars().all()+ for member in members:+ member.active = False+ await release_member_locks(db, team_id, member.user_id)+ await db.execute(update(TeamInvitation).where(+ TeamInvitation.team_id == team_id,+ TeamInvitation.accepted_at.is_(None), TeamInvitation.revoked_at.is_(None),+ ).values(revoked_at=datetime.now(UTC)))+ await record_activity(db, team_id, user_id, "team.deleted", team.name)+++async def active_member(db: AsyncSession, team_id: int, user_id: int) -> TeamMember:+ """在团队已锁定的事务中锁定目标有效成员。"""+ member = (await db.execute(select(TeamMember).where(TeamMember.team_id == team_id, TeamMember.user_id == user_id, TeamMember.active.is_(True)).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()+ if not member:+ raise HTTPException(404, "团队成员不存在")+ return member+++async def update_member(db: AsyncSession, team_id: int, actor_id: int, user_id: int, body: TeamMemberPatch) -> None:+ """所有者调整成员月额度或非所有者角色,不重置历史消费。"""+ team, _ = await get_team(db, team_id, actor_id, roles=("owner",), lock=True)+ member = await active_member(db, team_id, user_id)+ if team.owner_user_id == user_id and "role" in body.model_fields_set:+ raise HTTPException(409, "不能修改所有者的角色,请先转让所有权")+ for key, value in body.model_dump(exclude_unset=True).items():+ setattr(member, key, value)+ user = await db.get(User, user_id)+ await record_activity(db, team_id, actor_id, "member.updated", user.nickname if user else str(user_id))+++async def deactivate_member(db: AsyncSession, team_id: int, actor_id: int, member: TeamMember, action: str) -> None:+ """成员软退出与任务/编辑锁清理处于同一事务,不提前退还在途费用。"""+ from app.services.tasks.team_scope import cancel_removed_member_tasks+ from app.services.teams.edit_locks import release_member_locks++ member.active = False+ await db.flush()+ await cancel_removed_member_tasks(db, team_id, member.user_id)+ await release_member_locks(db, team_id, member.user_id)+ user = await db.get(User, member.user_id)+ await record_activity(db, team_id, actor_id, action, user.nickname if user else str(member.user_id))+++async def remove_member(db: AsyncSession, team_id: int, actor_id: int, user_id: int) -> None:+ """管理员仅能移除普通成员;不能用移除入口移除自己或所有者。"""+ team, actor = await get_team(db, team_id, actor_id, roles=("owner", "admin"), lock=True)+ member = await active_member(db, team_id, user_id)+ if actor_id == user_id:+ raise HTTPException(409, "请使用退出团队功能")+ if member_role(team, actor) == "admin" and member_role(team, member) != "member":+ raise HTTPException(403, "管理员只能移除普通成员")+ if team.owner_user_id == user_id:+ raise HTTPException(409, "不能移除团队所有者")+ await deactivate_member(db, team_id, actor_id, member, "member.removed")+++async def leave_team(db: AsyncSession, team_id: int, user_id: int) -> None:+ """所有者必须先转让;普通成员退出保留内容、账单和成员关系。"""+ team, member = await get_team(db, team_id, user_id, lock=True)+ if team.owner_user_id == user_id:+ raise HTTPException(409, "请先转让所有权,再退出团队")+ await deactivate_member(db, team_id, user_id, member, "member.left")+++async def transfer_ownership(db: AsyncSession, team_id: int, actor_id: int, user_id: int) -> None:+ """持有团队与两个成员行锁转让,先降级旧所有者再提升新所有者。"""+ team, actor = await get_team(db, team_id, actor_id, roles=("owner",), lock=True)+ if actor_id == user_id:+ raise HTTPException(409, "请选择其他团队成员接任所有者")+ target = await active_member(db, team_id, user_id)+ actor.role = "admin"+ await db.flush()+ team.owner_user_id = target.user_id+ target.role = "owner"+ await db.flush()+ user = await db.get(User, user_id)+ await record_activity(db, team_id, actor_id, "team.ownership_transferred", user.nickname if user else str(user_id))diff --git a/backend/app/services/teams/queries.py b/backend/app/services/teams/queries.pynew file mode 100644index 0000000..45fe614--- /dev/null+++ b/backend/app/services/teams/queries.py@@ -0,0 +1,88 @@+"""团队摘要、成员财务遮蔽与服务端分页查询。"""+from __future__ import annotations++from sqlalchemy import func, or_, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models import User+from app.models_drama import DramaAsset, DramaProject+from app.models_teams import Team, TeamActivity, TeamMember+from app.schemas_common import PageMeta+from app.schemas_teams import TeamActivityOut, TeamMemberOut, TeamPage, TeamSummary+from app.services.teams.access import get_team, member_role+++async def summaries(db: AsyncSession, rows: list[tuple[Team, TeamMember]], user_id: int) -> list[TeamSummary]:+ """一次批量聚合成员、项目和资产数量,避免逐队 N+1 查询。"""+ if not rows:+ return []+ ids = [team.id for team, _ in rows]+ member_counts = dict((await db.execute(select(TeamMember.team_id, func.count()).where(TeamMember.team_id.in_(ids), TeamMember.active.is_(True)).group_by(TeamMember.team_id))).all())+ project_counts = dict((await db.execute(select(DramaProject.team_id, func.count()).where(DramaProject.team_id.in_(ids)).group_by(DramaProject.team_id))).all())+ asset_counts = dict((await db.execute(select(DramaProject.team_id, func.count(DramaAsset.id)).join(DramaAsset, DramaAsset.project_id == DramaProject.id).where(DramaProject.team_id.in_(ids)).group_by(DramaProject.team_id))).all())+ return [TeamSummary(+ id=team.id, name=team.name, description=team.description, color=team.color,+ created_at=team.created_at, updated_at=team.updated_at,+ my_role=member_role(team, member), viewer_id=user_id,+ member_count=member_counts.get(team.id, 0), project_count=project_counts.get(team.id, 0), asset_count=asset_counts.get(team.id, 0),+ ) for team, member in rows]+++async def team_summary(db: AsyncSession, team_id: int, user_id: int) -> TeamSummary:+ """读取当前用户可访问的单队摘要。"""+ team, member = await get_team(db, team_id, user_id)+ return (await summaries(db, [(team, member)], user_id))[0]+++async def list_teams(db: AsyncSession, user_id: int, page: int, page_size: int) -> TeamPage[TeamSummary]:+ """只列出当前用户仍有效加入的团队,排序与分页保持稳定。"""+ filters = (TeamMember.user_id == user_id, TeamMember.active.is_(True))+ total = int(await db.scalar(select(func.count()).select_from(TeamMember).where(*filters)) or 0)+ rows = (await db.execute(select(Team, TeamMember).join(TeamMember, TeamMember.team_id == Team.id).where(*filters).order_by(Team.updated_at.desc(), Team.id.desc()).offset((page - 1) * page_size).limit(page_size))).all()+ return TeamPage(items=await summaries(db, list(rows), user_id), meta=PageMeta(page=page, page_size=page_size, total=total))+++async def member_outputs(db: AsyncSession, team: Team, viewer: TeamMember, rows: list[tuple[TeamMember, User]]) -> list[TeamMemberOut]:+ """按当前月预算账本聚合,并在序列化前遮蔽他人的财务字段。"""+ from app.models_team_billing import TeamMonthlyUsage+ from app.services.billing.team import billing_period++ user_ids = [member.user_id for member, _ in rows]+ period = billing_period()+ usages = (await db.execute(select(TeamMonthlyUsage).where(TeamMonthlyUsage.team_id == team.id, TeamMonthlyUsage.user_id.in_(user_ids), TeamMonthlyUsage.period == period))).scalars().all() if user_ids else []+ by_user = {usage.user_id: usage for usage in usages}+ owner = team.owner_user_id == viewer.user_id+ result = []+ for member, user in rows:+ visible = owner or user.id == viewer.user_id+ usage = by_user.get(user.id)+ result.append(TeamMemberOut(+ id=user.id, nickname=user.nickname, email=user.email, avatar_url=user.avatar_url or "", role=member_role(team, member),+ monthly_limit_fen=member.monthly_limit_fen if visible else None,+ spent_fen=int(usage.spent_fen or 0) if visible and usage else 0 if visible else None,+ reserved_fen=int(usage.reserved_fen or 0) if visible and usage else 0 if visible else None,+ joined_at=member.joined_at,+ ))+ return result+++async def list_members(db: AsyncSession, team_id: int, user_id: int, page: int, page_size: int, q: str = "", role: str | None = None) -> TeamPage[TeamMemberOut]:+ """成员筛选和分页在数据库执行,禁止返回已退出成员。"""+ team, viewer = await get_team(db, team_id, user_id)+ filters = [TeamMember.team_id == team_id, TeamMember.active.is_(True)]+ if q.strip():+ filters.append(or_(User.nickname.ilike(f"%{q.strip()}%"), User.email.ilike(f"%{q.strip()}%")))+ if role:+ filters.append(TeamMember.role == role)+ stmt = select(TeamMember, User).join(User, User.id == TeamMember.user_id).where(*filters)+ total = int(await db.scalar(select(func.count()).select_from(TeamMember).join(User, User.id == TeamMember.user_id).where(*filters)) or 0)+ rows = (await db.execute(stmt.order_by(TeamMember.joined_at.asc(), TeamMember.id.asc()).offset((page - 1) * page_size).limit(page_size))).all()+ return TeamPage(items=await member_outputs(db, team, viewer, list(rows)), meta=PageMeta(page=page, page_size=page_size, total=total))+++async def list_activities(db: AsyncSession, team_id: int, user_id: int, page: int, page_size: int) -> TeamPage[TeamActivityOut]:+ """动态不因原项目或操作者退出而丢失。"""+ await get_team(db, team_id, user_id)+ total = int(await db.scalar(select(func.count()).select_from(TeamActivity).where(TeamActivity.team_id == team_id)) or 0)+ rows = (await db.execute(select(TeamActivity, User.nickname).join(User, User.id == TeamActivity.actor_user_id).where(TeamActivity.team_id == team_id).order_by(TeamActivity.created_at.desc(), TeamActivity.id.desc()).offset((page - 1) * page_size).limit(page_size))).all()+ return TeamPage(items=[TeamActivityOut(id=row.id, actor_user_id=row.actor_user_id, actor_nickname=nickname, action=row.action, subject=row.subject, project_id=row.project_id, created_at=row.created_at) for row, nickname in rows], meta=PageMeta(page=page, page_size=page_size, total=total))diff --git a/backend/app/services/teams/script_updates.py b/backend/app/services/teams/script_updates.pynew file mode 100644index 0000000..61dd085--- /dev/null+++ b/backend/app/services/teams/script_updates.py@@ -0,0 +1,65 @@+"""按集原子更新 JSON,不在模型调用期间持有数据库写锁。"""+from __future__ import annotations++from fastapi import HTTPException+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models_drama import DramaScript+++async def locked_script(db: AsyncSession, project_id: int) -> DramaScript:+ """从最新数据库版本读改写,避免不同集互相覆盖。"""+ row = (await db.execute(select(DramaScript).where(DramaScript.project_id == project_id).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()+ if not row:+ raise HTTPException(status_code=404, detail="剧本不存在")+ return row+++def episode_rows(content: dict | list | None) -> list[dict]:+ """兼容旧数组与新 episodes 容器,保留未知扩展字段。"""+ rows = content.get("episodes", []) if isinstance(content, dict) else content+ return [dict(item) for item in (rows or []) if isinstance(item, dict)]+++async def patch_episode_body(db: AsyncSession, project_id: int, episode_number: int, patch: dict) -> dict:+ """仅更新明确提交的字段,空字符串表示清空,其他集和扩展数据保持原样。"""+ script = await locked_script(db, project_id)+ rows = episode_rows(script.episode_content)+ item = next((row for row in rows if int(row.get("episodeNumber") or 0) == episode_number), None)+ if item is None:+ raise HTTPException(status_code=404, detail="分集剧本不存在")+ params = dict(script.params or {})+ versions = dict(params.get("episode_versions") or {})+ version = int(versions.get(str(episode_number), 0))+ if patch.get("version") is not None and int(patch["version"]) != version:+ raise HTTPException(status_code=409, detail="本集内容已更新,请刷新后再保存")+ item.update({key: value for key, value in patch.items() if key in {"title", "creative", "summary", "body"} and value is not None})+ container = dict(script.episode_content) if isinstance(script.episode_content, dict) else {}+ container["episodes"] = rows+ script.episode_content = container+ versions[str(episode_number)] = version + 1+ params["episode_versions"] = versions+ script.params = params+ await db.flush()+ return {**item, "version": version + 1}+++def set_episode_job_state(script: DramaScript, episode_number: int, status: str, **extra) -> None:+ """单集生成状态分别保存,不再用单一全剧槽位阻止其他集并行。"""+ params = dict(script.params or {})+ jobs = dict(params.get("episode_jobs") or {})+ jobs[str(episode_number)] = {"status": status, **extra}+ params["episode_jobs"] = jobs+ script.params = params+++def bump_episode_versions(script: DramaScript, numbers: list[int]) -> None:+ """模型写回同样更新内容版本,生成前的旧草稿不能覆盖新正文。"""+ params = dict(script.params or {})+ versions = dict(params.get("episode_versions") or {})+ for number in set(numbers):+ if number > 0:+ versions[str(number)] = int(versions.get(str(number), 0)) + 1+ params["episode_versions"] = versions+ script.params = paramsdiff --git a/backend/app/services/teams/write_access.py b/backend/app/services/teams/write_access.pynew file mode 100644index 0000000..f9920b5--- /dev/null+++ b/backend/app/services/teams/write_access.py@@ -0,0 +1,127 @@+"""将现有漫剧写入口统一映射到实际团队资源,防止漏掉旧路由授权。"""+from __future__ import annotations++import re++from fastapi import Depends, HTTPException, Request+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.database import get_db+from app.deps import get_current_user+from app.models import User+from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProject+from app.services.drama.access import get_owned_drama_project, require_drama_project_manager+from app.services.teams.access import get_team+from app.services.teams.edit_locks import _task_conflicts, episode_resource_id, validate_lock+++async def workspace_team(request: Request, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> int | None:+ """仅列表/创建读取显式空间;资源授权始终根据数据库真实归属。"""+ query = request.query_params.get("team_id")+ header = request.headers.get("X-Team-Id")+ if not query and not header:+ return None+ try:+ team_id = int(query or header or "0")+ if team_id < 1 or (query and header and int(query) != int(header)):+ raise ValueError+ except ValueError as exc:+ raise HTTPException(status_code=422, detail="无效的团队空间") from exc+ await get_team(db, team_id, user.id)+ return team_id+++async def write_target(db: AsyncSession, path: str, values: dict) -> tuple[int, str, int] | None:+ """推导路径和请求字段对应的资源键,不接受客户端指定锁范围。"""+ suffix = path.removeprefix("/api/drama/")+ match = re.match(r"scripts/(\d+)/episodes/(\d+)$", suffix)+ if match:+ return int(match[1]), "episode", int(match[2])+ match = re.match(r"(projects|scripts|canvas)/(\d+)$", suffix)+ if match:+ return int(match[2]), {"projects": "structure", "scripts": "script", "canvas": "canvas"}[match[1]], 0+ match = re.match(r"assets/(\d+)(?:/.*)?$", suffix)+ if match:+ asset = await db.get(DramaAsset, int(match[1]))+ if asset:+ return asset.project_id, "asset", asset.id+ raise HTTPException(status_code=404, detail="资产不存在")+ match = re.match(r"episodes/(\d+)(?:/.*)?$", suffix)+ if match:+ episode = await db.get(DramaEpisode, int(match[1]))+ if episode:+ return episode.project_id, "episode", await episode_resource_id(db, episode.id)+ raise HTTPException(status_code=404, detail="分集不存在")+ match = re.match(r"fragments/(\d+)(?:/.*)?$", suffix)+ if match:+ fragment = await db.get(DramaEpisodeFragment, int(match[1]))+ episode = await db.get(DramaEpisode, fragment.episode_id) if fragment else None+ if episode:+ return episode.project_id, "episode", await episode_resource_id(db, episode.id)+ raise HTTPException(status_code=404, detail="分镜不存在")+ project_id = values.get("project_id")+ if not project_id:+ return None+ if suffix == "canvas":+ return int(project_id), "canvas", 0+ if suffix == "assets":+ return int(project_id), "asset", 0+ if suffix == "generation/voice":+ return int(project_id), "structure", 0+ if suffix.startswith("generation/"):+ return int(project_id), "asset", int(values.get("asset_id") or values.get("character_asset_id") or 0)+ if suffix in {"agents/episode_script", "episodes/confirm_from_script"} and values.get("episode_number"):+ return int(project_id), "episode", int(values["episode_number"])+ if suffix in {"ai/chat", "skills/optimize"}:+ return None+ return int(project_id), "structure", 0+++async def enforce_drama_write(request: Request, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)) -> None:+ """团队写操作必须持有当前资源租约,个人旧接口保持兼容。"""+ if request.method in {"GET", "HEAD", "OPTIONS"}:+ return+ # 取消走任务操作权限,不依赖等待释放的生成内容租约。+ if request.url.path.endswith(("/cancel_generate", "/cancel_video_jobs")):+ return+ values = dict(request.query_params)+ if "application/json" in request.headers.get("content-type", ""):+ try:+ body = await request.json()+ if isinstance(body, dict):+ values.update(body)+ except ValueError:+ return # 请求模型将提供标准 JSON 校验错误。+ try:+ target = await write_target(db, request.url.path, values)+ except (TypeError, ValueError) as exc:+ raise HTTPException(status_code=422, detail="无效的创作资源编号") from exc+ if not target:+ return+ project = await get_owned_drama_project(db, target[0], user)+ if project.team_id is None:+ # 与个人项目迁入串行,不能用迁入前的 identity-map 快照绕过团队租约。+ project = (await db.execute(select(DramaProject).where(DramaProject.id == project.id).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()+ if project is None:+ raise HTTPException(status_code=404, detail="漫剧项目不存在")+ if project.team_id is not None:+ raise HTTPException(status_code=409, detail="项目空间已变化,请刷新后重试")+ return+ if request.method == "DELETE" and re.search(r"/projects/\d+$", request.url.path):+ await require_drama_project_manager(db, project, user.id)+ if re.search(r"/scripts/\d+$", request.url.path) and "episode_content" in values:+ raise HTTPException(status_code=409, detail="团队剧本请按集保存,避免覆盖其他成员的修改")+ session_id = request.headers.get("X-Edit-Session", "")+ token = request.headers.get("X-Edit-Token", "")+ try:+ version = int(request.headers.get("X-Edit-Version", "0"))+ except ValueError as exc:+ raise HTTPException(status_code=422, detail="无效的编辑版本") from exc+ if not session_id or not token:+ raise HTTPException(status_code=428, detail="请先获取此内容的编辑权限")+ await validate_lock(db, project, user.id, target[1], target[2], session_id, token, version)+ # 批量任务在本次路由内部创建;新的 HTTP 请求不能越过既有系统写回占用。+ await _task_conflicts(db, project.id, (target[1], target[2]))+ db.info.update(team_edit_session_id=session_id, team_edit_token=token, team_edit_version=version,+ team_edit_resource=target[1:], team_edit_project_id=project.id)diff --git a/backend/app/team_schema.py b/backend/app/team_schema.pynew file mode 100644index 0000000..59966fb--- /dev/null+++ b/backend/app/team_schema.py@@ -0,0 +1,30 @@+"""团队模式增量迁移:旧个人记录均保持 team_id=NULL,不搬迁余额或历史账单。"""+from sqlalchemy import text+++async def apply_team_schema_patches(conn) -> None:+ """兼容既有 PostgreSQL 库,新增字段与索引均可重复执行。"""+ # 兼容早期本地团队原型表,保留旧余额字段与已有内容。+ await conn.execute(text("ALTER TABLE teams ADD COLUMN IF NOT EXISTS description VARCHAR(180) NOT NULL DEFAULT ''"))+ await conn.execute(text("ALTER TABLE teams ADD COLUMN IF NOT EXISTS color VARCHAR(7) NOT NULL DEFAULT '#435c4b'"))+ await conn.execute(text("ALTER TABLE teams ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now()"))+ await conn.execute(text("ALTER TABLE team_members ADD COLUMN IF NOT EXISTS active BOOLEAN NOT NULL DEFAULT true"))+ await conn.execute(text("ALTER TABLE team_members ADD COLUMN IF NOT EXISTS monthly_limit_fen INTEGER"))+ await conn.execute(text("ALTER TABLE team_members ADD COLUMN IF NOT EXISTS joined_at TIMESTAMPTZ NOT NULL DEFAULT now()"))+ legacy = set((await conn.execute(text("SELECT column_name FROM information_schema.columns WHERE table_schema='public' AND table_name='teams'"))).scalars().all())+ if {"balance_fen", "frozen_fen"} <= legacy:+ await conn.execute(text("ALTER TABLE teams ALTER COLUMN balance_fen SET DEFAULT 0"))+ await conn.execute(text("ALTER TABLE teams ALTER COLUMN frozen_fen SET DEFAULT 0"))+ await conn.execute(text("INSERT INTO team_wallets(team_id,balance_fen,frozen_fen) SELECT id,balance_fen,frozen_fen FROM teams ON CONFLICT(team_id) DO NOTHING"))+ await conn.execute(text("CREATE UNIQUE INDEX IF NOT EXISTS uq_team_membership ON team_members(team_id,user_id)"))+ await conn.execute(text("CREATE UNIQUE INDEX IF NOT EXISTS uq_team_active_owner ON team_members(team_id) WHERE role='owner' AND active IS TRUE"))+ for table in ("drama_projects", "task_runs", "usage_events", "orders"):+ await conn.execute(text(f"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS team_id INTEGER REFERENCES teams(id)"))+ await conn.execute(text(f"CREATE INDEX IF NOT EXISTS ix_{table}_team_id ON {table}(team_id)"))+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN IF NOT EXISTS billing_enabled_snapshot BOOLEAN"))+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN IF NOT EXISTS billing_period VARCHAR(7)"))+ await conn.execute(text("ALTER TABLE teams ADD COLUMN IF NOT EXISTS monthly_limit_fen INTEGER"))+ for table in ("task_runs", "usage_events"):+ await conn.execute(text(f"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS billing_payer_user_id INTEGER REFERENCES users(id)"))+ await conn.execute(text(f"CREATE INDEX IF NOT EXISTS ix_{table}_billing_payer_user_id ON {table}(billing_payer_user_id)"))+ await conn.execute(text("CREATE UNIQUE INDEX IF NOT EXISTS uq_team_admin_adjust_request ON team_wallet_ledger(team_id,ref_id) WHERE ref_type='admin_adjust'"))diff --git a/backend/scripts/prepare_team_schema.py b/backend/scripts/prepare_team_schema.pynew file mode 100644index 0000000..86927c2--- /dev/null+++ b/backend/scripts/prepare_team_schema.py@@ -0,0 +1,50 @@+"""为关闭启动建表的现有开发环境显式执行幂等增量迁移。"""+from __future__ import annotations++import asyncio+import os+from pathlib import Path+import sys+++async def prepare() -> None:+ """按项目既有顺序创建缺失表、补列和索引,不启动生成任务或种子流程。"""+ from sqlalchemy.ext.asyncio import create_async_engine++ from app.config import get_settings+ from app.database import init_db+ from app.main import _apply_schema_patches++ # 迁移连接独立于应用池,关闭 JIT 并限制语句/空闲事务,避免断连后长期持 DDL 锁。+ migration_engine = create_async_engine(get_settings().database_url, connect_args={+ "server_settings": {+ "application_name": "printfilm-team-schema",+ "jit": "off",+ "statement_timeout": "45000",+ "idle_in_transaction_session_timeout": "45000",+ },+ })+ try:+ await asyncio.wait_for(init_db(engine_override=migration_engine), timeout=60)+ await asyncio.wait_for(_apply_schema_patches(engine_override=migration_engine), timeout=60)+ finally:+ await migration_engine.dispose()+++def main() -> int:+ """使用 backend/.env 的现有连接配置,错误只报告类型,不输出凭据。"""+ backend = Path(__file__).resolve().parents[1]+ os.chdir(backend)+ sys.path.insert(0, str(backend))+ print("正在准备团队模式数据库结构……", flush=True)+ try:+ asyncio.run(prepare())+ except Exception as error:+ print(f"数据库准备未完成({type(error).__name__}),请检查连接后重试。", file=sys.stderr)+ return 1+ print("团队模式数据库结构已就绪。", flush=True)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/backend/tests/test_admin_team_balance.py b/backend/tests/test_admin_team_balance.pynew file mode 100644index 0000000..1994ff0--- /dev/null+++ b/backend/tests/test_admin_team_balance.py@@ -0,0 +1,68 @@+"""团队独立调账已退役;管理员改为设置两级月度上限。"""+import uuid+import pytest+from sqlalchemy import select+from app.models_teams import TeamMember+from app.models_team_billing import TeamWallet, TeamWalletLedger, TeamMonthlyUsage+from tests.test_admin_teams import bearer, team_admin_api # noqa: F401+++async def test_team_adjustment_retired_preserves_all_wallets(team_admin_api):+ """旧客户端不得通过团队入口调整任何账户资金。"""+ a = team_admin_api+ wallet = await a.db.get(TeamWallet, a.first.id)+ before = (a.owner.balance_fen, wallet.balance_fen, wallet.frozen_fen)+ r = await a.client.post(f"/api/admin/teams/{a.first.id}/balance-adjustments",+ json={"delta_fen": 500, "note": "旧入口", "request_id": str(uuid.uuid4())}, headers=bearer(a.admin))+ assert r.status_code == 410+ assert (a.owner.balance_fen, wallet.balance_fen, wallet.frozen_fen) == before+++async def test_admin_budget_can_set_total_and_owner_member_limit(team_admin_api):+ """总上限与成员上限相互独立,不重置消费、冻结或预留。"""+ a = team_admin_api+ url = f"/api/admin/teams/{a.first.id}"+ h = bearer(a.admin)+ before = a.owner.balance_fen+ for cap in (500, 0, None):+ r = await a.client.patch(url + "/budget", json={"monthly_limit_fen": cap}, headers=h)+ assert r.status_code == 200 and a.first.monthly_limit_fen == cap+ r = await a.client.patch(url + f"/members/{a.owner.id}/budget", json={"monthly_limit_fen": 100}, headers=h)+ assert r.status_code == 200+ m = (await a.db.execute(select(TeamMember).where(TeamMember.team_id == a.first.id, TeamMember.user_id == a.owner.id))).scalar_one()+ assert m.monthly_limit_fen == 100+ u = (await a.db.execute(select(TeamMonthlyUsage).where(TeamMonthlyUsage.team_id == a.first.id, TeamMonthlyUsage.user_id == a.owner.id))).scalar_one()+ assert (u.spent_fen, u.reserved_fen, a.owner.balance_fen) == (110, 20, before)++[email protected]("value", [-1, 1.5, True, "100", 100000001])+async def test_budget_rejects_invalid_amounts(team_admin_api, value):+ a = team_admin_api+ for suffix in ("/budget", f"/members/{a.owner.id}/budget"):+ r = await a.client.patch(f"/api/admin/teams/{a.first.id}" + suffix, json={"monthly_limit_fen": value}, headers=bearer(a.admin))+ assert r.status_code == 422+++async def test_budget_permissions_and_inactive_member(team_admin_api):+ a = team_admin_api+ url = f"/api/admin/teams/{a.first.id}"+ for suffix in ("/budget", f"/members/{a.owner.id}/budget"):+ assert (await a.client.patch(url + suffix, json={"monthly_limit_fen": 0}, headers=bearer(a.owner))).status_code == 403+ assert (await a.client.patch(url + suffix, json={"monthly_limit_fen": 0})).status_code == 401+ assert (await a.client.patch(url + f"/members/{a.former.id}/budget", json={"monthly_limit_fen": 0}, headers=bearer(a.admin))).status_code == 404+ assert (await a.client.patch("/api/admin/teams/987654321/budget", json={"monthly_limit_fen": 0}, headers=bearer(a.admin))).status_code == 404+++async def test_legacy_team_ledger_remains_readable(team_admin_api):+ """旧账目只读保留,操作者与备注仍可追溯。"""+ a = team_admin_api+ a.db.add(TeamWalletLedger(team_id=a.first.id, actor_user_id=a.admin.id, delta_fen=500, balance_after_fen=4321, kind="adjust", ref_type="admin_adjust", ref_id=str(uuid.uuid4()), note="历史补款"))+ await a.db.flush()+ r = await a.client.get(f"/api/admin/teams/{a.first.id}/wallet-ledger", params={"q": "历史补款", "adjustments_only": True}, headers=bearer(a.admin))+ assert r.status_code == 200 and r.json()["meta"]["total"] == 1+ assert r.json()["items"][0]["actor_user_id"] == a.admin.iddiff --git a/backend/tests/test_admin_teams.py b/backend/tests/test_admin_teams.pynew file mode 100644index 0000000..d1ff41c--- /dev/null+++ b/backend/tests/test_admin_teams.py@@ -0,0 +1,187 @@+"""管理端团队只读接口:平台权限、聚合、历史成员、消费隔离和分页。"""+from datetime import UTC, datetime+from types import SimpleNamespace+import uuid++from fastapi import FastAPI+from httpx import ASGITransport, AsyncClient+import pytest+import pytest_asyncio++from app.api.admin import router+from app.database import get_db+from app.models import UsageEvent+from app.models_drama import DramaProject+from app.models_teams import Team, TeamMember+from app.models_team_billing import TeamMonthlyUsage, TeamWallet+from app.services.auth import create_access_token+from app.services.billing.team import billing_period+from tests.conftest import make_user+++@pytest_asyncio.fixture+async def team_admin_api(db_session):+ """隔离测试库构造两个团队及个人消费,保留真实管理员鉴权链。"""+ db = db_session+ admin, owner, former, other = [await make_user(db) for _ in range(4)]+ admin.role = "admin"+ owner.nickname = "团队所有者"+ former.nickname = "历史创作者"+ prefix = "admin-teams-" + uuid.uuid4().hex[:8]+ first = Team(name=prefix + "-A", owner_user_id=owner.id)+ second = Team(name=prefix + "-B", owner_user_id=other.id)+ db.add_all([first, second])+ await db.flush()+ db.add_all([+ TeamMember(team_id=first.id, user_id=owner.id, role="owner"),+ TeamMember(team_id=first.id, user_id=former.id, role="member", active=False, monthly_limit_fen=500),+ TeamMember(team_id=second.id, user_id=other.id, role="owner"),+ TeamWallet(team_id=first.id, balance_fen=4321, frozen_fen=100),+ TeamMonthlyUsage(team_id=first.id, user_id=owner.id, period=billing_period(), spent_fen=110, reserved_fen=20),+ TeamMonthlyUsage(team_id=first.id, user_id=former.id, period=billing_period(), spent_fen=30, reserved_fen=0),+ TeamMonthlyUsage(team_id=first.id, user_id=former.id, period="2000-01", spent_fen=60, reserved_fen=0),+ ])+ project = DramaProject(team_id=first.id, user_id=owner.id, title="团队测试剧本")+ db.add(project)+ await db.flush()+ events = [+ UsageEvent(team_id=first.id, user_id=former.id, drama_project_id=project.id,+ billing_key="drama_text", model="team-model", charge_fen=30, cost_fen=12, settled=True,+ created_at=datetime(2026, 10, 21, 16, 0, tzinfo=UTC)),+ UsageEvent(team_id=first.id, user_id=owner.id, drama_project_id=987654321,+ billing_key="drama_text", model="pending-model", charge_fen=90, settled=False,+ created_at=datetime(2026, 10, 22, 15, 59, 59, 999999, tzinfo=UTC)),+ UsageEvent(team_id=first.id, user_id=owner.id, billing_key="drama_text", charge_fen=7, settled=True,+ created_at=datetime(2026, 10, 22, 16, 0, tzinfo=UTC)),+ UsageEvent(team_id=None, user_id=former.id, billing_key="drama_text", charge_fen=9999, settled=True),+ UsageEvent(team_id=second.id, user_id=other.id, billing_key="drama_text", charge_fen=8888, settled=True),+ ]+ db.add_all(events)+ await db.commit()+ app = FastAPI()+ app.include_router(router, prefix="/api")++ async def override_db():+ """API 与 fixture 共用可回滚的会话。"""+ yield db++ app.dependency_overrides[get_db] = override_db+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:+ yield SimpleNamespace(client=client, db=db, admin=admin, owner=owner, former=former,+ first=first, second=second, prefix=prefix, events=events)+++def bearer(user):+ """为测试账号签发正常 JWT,不绕过管理员依赖。"""+ return {"Authorization": "Bearer " + create_access_token(str(user.id))}+++async def test_team_list_aggregates_without_join_multiplication(team_admin_api):+ """多个成员和月份不会重复计数,空钱包只读返回零。"""+ a = team_admin_api+ r = await a.client.get("/api/admin/teams", params={"q": a.prefix}, headers=bearer(a.admin))+ assert r.status_code == 200+ body = r.json()+ assert body["meta"]["total"] == 2+ rows = {row["id"]: row for row in body["items"]}+ first = rows[a.first.id]+ assert (first["member_count"], first["project_count"]) == (1, 1)+ assert (first["balance_fen"], first["frozen_fen"]) == (a.owner.balance_fen, a.owner.frozen_fen)+ assert (first["month_spent_fen"], first["total_spent_fen"]) == (140, 200)+ assert first["owner_email"] == a.owner.email+ assert rows[a.second.id]["balance_fen"] == 100000+ assert await a.db.get(TeamWallet, a.second.id) is None+ assert "hashed_password" not in str(body) and "token_hash" not in str(body)+++async def test_team_list_search_and_server_pagination(team_admin_api):+ """支持团队/所有者搜索以及服务端总数与稳定分页。"""+ a = team_admin_api+ headers = bearer(a.admin)+ for query in (str(a.first.id), a.owner.email, a.first.name):+ r = await a.client.get("/api/admin/teams", params={"q": query, "owner_id": a.owner.id}, headers=headers)+ assert [x["id"] for x in r.json()["items"]] == [a.first.id]+ r = await a.client.get("/api/admin/teams", params={"q": a.prefix, "page": 2, "page_size": 1}, headers=headers)+ assert r.json()["meta"] == {"page": 2, "page_size": 1, "total": 2}+ assert r.json()["items"][0]["id"] == a.first.id+++async def test_admin_outside_team_can_read_detail_and_missing_is_404(team_admin_api):+ """平台管理员无需加入团队;不存在的团队在全部子入口统一 404。"""+ a = team_admin_api+ headers = bearer(a.admin)+ r = await a.client.get(f"/api/admin/teams/{a.first.id}", headers=headers)+ assert r.status_code == 200 and r.json()["id"] == a.first.id+ for suffix in ("", "/members", "/usage-events"):+ assert (await a.client.get("/api/admin/teams/987654321" + suffix, headers=headers)).status_code == 404+++async def test_team_members_include_removed_and_preserve_monthly_usage(team_admin_api):+ """历史成员可查,退出不会清掉历史消费;月份、角色、状态与搜索均生效。"""+ a = team_admin_api+ url = f"/api/admin/teams/{a.first.id}/members"+ headers = bearer(a.admin)+ r = await a.client.get(url, params={"state": "all", "page_size": 1}, headers=headers)+ assert r.json()["meta"]["total"] == 2 and len(r.json()["items"]) == 1+ r = await a.client.get(url, params={"state": "removed", "q": "历史", "role": "member"}, headers=headers)+ row = r.json()["items"][0]+ assert row["user_id"] == a.former.id and row["active"] is False+ assert row["spent_fen"] == 30 and row["monthly_limit_fen"] == 500+ r = await a.client.get(url, params={"state": "removed", "period": "2000-01"}, headers=headers)+ assert r.json()["items"][0]["spent_fen"] == 60+ assert (await a.client.get(url, params={"state": "active"}, headers=headers)).json()["meta"]["total"] == 1+++async def test_team_usage_isolation_dates_filters_and_totals(team_admin_api):+ """个人/其他团队消费被隔离;上海整日包含最后一秒小数,汇总不随分页改变。"""+ a = team_admin_api+ url = f"/api/admin/teams/{a.first.id}/usage-events"+ headers = bearer(a.admin)+ r = await a.client.get(url, params={"date_from": "2026-10-22", "date_to": "2026-10-22", "page_size": 1}, headers=headers)+ body = r.json()+ assert body["meta"]["total"] == 2+ assert body["summary"]["settled_charge_fen"] == 30+ assert body["summary"]["record_count"] == 2+ assert body["items"][0]["project_title"] is None+ assert "raw_usage_json" not in str(body)+ r = await a.client.get(url, params={"q": "team-model", "user_id": a.former.id, "settled": True}, headers=headers)+ row = r.json()["items"][0]+ assert r.json()["meta"]["total"] == 1 and row["charge_fen"] == 30+ assert row["project_title"] == "团队测试剧本" and row["user_email"] == a.former.email+ r = await a.client.get(url, params={"settled": False}, headers=headers)+ assert r.json()["summary"]["settled_charge_fen"] == 0+ assert r.json()["items"][0]["id"] == a.events[1].id+ r = await a.client.get(url, params={"date_to": "9999-12-31"}, headers=headers)+ assert r.status_code == 200 and r.json()["meta"]["total"] == 3++[email protected]("suffix", ["", "/{id}", "/{id}/members", "/{id}/usage-events"])+async def test_team_admin_routes_enforce_platform_admin(team_admin_api, suffix):+ """未登录为401,团队所有者仍不能越过平台管理员权限。"""+ a = team_admin_api+ url = "/api/admin/teams" + suffix.format(id=a.first.id)+ assert (await a.client.get(url)).status_code == 401+ assert (await a.client.get(url, headers=bearer(a.owner))).status_code == 403+++async def test_admin_team_filters_validate_input(team_admin_api):+ """拒绝倒置日期、非法角色/月份与越界分页。"""+ a = team_admin_api+ headers = bearer(a.admin)+ for path, params in [+ ("/api/admin/teams", {"page_size": 101}),+ ("/api/admin/teams", {"owner_id": 999999999999}),+ ("/api/admin/teams/999999999999", {}),+ (f"/api/admin/teams/{a.first.id}/members", {"role": "root"}),+ (f"/api/admin/teams/{a.first.id}/members", {"period": "2026-13"}),+ (f"/api/admin/teams/{a.first.id}/usage-events", {"date_from": "2026-10-23", "date_to": "2026-10-22"}),+ (f"/api/admin/teams/{a.first.id}/usage-events", {"user_id": 999999999999}),+ ]:+ assert (await a.client.get(path, params=params, headers=headers)).status_code == 422diff --git a/backend/tests/test_team_billing.py b/backend/tests/test_team_billing.pynew file mode 100644index 0000000..45c3030--- /dev/null+++ b/backend/tests/test_team_billing.py@@ -0,0 +1,295 @@+"""Team wallet money isolation and reservation lifecycle (isolated test database)."""+from unittest.mock import AsyncMock+import pytest+from sqlalchemy import select+from app.models import UsageEvent, WalletLedger+from app.models_tasks import TaskRun+from app.services.billing.settlement import ensure_balance_for_task, freeze_for_task, settle_task+from conftest import make_user+++async def seed_team(db, *, limit=1000, balance=2000):+ from app.models_teams import Team, TeamMember+ from app.models_team_billing import TeamWallet+ owner = await make_user(db, balance_fen=balance)+ member = await make_user(db, balance_fen=90000)+ team = Team(name="测试团队", owner_user_id=owner.id)+ db.add(team)+ await db.flush()+ db.add_all([+ TeamMember(team_id=team.id, user_id=owner.id, role="owner", active=True),+ TeamMember(team_id=team.id, user_id=member.id, role="member", active=True, monthly_limit_fen=limit),+ TeamWallet(team_id=team.id, balance_fen=0, frozen_fen=0),+ ])+ await db.flush()+ return team, owner, member+++async def enqueue(db, member, team, monkeypatch, *, estimate=300):+ monkeypatch.setattr("app.services.billing.estimates.estimate_task_fen", AsyncMock(return_value=estimate))+ monkeypatch.setattr("app.services.billing.settlement.estimate_task_fen", AsyncMock(return_value=estimate))+ task = TaskRun(team_id=team.id, requested_by=member.id, domain="drama", task_type="asset_image", status="pending", billing_status="none", payload={})+ task.billing_estimate_fen = await ensure_balance_for_task(db, member, task)+ db.add(task)+ await db.flush()+ return task+++async def test_team_reserve_freeze_settle_isolated_and_idempotent(db_session, monkeypatch):+ from app.models_team_billing import TeamWallet, TeamMonthlyUsage, TeamWalletLedger+ team, owner, member = await seed_team(db_session)+ task = await enqueue(db_session, member, team, monkeypatch)+ usage = (await db_session.execute(select(TeamMonthlyUsage).where(TeamMonthlyUsage.user_id == member.id))).scalar_one()+ assert usage.reserved_fen == 300+ assert task.billing_status == "reserved"+ await freeze_for_task(db_session, task)+ await freeze_for_task(db_session, task)+ wallet = owner+ assert (wallet.balance_fen, wallet.frozen_fen, member.balance_fen) == (1700, 300, 90000)+ db_session.add(UsageEvent(user_id=member.id, team_id=team.id, task_run_id=task.id, billing_key="seedream", charge_fen=180, cost_fen=120, settled=False))+ await db_session.flush()+ assert await settle_task(db_session, task.id) == {"charged": 180, "refunded": 120}+ assert await settle_task(db_session, task.id) == {"charged": 180, "refunded": 120}+ assert (wallet.balance_fen, wallet.frozen_fen, usage.spent_fen, usage.reserved_fen) == (1820, 0, 180, 0)+ assert len((await db_session.execute(select(WalletLedger).where(WalletLedger.user_id == owner.id))).scalars().all()) == 3+++async def test_team_monthly_limit_counts_queued_reservations(db_session, monkeypatch):+ team, owner, member = await seed_team(db_session, limit=500)+ await enqueue(db_session, member, team, monkeypatch)+ with pytest.raises(ValueError, match="额度"):+ await enqueue(db_session, member, team, monkeypatch)+++async def test_team_insufficient_wallet_does_not_use_personal_balance(db_session, monkeypatch):+ team, owner, member = await seed_team(db_session, balance=100)+ with pytest.raises(ValueError, match="余额不足"):+ await enqueue(db_session, member, team, monkeypatch)+ assert member.balance_fen == 90000+++async def test_cancel_before_start_releases_team_budget(db_session, monkeypatch):+ from app.models_team_billing import TeamWallet, TeamMonthlyUsage+ team, owner, member = await seed_team(db_session)+ task = await enqueue(db_session, member, team, monkeypatch)+ task.status = "cancelled"+ await settle_task(db_session, task.id)+ wallet = owner+ usage = (await db_session.execute(select(TeamMonthlyUsage).where(TeamMonthlyUsage.user_id == member.id))).scalar_one()+ assert (wallet.balance_fen, wallet.frozen_fen, usage.reserved_fen) == (2000, 0, 0)+++async def test_disabled_team_billing_keeps_zero_charge_and_no_budget(db_session, monkeypatch):+ from app.config import get_settings+ from app.models_team_billing import TeamWallet, TeamMonthlyUsage+ from app.services.billing.usage import record_line+ team, owner, member = await seed_team(db_session, limit=0, balance=0)+ monkeypatch.setattr(get_settings(), "billing_enabled", False)+ task = await enqueue(db_session, member, team, monkeypatch)+ await freeze_for_task(db_session, task)+ event = await record_line(db_session, user_id=owner.id, task_run_id=task.id, billing_key="seedream", tokens=100)+ assert (event.user_id, event.team_id, event.charge_fen) == (member.id, team.id, 0)+ assert await settle_task(db_session, task.id) == {"charged": 0, "refunded": 0}+ assert (await db_session.get(TeamWallet, team.id)).balance_fen == 0+ assert not (await db_session.execute(select(TeamMonthlyUsage).where(TeamMonthlyUsage.team_id == team.id))).scalars().all()+++async def test_team_overage_settles_actual_after_member_removed(db_session, monkeypatch):+ from app.models_teams import TeamMember+ from app.models_team_billing import TeamWallet, TeamMonthlyUsage+ team, owner, member = await seed_team(db_session)+ task = await enqueue(db_session, member, team, monkeypatch)+ await freeze_for_task(db_session, task)+ membership = (await db_session.execute(select(TeamMember).where(TeamMember.team_id == team.id, TeamMember.user_id == member.id))).scalar_one()+ membership.active = False+ db_session.add(UsageEvent(user_id=member.id, team_id=team.id, task_run_id=task.id, billing_key="seedream", charge_fen=450, cost_fen=120, settled=False))+ await db_session.flush()+ assert await settle_task(db_session, task.id) == {"charged": 450, "refunded": 0}+ assert owner.balance_fen == 1550+ usage = (await db_session.execute(select(TeamMonthlyUsage).where(TeamMonthlyUsage.user_id == member.id))).scalar_one()+ assert (usage.spent_fen, usage.reserved_fen) == (450, 0)+++def test_period_uses_beijing_month_boundary():+ from datetime import UTC, datetime+ from app.services.billing.team import billing_period+ assert billing_period(datetime(2026, 9, 30, 15, 59, tzinfo=UTC)) == "2026-09"+ assert billing_period(datetime(2026, 9, 30, 16, 0, tzinfo=UTC)) == "2026-10"+++async def test_team_wallet_and_usage_http_authorization(db_session):+ import httpx+ from fastapi import FastAPI+ from app.api.team_billing import router+ from app.database import get_db+ from app.deps import get_current_user+ from app.models_team_billing import TeamMonthlyUsage+ from app.services.billing.team import billing_period+ team, owner, member = await seed_team(db_session)+ db_session.add_all([TeamMonthlyUsage(team_id=team.id, user_id=owner.id, period=billing_period(), spent_fen=900, reserved_fen=100), TeamMonthlyUsage(team_id=team.id, user_id=member.id, period=billing_period(), spent_fen=200, reserved_fen=300)])+ await db_session.flush()+ app = FastAPI()+ app.include_router(router)+ async def current_db():+ yield db_session+ app.dependency_overrides[get_db] = current_db+ app.dependency_overrides[get_current_user] = lambda: member+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://test") as client:+ assert (await client.get(f"/teams/{team.id}/wallet")).status_code == 403+ response = await client.get(f"/teams/{team.id}/usage/summary")+ assert response.status_code == 200+ assert response.json()["spent_fen"] == 200+ assert "balance_fen" not in response.json()+ assert (await client.get(f"/teams/{team.id}/usage/records?member_id={owner.id}")).status_code == 403+ app.dependency_overrides[get_current_user] = lambda: owner+ response = await client.get(f"/teams/{team.id}/usage/summary")+ assert response.json()["spent_fen"] == 1100+ assert response.json()["balance_fen"] == 2000+++async def test_legacy_team_callback_credits_original_payer_once(db_session, monkeypatch):+ import httpx+ from fastapi import FastAPI+ from app.api.billing import router+ from app.database import get_db+ from app.models import Order+ from app.models_team_billing import TeamWallet+ team, owner, member = await seed_team(db_session)+ order = Order(out_trade_no=f"team-test-{team.id}", team_id=team.id, user_id=owner.id, sku_id="test", amount_fen=100, credit_fen=150, pay_type="alipay", status="pending")+ db_session.add(order)+ await db_session.flush()+ from app.services.teams.management import transfer_ownership+ await transfer_ownership(db_session, team.id, owner.id, member.id)+ monkeypatch.setattr("app.api.billing.epay.verify", lambda params: True)+ app = FastAPI()+ app.include_router(router)+ async def current_db():+ yield db_session+ app.dependency_overrides[get_db] = current_db+ params = {"out_trade_no": order.out_trade_no, "money": "1.00", "trade_status": "TRADE_SUCCESS"}+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://test") as client:+ assert (await client.get("/billing/epay/notify", params=params)).status_code == 200+ assert (await client.get("/billing/epay/notify", params=params)).status_code == 200+ assert (await db_session.get(TeamWallet, team.id)).balance_fen == 0+ assert owner.balance_fen == 2150+++async def test_team_callback_rejects_malformed_amount(db_session, monkeypatch):+ import httpx+ from fastapi import FastAPI+ from app.api.billing import router+ from app.database import get_db+ from app.models import Order+ team, owner, member = await seed_team(db_session)+ order = Order(out_trade_no=f"bad-team-{team.id}", team_id=team.id, user_id=owner.id, sku_id="test", amount_fen=100, credit_fen=150, pay_type="alipay", status="pending")+ db_session.add(order)+ await db_session.flush()+ monkeypatch.setattr("app.api.billing.epay.verify", lambda params: True)+ app = FastAPI()+ app.include_router(router)+ async def current_db():+ yield db_session+ app.dependency_overrides[get_db] = current_db+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://test") as client:+ for amount in ("NaN", "", "1.001", "-1"):+ response = await client.get("/billing/epay/notify", params={"out_trade_no": order.out_trade_no, "money": amount, "trade_status": "TRADE_SUCCESS"})+ assert response.status_code == 400+ assert order.status == "pending"+++async def test_personal_history_excludes_team_charges_and_orders(db_session):+ from app.api.billing import list_orders, usage_events, usage_summary+ from app.models import Order+ team, owner, member = await seed_team(db_session)+ db_session.add(UsageEvent(user_id=owner.id, team_id=team.id, billing_key="seedream", charge_fen=100, cost_fen=80))+ db_session.add(Order(out_trade_no=f"history-{team.id}", team_id=team.id, user_id=owner.id, sku_id="test", amount_fen=100, credit_fen=150, pay_type="alipay", status="pending"))+ await db_session.flush()+ result = await usage_events(page=1, page_size=20, db=db_session, user=owner)+ assert result["items"] == []+ assert (await usage_summary(db=db_session, user=owner))["charge_fen"] == 0+ assert (await list_orders(db=db_session, user=owner, limit=50))["orders"] == []++[email protected]("cap_scope", ["member", "team"])+async def test_postgres_concurrent_budget_and_settlement_are_serialized(db_session, monkeypatch, cap_scope):+ """Two real independent PG transactions cannot bypass the same monthly budget."""+ import asyncio+ from sqlalchemy import delete+ from sqlalchemy.engine.url import make_url+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine+ from app.config import get_settings+ from app.models import User+ from app.models_teams import Team, TeamMember+ from app.models_team_billing import TeamMonthlyUsage, TeamWallet, TeamWalletLedger+ from conftest import _resolve_test_database_url+ url, _ = _resolve_test_database_url(get_settings().database_url)+ assert "test" in (make_url(url).database or "")+ engine = create_async_engine(url, pool_pre_ping=True)+ sessions = async_sessionmaker(engine, expire_on_commit=False)+ team_id = None+ user_ids = []+ monkeypatch.setattr("app.services.billing.settlement.estimate_task_fen", AsyncMock(return_value=300))+ try:+ async with sessions() as db:+ team, owner, member = await seed_team(db, limit=500 if cap_scope == "member" else None)+ if cap_scope == "team":+ team.monthly_limit_fen = 500+ team_id = team.id+ user_ids = [owner.id, member.id]+ member_id = member.id+ await db.commit()+ async def submit(actor_id):+ async with sessions() as db:+ actor = await db.get(User, actor_id)+ task = TaskRun(team_id=team_id, requested_by=actor_id, domain="drama", task_type="asset_image", status="pending", billing_status="none", payload={})+ try:+ task.billing_estimate_fen = await ensure_balance_for_task(db, actor, task)+ db.add(task)+ await db.flush()+ task_id = task.id+ await db.commit()+ return task_id+ except ValueError:+ await db.rollback()+ return None+ submitted = await asyncio.gather(submit(member_id), submit(member_id if cap_scope == "member" else user_ids[0]))+ assert sum(ident is not None for ident in submitted) == 1+ task_id = next(ident for ident in submitted if ident is not None)+ async with sessions() as db:+ task = await db.get(TaskRun, task_id)+ await freeze_for_task(db, task)+ db.add(UsageEvent(user_id=member_id, team_id=team_id, task_run_id=task_id, billing_key="seedream", charge_fen=180, cost_fen=120, settled=False))+ await db.commit()+ async def settle():+ async with sessions() as db:+ result = await settle_task(db, task_id)+ await db.commit()+ return result+ assert await asyncio.gather(settle(), settle()) == [{"charged": 180, "refunded": 120}] * 2+ async with sessions() as db:+ wallet = await db.get(User, user_ids[0])+ assert (wallet.balance_fen, wallet.frozen_fen) == (1820, 0)+ monthly = (await db.execute(select(TeamMonthlyUsage).where(TeamMonthlyUsage.team_id == team_id))).scalar_one()+ assert (monthly.spent_fen, monthly.reserved_fen) == (180, 0)+ finally:+ if team_id is not None:+ # Only remove rows belonging to this test's newly committed team/users.+ async with sessions() as db:+ for model in (UsageEvent, TaskRun, TeamMonthlyUsage, TeamWalletLedger, TeamWallet, TeamMember):+ await db.execute(delete(model).where(model.team_id == team_id))+ await db.execute(delete(Team).where(Team.id == team_id))+ await db.execute(delete(WalletLedger).where(WalletLedger.user_id.in_(user_ids)))+ await db.execute(delete(User).where(User.id.in_(user_ids)))+ await db.commit()+ await engine.dispose()diff --git a/backend/tests/test_team_content.py b/backend/tests/test_team_content.pynew file mode 100644index 0000000..4b00275--- /dev/null+++ b/backend/tests/test_team_content.py@@ -0,0 +1,232 @@+"""团队内容 API:项目归属迁入和本地媒体独立复制的真实 PostgreSQL 测试。"""+from datetime import UTC, datetime, timedelta++import pytest+import pytest_asyncio+from sqlalchemy import select++from app.api.team_content import personal_router, router+from app.models import UsageEvent+from app.models_drama import DramaAsset, DramaEpisode, DramaProject, DramaScript+from app.models_team_locks import TeamEditLock+from app.models_tasks import TaskRun+from app.models_teams import Team, TeamMember+from app.services.teams.edit_locks import acquire_lock+from tests.test_teams_api import teams_api # noqa: F401+++@pytest_asyncio.fixture+async def content_api(teams_api, monkeypatch, tmp_path):+ """复用认证/事务 fixture,所有媒体读写仅进入 pytest 临时目录。"""+ teams_api.app.include_router(router, prefix="/api")+ teams_api.app.include_router(personal_router, prefix="/api")+ monkeypatch.setattr("app.services.storage.STATIC_ROOT", tmp_path)+ monkeypatch.setattr("app.services.storage.GENERATED_ROOT", tmp_path / "generated")+ teams_api.static_root = tmp_path+ return teams_api+++async def project(a, *, team_id=None, user_id=None, title="项目"):+ """创建不触发模型任务的最小漫剧项目。"""+ row = DramaProject(user_id=user_id or a.owner.id, team_id=team_id, title=title, params={"episode_count": 2})+ a.db.add(row)+ await a.db.flush()+ return row+++async def copy_headers(a, target):+ """获取真实目标 asset:0 租约供资产复制接口复核。"""+ lock = await acquire_lock(a.db, a.team_id, a.owner.id, target.id, "asset", 0, "copy-test")+ return {"X-Edit-Session": "copy-test", "X-Edit-Token": lock["token"], "X-Edit-Version": str(lock["version"])}+++async def test_team_content_lists_are_paginated_and_scoped(content_api):+ """团队列表排除个人和其他团队,搜索/类型/项目筛选在服务端生效。"""+ a = content_api+ first = await project(a, team_id=a.team_id, title="长安故事")+ await project(a, team_id=a.team_id, title="夏日")+ await project(a, title="个人长安")+ a.db.add(DramaAsset(project_id=first.id, type="character", asset_type="image", name="长安角色", params={"description": "角色介绍"}))+ await a.db.commit()+ response = await a.client.get(f"/api/teams/{a.team_id}/projects", params={"q": "长安", "page_size": 1})+ assert response.status_code == 200, response.text+ assert response.json()["meta"]["total"] == 1+ assert response.json()["items"][0]["id"] == first.id+ assert response.json()["items"][0]["status"] == "draft"+ response = await a.client.get(f"/api/teams/{a.team_id}/assets", params={"type": "character", "project_id": first.id, "q": "长安"})+ assert response.json()["meta"]["total"] == 1+ assert response.json()["items"][0]["description"] == "角色介绍"+ a.auth["user"] = a.outsider+ assert (await a.client.get(f"/api/teams/{a.team_id}/projects")).status_code == 404+ assert (await a.client.get(f"/api/teams/{a.team_id}/assets")).status_code == 404+++async def test_team_content_create_requires_real_source(content_api):+ """创建沿用真实漫剧数据结构;短创意被拒绝,不伪造创意或启动生成。"""+ a = content_api+ path = f"/api/teams/{a.team_id}/projects"+ assert (await a.client.post(path, json={"title": "测试", "source": "太短", "episode_count": 2})).status_code == 422+ source = "这是由用户亲自提供的一段足够长的原始创意,用于创建真实团队项目。"+ created = await a.client.post(path, json={"title": "新作品", "source": source, "episode_count": 3})+ assert created.status_code == 201, created.text+ body = created.json()+ assert body["team_id"] == a.team_id+ assert body["script"]["source"] == source+ assert await a.db.scalar(select(TaskRun.id).where(TaskRun.drama_project_id == body["id"])) is None+++async def test_team_content_transfer_refuses_busy_then_preserves_id_and_old_costs(content_api):+ """迁入仅允许本人空闲项目,保留项目 ID、历史个人任务和费用归属。"""+ a = content_api+ row = await project(a, title="待迁入")+ script = DramaScript(project_id=row.id, name="剧本", episode_content={"episodes": [{"body": "第一集"}, {"episodeNumber": 1, "body": "第二集"}, {"episodeNumber": 1, "body": "第三集"}]})+ a.db.add(script)+ task = TaskRun(domain="drama", task_type="script_summary", requested_by=a.owner.id, drama_project_id=row.id, status="pending", billing_status="none")+ usage = UsageEvent(user_id=a.owner.id, drama_project_id=row.id, billing_key="llm_chat", charge_fen=123, cost_fen=123, settled=True)+ a.db.add_all([task, usage])+ await a.db.commit()+ listing = await a.client.get(f"/api/teams/{a.team_id}/transferable-projects")+ assert listing.json()["items"][0]["transferable"] is False+ path = f"/api/teams/{a.team_id}/projects/{row.id}/transfer"+ assert (await a.client.post(path)).status_code == 409+ task.status = "succeeded"+ await a.db.commit()+ transferred = await a.client.post(path)+ assert transferred.status_code == 200, transferred.text+ assert transferred.json()["id"] == row.id+ assert transferred.json()["team_id"] == a.team_id+ await a.db.refresh(task)+ await a.db.refresh(usage)+ assert task.team_id is None and usage.team_id is None and usage.charge_fen == 123+ await a.db.refresh(script)+ rows = script.episode_content["episodes"]+ assert len({item["episodeNumber"] for item in rows}) == 3+ assert [item["body"] for item in rows] == ["第一集", "第二集", "第三集"]+ assert (await a.client.post(path)).status_code == 200+++async def test_team_content_transfer_foreign_team_and_live_lease_are_rejected(content_api):+ """不可迁入别人或其他团队的项目,存活人工租约同样阻止迁入。"""+ a = content_api+ foreign = await project(a, user_id=a.outsider.id)+ assert (await a.client.post(f"/api/teams/{a.team_id}/projects/{foreign.id}/transfer")).status_code == 404+ other = Team(name="其他团队", owner_user_id=a.owner.id)+ a.db.add(other)+ await a.db.flush()+ a.db.add(TeamMember(team_id=other.id, user_id=a.owner.id, role="owner"))+ owned_elsewhere = await project(a, team_id=other.id)+ leased = await project(a)+ a.db.add(TeamEditLock(team_id=a.team_id, project_id=leased.id, resource_type="structure", resource_id=0, user_id=a.owner.id, session_id="old", token_hash="0" * 64, version=1, expires_at=datetime.now(UTC) + timedelta(minutes=1)))+ await a.db.commit()+ assert (await a.client.post(f"/api/teams/{a.team_id}/projects/{owned_elsewhere.id}/transfer")).status_code == 409+ assert (await a.client.post(f"/api/teams/{a.team_id}/projects/{leased.id}/transfer")).status_code == 409+++async def test_team_content_copy_is_independent_and_cleans_source_runtime_params(content_api):+ """复制创建新资产 ID、独立本地媒体并清除生成状态与旧画布/资源关联。"""+ a = content_api+ source, target = await project(a, team_id=a.team_id), await project(a, team_id=a.team_id)+ media = a.static_root / "generated" / f"p{source.id}" / "portrait.png"+ media.parent.mkdir(parents=True)+ media.write_bytes(b"test-local-media")+ source_url = f"/static/generated/p{source.id}/portrait.png"+ asset = DramaAsset(project_id=source.id, type="character", asset_type="image", name="角色", cover=source_url, url=source_url, params={"description": "保留设定", "generation": {"status": "running"}, "canvas_node_id": "old", "project_id": source.id, "reference_asset_ids": [999], "image_versions": [{"url": source_url}]})+ a.db.add(asset)+ await a.db.commit()+ path = f"/api/teams/{a.team_id}/assets/{asset.id}/copy"+ assert (await a.client.post(path, json={"project_id": target.id})).status_code == 428+ response = await a.client.post(path, json={"project_id": target.id}, headers=await copy_headers(a, target))+ assert response.status_code == 201, response.text+ copied = response.json()+ assert copied["id"] != asset.id and copied["project_id"] == target.id+ assert copied["params"]["description"] == "保留设定"+ assert set(copied["params"]).isdisjoint({"generation", "canvas_node_id", "project_id", "reference_asset_ids"})+ assert f"/p{target.id}/" in copied["url"] and copied["cover"] == copied["url"]+ destination = a.static_root / copied["url"].removeprefix("/static/")+ assert destination.read_bytes() == b"test-local-media"+ media.unlink()+ assert destination.exists()+ assert copied["params"]["image_versions"][0]["url"] == copied["url"]+++async def test_team_content_copy_cross_team_or_uncontrolled_url_rejected(content_api):+ """复制不下载任意外网 URL,源与目标必须同属当前团队。"""+ a = content_api+ target = await project(a, team_id=a.team_id)+ personal = await project(a)+ own = await project(a, team_id=a.team_id)+ foreign = DramaAsset(project_id=personal.id, type="character", name="个人素材")+ remote = DramaAsset(project_id=own.id, type="scene", name="远程素材", url="http://127.0.0.1:1234/private")+ a.db.add_all([foreign, remote])+ await a.db.commit()+ headers = await copy_headers(a, target)+ path = f"/api/teams/{a.team_id}/assets"+ assert (await a.client.post(f"{path}/{foreign.id}/copy", json={"project_id": target.id}, headers=headers)).status_code == 404+ assert (await a.client.post(f"{path}/{remote.id}/copy", json={"project_id": target.id}, headers=headers)).status_code == 409+++async def test_team_content_descendant_tasks_only_block_their_own_project(content_api):+ """历史仅关联子资产的任务不能漏判,也不能污染其他个人项目的迁入状态。"""+ a = content_api+ busy = await project(a, title="繁忙")+ idle = await project(a, title="空闲")+ asset = DramaAsset(project_id=busy.id, type="character", name="占用资产")+ a.db.add(asset)+ await a.db.flush()+ a.db.add(TaskRun(domain="drama", task_type="asset_image", requested_by=a.owner.id, asset_id=asset.id, status="running", billing_status="none"))+ await a.db.commit()+ result = (await a.client.get(f"/api/teams/{a.team_id}/transferable-projects")).json()+ rows = {row["id"]: row for row in result["items"]}+ assert rows[busy.id]["transferable"] is False+ assert rows[idle.id]["transferable"] is True+ assert (await a.client.post(f"/api/teams/{a.team_id}/projects/{busy.id}/transfer")).status_code == 409+++async def test_team_content_personal_copy_requires_both_projects_owned_by_current_user(content_api):+ """个人复制不需要团队租约,但不能读取其他用户的个人资产或媒体文件。"""+ a = content_api+ source, target, foreign = await project(a), await project(a), await project(a, user_id=a.outsider.id)+ asset = DramaAsset(project_id=source.id, type="prop", name="个人道具", params={"description": "副本内容"})+ foreign_asset = DramaAsset(project_id=foreign.id, type="prop", name="他人素材")+ a.db.add_all([asset, foreign_asset])+ await a.db.commit()+ path = "/api/drama/assets"+ result = await a.client.post(f"{path}/{asset.id}/copy", json={"project_id": target.id})+ assert result.status_code == 201, result.text+ assert result.json()["id"] != asset.id+ assert (await a.client.post(f"{path}/{foreign_asset.id}/copy", json={"project_id": target.id})).status_code == 404+ assert (await a.client.post(f"{path}/{asset.id}/copy", json={"project_id": foreign.id})).status_code == 404+ foreign_dir = a.static_root / "generated" / f"p{foreign.id}"+ foreign_dir.mkdir(parents=True)+ (foreign_dir / "secret.png").write_bytes(b"private")+ asset.url = f"/static/generated/p{foreign.id}/secret.png"+ await a.db.commit()+ assert (await a.client.post(f"{path}/{asset.id}/copy", json={"project_id": target.id})).status_code == 409+++async def test_team_content_project_status_filters_and_legacy_params(content_api):+ """完成状态来自真实视频,不因畸形旧 episode_count 让整个列表崩溃。"""+ from app.models_drama import DramaEpisodeFragment++ a = content_api+ completed = await project(a, team_id=a.team_id)+ completed.params = {"episode_count": 1}+ episode = DramaEpisode(project_id=completed.id, name="第一集")+ a.db.add(episode)+ await a.db.flush()+ a.db.add(DramaEpisodeFragment(episode_id=episode.id, sort_order=1, video="https://storage.example.com/video.mp4"))+ malformed = await project(a, team_id=a.team_id)+ malformed.params = {"episode_count": "unknown"}+ await a.db.commit()+ result = await a.client.get(f"/api/teams/{a.team_id}/projects", params={"status": "completed"})+ assert result.status_code == 200, result.text+ assert [row["id"] for row in result.json()["items"]] == [completed.id]diff --git a/backend/tests/test_team_drama_integration.py b/backend/tests/test_team_drama_integration.pynew file mode 100644index 0000000..7cbe286--- /dev/null+++ b/backend/tests/test_team_drama_integration.py@@ -0,0 +1,203 @@+"""真实旧漫剧路由与团队租约、空间隔离的集成回归。"""+import pytest+import pytest_asyncio+from sqlalchemy import select++from app.api.drama import router as drama_router+from app.api.team_edit_locks import router as locks_router+from app.models import UsageEvent+from app.models_drama import DramaAsset, DramaProject, DramaScript+from app.models_tasks import TaskRun+from app.models_teams import TeamMember+from tests.test_teams_api import teams_api # noqa: F401+++async def test_edit_lock_conflict_returns_serializable_423_instead_of_network_error(drama_api):+ a = drama_api+ await headers(a, "asset", a.asset.id, "owner-holding")+ a.auth["user"] = a.member+ response = await a.client.post(f"/api/teams/{a.team_id}/edit-locks/acquire", json={+ "project_id": a.project.id, "resource_type": "asset", "resource_id": a.asset.id,+ "session_id": "member-conflict",+ })+ assert response.status_code == 423, response.text+ detail = response.json()["detail"]+ assert detail["owner_user_id"] == a.owner.id+ assert "正在编辑" in detail["message"]+ assert isinstance(detail["expires_at"], str)+ assert "token" not in detail+++async def test_other_editor_lock_does_not_block_reading_storyboard(drama_api):+ from app.models_drama import DramaEpisode, DramaEpisodeFragment+ a = drama_api+ episode = DramaEpisode(project_id=a.project.id, name="只读分镜", params={"episodeNumber": 1})+ a.db.add(episode)+ await a.db.flush()+ a.db.add(DramaEpisodeFragment(episode_id=episode.id, sort_order=0, content="可读取的分镜正文", video="/static/mock/local/default.mp4"))+ await a.db.commit()+ await headers(a, "episode", 1, "owner-editing")+ a.auth["user"] = a.member+ locked = await a.client.post(f"/api/teams/{a.team_id}/edit-locks/acquire", json={"project_id": a.project.id, "resource_type": "episode", "resource_id": 1, "session_id": "member-viewing"})+ assert locked.status_code == 423+ listing = await a.client.get(f"/api/drama/episodes?project_id={a.project.id}")+ assert listing.status_code == 200+ result = await a.client.get(f"/api/drama/episodes/{episode.id}")+ assert result.status_code == 200, result.text+ assert result.json()["fragments"][0]["content"] == "可读取的分镜正文"+ assert result.json()["fragments"][0]["video"] == "/static/mock/local/default.mp4"+++async def test_team_status_repairs_cancelled_queue_without_touching_other_members_active_task(drama_api):+ """团队取消任务后不再假排队,查看者不是提交者时也保留真正的活动任务。"""+ from app.models_drama import DramaEpisode, DramaEpisodeFragment+ a = drama_api+ episode = DramaEpisode(project_id=a.project.id, name="状态修复测试")+ a.db.add(episode)+ await a.db.flush()+ cancelled = DramaEpisodeFragment(episode_id=episode.id, sort_order=0, params={"generation": {"status": "queued", "message": "已入队"}})+ active = DramaEpisodeFragment(episode_id=episode.id, sort_order=1, params={"generation": {"status": "queued"}})+ a.db.add_all([cancelled, active])+ await a.db.flush()+ for fragment, state in [(cancelled, "cancelled"), (active, "pending")]:+ a.db.add(TaskRun(domain="drama", task_type="fragment_video", queue_type="video", status=state,+ requested_by=a.owner.id, team_id=a.team_id, drama_project_id=a.project.id,+ episode_id=episode.id, fragment_id=fragment.id,+ payload={"fragment_ids": [fragment.id]}))+ await a.db.commit()+ a.auth["user"] = a.member+ response = await a.client.get(f"/api/drama/episodes/{episode.id}/generate_status")+ assert response.status_code == 200, response.text+ data = response.json()+ statuses = {row["fragment_id"]: row["status"] for row in data["fragments"]}+ assert statuses == {cancelled.id: "cancelled", active.id: "queued"}+ assert data["running"] == 1+ await a.db.refresh(cancelled)+ assert cancelled.params["generation"]["status"] == "cancelled"+ assert active.params["generation"]["status"] == "queued"+++@pytest_asyncio.fixture+async def drama_api(teams_api):+ """挂载生产依赖,所有请求只访问当前 PostgreSQL 回滚事务。"""+ a = teams_api+ a.app.include_router(drama_router, prefix="/api")+ a.app.include_router(locks_router, prefix="/api")+ row = DramaProject(user_id=a.owner.id, team_id=a.team_id, title="团队作品")+ a.db.add(row)+ await a.db.flush()+ a.db.add(DramaScript(project_id=row.id, name="剧本", episode_content={"episodes": [{"episodeNumber": 1, "body": "第一集"}, {"episodeNumber": 2, "body": "第二集"}]}))+ asset = DramaAsset(project_id=row.id, type="character", asset_type="image", name="最新角色", params={"description": "最新描述"})+ a.db.add(asset)+ await a.db.commit()+ a.project, a.asset = row, asset+ return a+++async def headers(a, kind, resource_id=0, session="editor", force=False):+ """由真实 HTTP 接口获取不可伪造的编辑凭证。"""+ response = await a.client.post(f"/api/teams/{a.team_id}/edit-locks/acquire", json={"project_id": a.project.id, "resource_type": kind, "resource_id": resource_id, "session_id": session, "force": force})+ assert response.status_code == 200, response.text+ value = response.json()+ return {"X-Edit-Session": session, "X-Edit-Token": value["token"], "X-Edit-Version": str(value["version"])}+++async def test_old_drama_routes_require_current_membership_and_separate_spaces(drama_api):+ """队友能读创建者的作品,个人列表不混入团队,离队创建者也被即时拒绝。"""+ a = drama_api+ a.auth["user"] = a.member+ assert (await a.client.get(f"/api/drama/projects/{a.project.id}")).status_code == 200+ assert (await a.client.get("/api/drama/projects")).json() == []+ scoped = await a.client.get("/api/drama/projects", headers={"X-Team-Id": str(a.team_id)})+ assert [row["id"] for row in scoped.json()] == [a.project.id]+ a.auth["user"] = a.outsider+ assert (await a.client.get(f"/api/drama/projects/{a.project.id}")).status_code == 404+ a.auth["user"] = a.owner+ membership = await a.db.scalar(select(TeamMember).where(TeamMember.team_id == a.team_id, TeamMember.user_id == a.owner.id))+ membership.active = False+ await a.db.commit()+ assert (await a.client.get(f"/api/drama/projects/{a.project.id}")).status_code == 404+++async def test_old_write_routes_reject_missing_wrong_and_fenced_tokens(drama_api):+ """旧页面不能绕过租约;接管后旧标签页的保存失效。"""+ a = drama_api+ path = f"/api/drama/assets/{a.asset.id}"+ assert (await a.client.patch(path, json={"name": "未授权"})).status_code == 428+ wrong = await headers(a, "episode", 1)+ assert (await a.client.patch(path, json={"name": "错目标"}, headers=wrong)).status_code == 409+ a.auth["user"] = a.member+ old = await headers(a, "asset", a.asset.id, "member")+ assert (await a.client.patch(path, json={"name": "成员保存"}, headers=old)).status_code == 200+ a.auth["user"] = a.owner+ await headers(a, "asset", a.asset.id, "owner", force=True)+ a.auth["user"] = a.member+ assert (await a.client.patch(path, json={"name": "过期保存"}, headers=old)).status_code == 409+++async def test_team_scripts_save_per_episode_and_preserve_other_writer(drama_api):+ """旧整包保存拒绝;分集提交只更新本集,版本不匹配明确冲突。"""+ a = drama_api+ script_headers = await headers(a, "script")+ assert (await a.client.patch(f"/api/drama/scripts/{a.project.id}", headers=script_headers, json={"episode_content": {"episodes": []}})).status_code == 409+ first = await headers(a, "episode", 1)+ assert (await a.client.patch(f"/api/drama/scripts/{a.project.id}/episodes/1", headers=first, json={"body": "缺少读取版本"})).status_code == 428+ a.auth["user"] = a.member+ second = await headers(a, "episode", 2, "member")+ assert (await a.client.patch(f"/api/drama/scripts/{a.project.id}/episodes/2", headers=second, json={"body": "成员第二集", "version": 0})).status_code == 200+ a.auth["user"] = a.owner+ path = f"/api/drama/scripts/{a.project.id}/episodes/1"+ assert (await a.client.patch(path, headers=first, json={"body": "所有者第一集", "version": 0})).status_code == 200+ assert (await a.client.patch(path, headers=first, json={"body": "陈旧第一集", "version": 0})).status_code == 409+ script = await a.db.scalar(select(DramaScript).where(DramaScript.project_id == a.project.id))+ assert [row["body"] for row in script.episode_content["episodes"]] == ["所有者第一集", "成员第二集"]+++async def test_running_task_cannot_be_forced_and_chat_does_not_occupy_content(drama_api):+ """系统写回占用不能被人工接管,只读聊天不会阻塞正文。"""+ a = drama_api+ task = TaskRun(domain="drama", task_type="episode_scripts", requested_by=a.member.id, drama_project_id=a.project.id, team_id=a.team_id, status="running", payload={"episode_number": 1})+ a.db.add(task)+ await a.db.commit()+ path = f"/api/teams/{a.team_id}/edit-locks/acquire"+ body = {"project_id": a.project.id, "resource_type": "episode", "resource_id": 1, "session_id": "owner", "force": True}+ assert (await a.client.post(path, json=body)).status_code == 423+ task.task_type = "agent_chat"+ await a.db.commit()+ assert (await a.client.post(path, json=body)).status_code == 200+++async def test_team_canvas_cannot_overwrite_assets_and_usage_is_private(drama_api):+ """布局快照不覆盖独立资产;普通成员不可由项目统计读取他人花费或上游成本。"""+ a = drama_api+ lock = await headers(a, "canvas")+ node = {"id": "node", "position": {"x": 10, "y": 20}, "data": {"assetId": a.asset.id, "label": "陈旧角色", "mediaUrl": "/old.png"}}+ result = await a.client.post("/api/drama/canvas", headers=lock, json={"project_id": a.project.id, "nodes": [node], "edges": []})+ assert result.status_code == 200, result.text+ await a.db.refresh(a.asset)+ assert a.asset.name == "最新角色" and a.asset.url is None+ canvas = (await a.client.get(f"/api/drama/canvas/{a.project.id}")).json()+ assert canvas["nodes"][0]["data"]["label"] == "最新角色"+ a.db.add_all([UsageEvent(user_id=a.owner.id, team_id=a.team_id, drama_project_id=a.project.id, billing_key="llm_chat", charge_fen=100, cost_fen=55), UsageEvent(user_id=a.member.id, team_id=a.team_id, drama_project_id=a.project.id, billing_key="llm_chat", charge_fen=30, cost_fen=20)])+ await a.db.commit()+ a.auth["user"] = a.member+ usage = (await a.client.get(f"/api/drama/projects/{a.project.id}")).json()["usage"]+ assert usage["charge_fen"] == 30 and usage["cost_fen"] == 0+ a.auth["user"] = a.owner+ usage = (await a.client.get(f"/api/drama/projects/{a.project.id}")).json()["usage"]+ assert usage["charge_fen"] == 130 and usage["cost_fen"] == 0+++def test_main_registers_team_api_routes():+ """主应用确实公开了前端使用的接口,防止只在测试子应用里通过。"""+ from app.main import app+ paths = {route.path for route in app.routes if hasattr(route, "path")}+ assert {"/api/teams", "/api/team-invitations/accept", "/api/teams/{team_id}/projects", "/api/teams/{team_id}/usage/summary", "/api/teams/{team_id}/edit-locks/acquire", "/api/drama/assets/{asset_id}/copy"} <= pathsdiff --git a/backend/tests/test_team_edit_locks.py b/backend/tests/test_team_edit_locks.pynew file mode 100644index 0000000..543ebbd--- /dev/null+++ b/backend/tests/test_team_edit_locks.py@@ -0,0 +1,91 @@+"""团队编辑占用与按集保存:仅使用隔离 PostgreSQL 测试事务。"""+from __future__ import annotations++import pytest+from fastapi import HTTPException+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models_drama import DramaProject, DramaScript+from tests.conftest import make_user+++async def team_project(db: AsyncSession):+ """建立两位协作者和带两集正文的真实团队项目。"""+ from app.models_teams import Team, TeamMember++ owner = await make_user(db)+ member = await make_user(db)+ team = Team(name="占用测试", description="", color="#435c4b", owner_user_id=owner.id)+ db.add(team)+ await db.flush()+ db.add_all([TeamMember(team_id=team.id, user_id=owner.id, role="owner"), TeamMember(team_id=team.id, user_id=member.id, role="member")])+ project = DramaProject(user_id=owner.id, team_id=team.id, title="并行制作")+ db.add(project)+ await db.flush()+ script = DramaScript(project_id=project.id, name="剧本", episode_content={"episodes": [{"episodeNumber": 1, "body": "第一集", "extra": "保留"}, {"episodeNumber": 2, "body": "第二集"}]})+ db.add(script)+ await db.commit()+ return owner, member, team, project+++async def test_team_lock_same_episode_conflicts_and_different_episodes_parallel(db_session):+ from app.services.teams.edit_locks import acquire_lock++ owner, member, team, project = await team_project(db_session)+ first = await acquire_lock(db_session, team.id, owner.id, project.id, "episode", 1, "owner-tab")+ second = await acquire_lock(db_session, team.id, member.id, project.id, "episode", 2, "member-tab")+ assert first["token"] != second["token"]+ with pytest.raises(HTTPException) as exc:+ await acquire_lock(db_session, team.id, member.id, project.id, "episode", 1, "member-tab")+ assert exc.value.status_code == 423+ assert exc.value.detail["owner_user_id"] == owner.id+++async def test_structure_lock_conflicts_with_existing_episode_and_member_cannot_force(db_session):+ from app.services.teams.edit_locks import acquire_lock++ owner, member, team, project = await team_project(db_session)+ await acquire_lock(db_session, team.id, owner.id, project.id, "episode", 1, "owner-tab")+ with pytest.raises(HTTPException) as exc:+ await acquire_lock(db_session, team.id, member.id, project.id, "structure", 0, "member-tab", force=True)+ assert exc.value.status_code == 403+ with pytest.raises(HTTPException) as exc:+ await acquire_lock(db_session, team.id, member.id, project.id, "structure", 0, "member-tab")+ assert exc.value.status_code == 423+++async def test_forced_takeover_invalidates_old_token_and_released_member_cannot_write(db_session):+ from app.models_teams import TeamMember+ from app.services.teams.edit_locks import acquire_lock, validate_lock++ owner, member, team, project = await team_project(db_session)+ old = await acquire_lock(db_session, team.id, member.id, project.id, "asset", 0, "member-tab")+ new = await acquire_lock(db_session, team.id, owner.id, project.id, "asset", 0, "owner-tab", force=True)+ assert new["version"] > old["version"]+ with pytest.raises(HTTPException):+ await validate_lock(db_session, project, member.id, "asset", 0, "member-tab", old["token"], old["version"])+ membership = (await db_session.execute(select(TeamMember).where(TeamMember.team_id == team.id, TeamMember.user_id == member.id))).scalar_one()+ membership.active = False+ await db_session.commit()+ with pytest.raises(HTTPException) as exc:+ await acquire_lock(db_session, team.id, member.id, project.id, "canvas", 0, "member-tab")+ assert exc.value.status_code == 404+++async def test_episode_patch_preserves_other_episode_extra_fields_and_explicit_empty(db_session):+ from app.services.teams.script_updates import patch_episode_body++ owner, member, team, project = await team_project(db_session)+ await patch_episode_body(db_session, project.id, 1, {"body": ""})+ await patch_episode_body(db_session, project.id, 2, {"body": "第二集修改", "creative": "创意"})+ await db_session.commit()+ from sqlalchemy import select++ script = (await db_session.execute(select(DramaScript).where(DramaScript.project_id == project.id).execution_options(populate_existing=True))).scalar_one()+ assert script.episode_content["episodes"][0] == {"episodeNumber": 1, "body": "", "extra": "保留"}+ assert script.episode_content["episodes"][1]["body"] == "第二集修改"diff --git a/backend/tests/test_team_lock_fencing.py b/backend/tests/test_team_lock_fencing.pynew file mode 100644index 0000000..55e4316--- /dev/null+++ b/backend/tests/test_team_lock_fencing.py@@ -0,0 +1,74 @@+"""无需数据库的系统派生范围与内容版本安全回归。"""+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from fastapi import HTTPException++from app.models_drama import DramaScript+from app.models_tasks import TaskRun+from app.services.billing.context import billing_scope+from app.services.teams import edit_locks+from app.services.teams.script_updates import bump_episode_versions, patch_episode_body+++async def test_child_task_cannot_use_stale_human_snapshot_to_escape_parent(monkeypatch):+ """父任务第1集的授权不能因人工会话残留而放行真实第2集子任务。"""+ parent = TaskRun(id=41, domain="drama", task_type="episode_script", requested_by=7, team_id=3, drama_project_id=11, status="running", payload={"episode_number": 1})+ child = TaskRun(domain="drama", task_type="episode_script", requested_by=7, team_id=3, drama_project_id=11, payload={"episode_number": 2})+ db = SimpleNamespace(info={"team_parent_task_id": 41, "team_edit_project_id": 11, "team_edit_resource": ("episode", 1)}, get=AsyncMock(return_value=parent))+ monkeypatch.setattr(edit_locks, "_project", AsyncMock(return_value=SimpleNamespace(id=11)))+ async with billing_scope(parent.id, team_id=3):+ with pytest.raises(HTTPException) as error:+ await edit_locks.claim_task_locks(db, child, 7)+ assert error.value.status_code == 409+ assert "_team_edit_resource" not in child.payload+++async def test_human_snapshot_must_cover_actual_task_target(monkeypatch):+ """任务真实目标与已验证请求不一致时,即使相同项目也必须拒绝。"""+ child = TaskRun(domain="drama", task_type="episode_script", requested_by=7, team_id=3, drama_project_id=11, payload={"episode_number": 2})+ db = SimpleNamespace(info={"team_edit_project_id": 11, "team_edit_resource": ("episode", 1)})+ monkeypatch.setattr(edit_locks, "_project", AsyncMock(return_value=SimpleNamespace(id=11)))+ with pytest.raises(HTTPException) as error:+ await edit_locks.claim_task_locks(db, child, 7)+ assert error.value.status_code == 409+++async def test_structural_parent_grants_child_only_its_real_scope(monkeypatch):+ """整剧任务可派生本集任务,但持久占用缩小到真实集号。"""+ parent = TaskRun(id=41, domain="drama", task_type="script_summary", requested_by=7, team_id=3, drama_project_id=11, status="running", payload={})+ child = TaskRun(domain="drama", task_type="episode_script", requested_by=7, team_id=3, drama_project_id=11, payload={"episode_number": 2})+ db = SimpleNamespace(info={"team_parent_task_id": 41}, get=AsyncMock(return_value=parent))+ monkeypatch.setattr(edit_locks, "_project", AsyncMock(return_value=SimpleNamespace(id=11)))+ async with billing_scope(parent.id, team_id=3):+ await edit_locks.claim_task_locks(db, child, 7)+ assert child.payload["_team_edit_resource"] == ["episode", 2]+ assert child.payload["_team_parent_task_id"] == parent.id+++async def test_generated_content_invalidates_older_editor_version(monkeypatch):+ """模型完成后旧草稿保存必须冲突,其他集的内容与版本保持不变。"""+ script = DramaScript(project_id=11, name="剧本", episode_content={"episodes": [{"episodeNumber": 1, "body": "模型新正文"}, {"episodeNumber": 2, "body": "第二集"}]}, params={"episode_versions": {"1": 3, "2": 8}})+ bump_episode_versions(script, [1])+ monkeypatch.setattr("app.services.teams.script_updates.locked_script", AsyncMock(return_value=script))+ with pytest.raises(HTTPException) as error:+ await patch_episode_body(SimpleNamespace(flush=AsyncMock()), 11, 1, {"version": 3, "body": "旧草稿"})+ assert error.value.status_code == 409+ assert script.params["episode_versions"] == {"1": 4, "2": 8}+ assert script.episode_content["episodes"][0]["body"] == "模型新正文"+++async def test_asset_copy_keeps_content_but_drops_source_binding_ids():+ """副本音色可独立使用,不继续依赖来源角色或音色资产 ID。"""+ from app.services.teams.content_media import MediaCopier++ source = {"description": "角色说明", "voiceAudio": {"sourceAssetId": 8, "speaker": "voice-a"}, "sourceCharacterAssetId": 9, "canvas": {"id": "old"}, "image_versions": [{"id": "v1", "label": "定妆"}]}+ result = await MediaCopier(2, {1, 2}).rewrite(source, clean=True)+ assert result == {"description": "角色说明", "voiceAudio": {"speaker": "voice-a"}, "image_versions": [{"id": "v1", "label": "定妆"}]}+ assert source["voiceAudio"]["sourceAssetId"] == 8diff --git a/backend/tests/test_team_owner_billing.py b/backend/tests/test_team_owner_billing.pynew file mode 100644index 0000000..950f74e--- /dev/null+++ b/backend/tests/test_team_owner_billing.py@@ -0,0 +1,116 @@+"""所有者统一付款、两级月上限与历史任务兼容。"""+import pytest+from sqlalchemy import select+from app.models import UsageEvent, WalletLedger+from app.models_tasks import TaskRun+from app.models_teams import Team, TeamMember+from app.models_team_billing import TeamMonthlyUsage, TeamWallet+from app.services.billing.settlement import ensure_balance_for_task, freeze_for_task, settle_task+from app.services.billing.team import billing_period+from tests.test_team_billing import seed_team, enqueue+++async def test_owner_pays_actor_and_usage_remain_member(db_session, monkeypatch):+ """只扣所有者个人账户,记录发起成员并允许所有者核对个人账单。"""+ team, owner, member = await seed_team(db_session)+ task = await enqueue(db_session, member, team, monkeypatch)+ assert task.billing_payer_user_id == owner.id+ await freeze_for_task(db_session, task)+ event = UsageEvent(user_id=member.id, team_id=team.id, task_run_id=task.id, billing_key="seedream", charge_fen=180, settled=False)+ db_session.add(event)+ await db_session.flush()+ await settle_task(db_session, task.id)+ assert (owner.balance_fen, owner.frozen_fen, member.balance_fen) == (1820, 0, 90000)+ assert (event.user_id, event.team_id, event.billing_payer_user_id) == (member.id, team.id, owner.id)+ assert (await db_session.get(TeamWallet, team.id)).balance_fen == 0+ entries = (await db_session.execute(select(WalletLedger).where(WalletLedger.user_id == owner.id))).scalars().all()+ assert sum(e.delta_fen for e in entries) == -180+ assert all(f"team:{team.id} actor:{member.id}" in e.note for e in entries)+ from app.api.billing import usage_events, usage_summary+ assert (await usage_summary(db=db_session, user=owner))["charge_fen"] == 180+ assert (await usage_events(page=1, page_size=20, db=db_session, user=owner))["items"][0]["id"] == event.id+ assert (await usage_events(page=1, page_size=20, db=db_session, user=member))["items"] == []++[email protected]("limit", [0, 500])+async def test_total_month_limit_counts_other_members_and_reservations(db_session, monkeypatch, limit):+ team, owner, member = await seed_team(db_session, limit=None)+ team.monthly_limit_fen = limit+ if limit:+ await enqueue(db_session, owner, team, monkeypatch)+ with pytest.raises(ValueError, match="团队月度消费额度"):+ await enqueue(db_session, member, team, monkeypatch)+++async def test_owner_member_limit_is_enforced_and_old_month_does_not_count(db_session, monkeypatch):+ team, owner, member = await seed_team(db_session)+ membership = (await db_session.execute(select(TeamMember).where(TeamMember.team_id == team.id, TeamMember.user_id == owner.id))).scalar_one()+ membership.monthly_limit_fen = 300+ team.monthly_limit_fen = 300+ db_session.add(TeamMonthlyUsage(team_id=team.id, user_id=owner.id, period="2000-01", spent_fen=10000, reserved_fen=10000))+ await enqueue(db_session, owner, team, monkeypatch)+ team.monthly_limit_fen = None+ with pytest.raises(ValueError, match="成员月度消费额度"):+ await enqueue(db_session, owner, team, monkeypatch)+++async def test_transfer_does_not_change_accepted_payer(db_session, monkeypatch):+ from app.services.teams.management import transfer_ownership+ team, owner, member = await seed_team(db_session)+ first = await enqueue(db_session, member, team, monkeypatch)+ await transfer_ownership(db_session, team.id, owner.id, member.id)+ await freeze_for_task(db_session, first)+ assert (owner.balance_fen, member.balance_fen) == (1700, 90000)+ db_session.add(UsageEvent(user_id=member.id, task_run_id=first.id, billing_key="seedream", charge_fen=180, settled=False))+ await db_session.flush()+ await settle_task(db_session, first.id)+ second = await enqueue(db_session, owner, team, monkeypatch)+ assert (first.billing_payer_user_id, second.billing_payer_user_id) == (owner.id, member.id)+ assert (owner.balance_fen, member.balance_fen) == (1820, 90000)+ target = (await db_session.execute(select(TeamMember).where(TeamMember.team_id == team.id, TeamMember.user_id == member.id))).scalar_one()+ assert target.monthly_limit_fen == 1000+++async def test_personal_and_multiple_teams_share_owner_commitments(db_session, monkeypatch):+ team, owner, member = await seed_team(db_session, balance=700)+ await enqueue(db_session, member, team, monkeypatch)+ other = Team(name="同所有者的另一个团队", owner_user_id=owner.id)+ db_session.add(other)+ await db_session.flush()+ db_session.add(TeamMember(team_id=other.id, user_id=owner.id, role="owner"))+ await db_session.flush()+ await enqueue(db_session, owner, other, monkeypatch)+ personal = TaskRun(requested_by=owner.id, domain="tools", task_type="t2i", payload={})+ with pytest.raises(ValueError, match="余额不足"):+ await ensure_balance_for_task(db_session, owner, personal)+ with pytest.raises(ValueError, match="所有者余额不足"):+ await enqueue(db_session, member, team, monkeypatch)+++async def test_new_team_admission_respects_personal_pending_tasks(db_session, monkeypatch):+ team, owner, member = await seed_team(db_session, balance=500)+ db_session.add(TaskRun(requested_by=owner.id, domain="tools", task_type="t2i", payload={}, status="pending", billing_status="none", billing_estimate_fen=300))+ await db_session.flush()+ with pytest.raises(ValueError, match="所有者余额不足"):+ await enqueue(db_session, member, team, monkeypatch)+++async def test_legacy_frozen_task_finishes_in_original_wallet(db_session):+ """无付款快照的旧任务不能重复扣到个人账户。"""+ team, owner, member = await seed_team(db_session)+ wallet = await db_session.get(TeamWallet, team.id)+ wallet.balance_fen, wallet.frozen_fen = 1700, 300+ task = TaskRun(requested_by=member.id, team_id=team.id, domain="drama", task_type="asset_image", payload={}, status="succeeded", billing_status="frozen", billing_estimate_fen=300, billing_period=billing_period(), billing_enabled_snapshot=True)+ db_session.add(task)+ await db_session.flush()+ db_session.add(UsageEvent(user_id=member.id, team_id=team.id, task_run_id=task.id, billing_key="seedream", charge_fen=180, settled=False))+ await db_session.flush()+ await settle_task(db_session, task.id)+ assert (wallet.balance_fen, wallet.frozen_fen, owner.balance_fen) == (1820, 0, 2000)diff --git a/backend/tests/test_team_prompt_billing.py b/backend/tests/test_team_prompt_billing.pynew file mode 100644index 0000000..3828b26--- /dev/null+++ b/backend/tests/test_team_prompt_billing.py@@ -0,0 +1,30 @@+"""The editor's prompt optimization keeps its real project billing scope."""+from types import SimpleNamespace+from unittest.mock import AsyncMock+import pytest+from pydantic import ValidationError+from app.models import User+from app.schemas_agent import AgentSkillOptimizeBody+from app.api.drama import skills++[email protected]("project_id", [None, 71])+async def test_skill_prompt_optimization_preserves_project_scope(monkeypatch, project_id):+ optimize = AsyncMock(return_value="优化后的提示词")+ usage = AsyncMock()+ monkeypatch.setattr(skills, "optimize_prompt_with_skills", optimize)+ monkeypatch.setattr(skills, "record_llm_chat_line", usage)+ async def billed(db, user, **kwargs):+ assert kwargs["drama_project_id"] == project_id+ assert kwargs["task_type"] == "skill_optimize"+ return SimpleNamespace(id=9), await kwargs["executor"]()+ monkeypatch.setattr(skills, "run_billed_ephemeral", billed)+ result = await skills.optimize_prompt(AgentSkillOptimizeBody(prompt="画面提示", skill_ids=[1], project_id=project_id), db=SimpleNamespace(), user=User(id=2))+ assert result.task_id == 9+ assert usage.await_args.kwargs["drama_project_id"] == project_id+++def test_skill_optimization_rejects_invalid_project_id():+ with pytest.raises(ValidationError):+ AgentSkillOptimizeBody(prompt="test", project_id=0)diff --git a/backend/tests/test_team_reference_media.py b/backend/tests/test_team_reference_media.pynew file mode 100644index 0000000..40670f7--- /dev/null+++ b/backend/tests/test_team_reference_media.py@@ -0,0 +1,154 @@+"""离线校验团队视频任务只读取其他内容,不越过分集/资产的写入范围。"""+from copy import deepcopy+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from sqlalchemy import inspect++from app.models import User+from app.models_drama import DramaAsset, DramaEpisodeFragment, DramaProject+from app.services import storage+from app.services.drama import asset_video, generation+++def reference_asset(**overrides):+ """创建带嵌套音色绑定的参考资产,方便检测原对象被隐式修改。"""+ values = dict(id=2, project_id=17, name="角色", type="character", asset_type="image",+ cover="/static/cover.png", url="/static/cover.png",+ params={"voiceAudio": {"url": "/static/voice.mp3"},+ "canvas": {"voiceAudio": {"url": "/static/voice.mp3"}}})+ return DramaAsset(**{**values, **overrides})+++async def test_read_only_reference_publication_uses_independent_snapshots(monkeypatch):+ """团队请求可转换公网引用,但不改变 ORM 资产或提交任何事务。"""+ asset = reference_asset()+ original = deepcopy(asset.params)+ db = SimpleNamespace(commit=AsyncMock(), refresh=AsyncMock(), get=AsyncMock())+ monkeypatch.setattr(storage, "republish_url", lambda url, **_: "https://media.example.com/" + url.rsplit("/", 1)[-1])+ result = await generation.ensure_reference_assets_public_urls(db, [asset], read_only=True)+ assert result[0] is not asset+ assert inspect(result[0]).session is None and inspect(result[0]).transient+ assert result[0].cover == "https://media.example.com/cover.png"+ assert result[0].params["voiceAudio"]["url"] == "https://media.example.com/voice.mp3"+ result[0].params["canvas"]["voiceAudio"]["extra"] = True+ assert asset.params == original+ assert asset.cover == "/static/cover.png" and asset.url == "/static/cover.png"+ db.commit.assert_not_awaited()+ db.refresh.assert_not_awaited()+++async def test_personal_reference_publication_preserves_existing_cache(monkeypatch):+ """个人项目继续缓存公网 URL,避免改变既有生成流程。"""+ asset = reference_asset(params={})+ db = SimpleNamespace(commit=AsyncMock(), refresh=AsyncMock(), get=AsyncMock())+ monkeypatch.setattr(storage, "republish_url", lambda _url, **_: "https://media.example.com/a.png")+ result = await generation.ensure_reference_assets_public_urls(db, [asset])+ assert result[0] is asset and asset.url == "https://media.example.com/a.png"+ db.commit.assert_awaited_once()+ db.refresh.assert_awaited_once_with(asset)++[email protected]("narrator", [False, True])[email protected]("duration", [None, 1.1, 30.5])+async def test_team_invalid_audio_is_rejected_without_repair(monkeypatch, tmp_path, narrator, duration):+ """不可读、过短和过长均不能自动合成其他音色或重写角色/旁白绑定。"""+ asset = reference_asset()+ params = {"narrationVoiceAudio": {"url": "/static/narrator.mp3", "sourceAssetId": 9}} if narrator else {}+ project = DramaProject(id=17, team_id=8, params=params)+ original = deepcopy((asset.params, project.params))+ db = SimpleNamespace(commit=AsyncMock(), refresh=AsyncMock(), get=AsyncMock())+ monkeypatch.setattr(storage, "project_dir", lambda _id: tmp_path)+ monkeypatch.setattr(generation, "probe_voice_url_duration", AsyncMock(return_value=duration))+ synthesize = AsyncMock()+ monkeypatch.setattr(generation, "synthesize_voice_asset", synthesize)+ with pytest.raises(RuntimeError, match="资产|旁白"):+ await generation.ensure_fragment_reference_audios(db, User(id=1), project,+ DramaEpisodeFragment(id=3), [] if narrator else [asset])+ assert (asset.params, project.params) == original+ synthesize.assert_not_awaited()+ db.get.assert_not_awaited()+ db.commit.assert_not_awaited()+++async def test_team_ready_audio_only_probes_and_returns_original_refs(monkeypatch, tmp_path):+ """合格音频不触发生成、补足、数据库查询或写入。"""+ asset = reference_asset()+ project = DramaProject(id=17, team_id=8, params={"narrationVoiceAudio": {"url": "/static/voice.mp3"}})+ db = SimpleNamespace(commit=AsyncMock(), get=AsyncMock())+ probe = AsyncMock(return_value=2.1)+ monkeypatch.setattr(storage, "project_dir", lambda _id: tmp_path)+ monkeypatch.setattr(generation, "probe_voice_url_duration", probe)+ result = await generation.ensure_fragment_reference_audios(db, User(id=1), project,+ DramaEpisodeFragment(id=3), [asset])+ assert result == [asset] and result[0] is asset+ db.get.assert_not_awaited()+ db.commit.assert_not_awaited()+ probe.assert_awaited_once()+ assert "3" in str(probe.call_args.kwargs["work_dir"])+++async def test_personal_short_audio_still_repairs_binding(monkeypatch, tmp_path):+ """个人分镜继续保留自动补足逻辑。"""+ asset = reference_asset()+ project = DramaProject(id=17, team_id=None, params={})+ db = SimpleNamespace(commit=AsyncMock(), refresh=AsyncMock(), get=AsyncMock())+ monkeypatch.setattr(storage, "project_dir", lambda _id: tmp_path)+ monkeypatch.setattr(storage, "local_path_from_url", lambda _url: tmp_path / "voice.mp3")+ monkeypatch.setattr(storage, "rel_static_url", lambda _path: "/static/voice.mp3")+ monkeypatch.setattr(generation, "probe_voice_url_duration", AsyncMock(return_value=1.1))+ monkeypatch.setattr(generation, "finalize_voice_reference_url", lambda *_args, **_kwargs: "/static/padded.mp3")+ await generation.ensure_fragment_reference_audios(db, User(id=1), project,+ DramaEpisodeFragment(id=3), [asset])+ assert asset.params["voiceAudio"]["url"] == "/static/padded.mp3"+ db.commit.assert_awaited_once()+++async def test_team_continuity_does_not_write_source_fragment(monkeypatch, tmp_path):+ """尾帧抽取可提供本次参考,不能改变来源分镜的 JSON。"""+ video = tmp_path / "source.mp4"+ video.write_bytes(b"test")+ fragment = DramaEpisodeFragment(id=5, episode_id=2, video=str(video), params={"generation": {"status": "done"}})+ original = deepcopy(fragment.params)+ monkeypatch.setattr(storage, "project_dir", lambda _id: tmp_path)+ monkeypatch.setattr(storage, "local_path_from_url", lambda _url: video)+ monkeypatch.setattr(storage, "rel_static_url", lambda _path: "/static/last.jpg")+ monkeypatch.setattr(storage, "republish_url", lambda url, **_: url)+ monkeypatch.setattr("app.services.ffmpeg_compose.extract_video_last_frame", lambda *_args: True)+ result = await generation.ensure_fragment_last_frame_url(DramaProject(id=17, team_id=8), fragment)+ assert result == "/static/last.jpg" and fragment.params == original+++class StopPreparation(Exception):+ """在请求引用转换入口停止,以离线验证两个业务调用方的只读选择。"""++[email protected]("team_id", [None, 8])[email protected]("caller", ["fragment", "asset"])+async def test_video_preparation_selects_read_only_team_references(monkeypatch, team_id, caller):+ """分镜及资产视频调用同一只读策略,避免遗漏另一条写入路径。"""+ project = DramaProject(id=17, team_id=team_id, params={})+ asset = reference_asset()+ publish = AsyncMock(side_effect=StopPreparation)+ db = SimpleNamespace(get=AsyncMock(return_value=SimpleNamespace(params={})),+ execute=AsyncMock(return_value=SimpleNamespace(scalars=lambda: SimpleNamespace(all=lambda: []))))+ if caller == "fragment":+ monkeypatch.setattr(generation, "ensure_fragment_reference_images", AsyncMock(return_value=[asset]))+ monkeypatch.setattr(generation, "ensure_reference_assets_public_urls", publish)+ execute = generation.prepare_fragment_video_for_submit(db, User(id=1), project,+ DramaEpisodeFragment(id=3, episode_id=2, sort_order=0, content="内容", duration_sec=8))+ else:+ monkeypatch.setattr(asset_video, "load_reference_assets", AsyncMock(return_value=[asset]))+ monkeypatch.setattr(asset_video, "ensure_reference_assets_public_urls", publish)+ execute = asset_video.generate_asset_video(db, User(id=1), project, asset, "画面")+ with pytest.raises(StopPreparation):+ await execute+ assert publish.call_args.kwargs["read_only"] is (team_id is not None)diff --git a/backend/tests/test_team_schema_cli.py b/backend/tests/test_team_schema_cli.pynew file mode 100644index 0000000..6c4986a--- /dev/null+++ b/backend/tests/test_team_schema_cli.py@@ -0,0 +1,147 @@+"""数据库结构 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():+ """提供记录事务入口的假引擎与假连接,DDL 只由 AsyncMock 接收。"""+ connection = SimpleNamespace(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)++[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 --git a/backend/tests/test_team_task_privacy.py b/backend/tests/test_team_task_privacy.pynew file mode 100644index 0000000..a171639--- /dev/null+++ b/backend/tests/test_team_task_privacy.py@@ -0,0 +1,40 @@+"""Team task projections reveal coworker money only to the canonical team owner."""+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock+import pytest+from app.api.tasks import public_task+from app.models import User+from app.models_teams import Team, TeamMember+from app.services.tasks.service import cancel_task_for_user+++def task_row():+ return SimpleNamespace(id=1, domain="drama", task_type="asset_image", status="running", priority=100, requested_by=2, team_id=91, billing_estimate_fen=300, billing_charged_fen=180, billing_refunded_fen=120, events=[SimpleNamespace(id=1, event_type="task.completed", message="扣费 ¥1.80", payload={"amount_fen": 180, "result": {"cost": 90, "video_url": "/video.mp4"}, "items": [{"refund_yuan": 1.2, "label": "成功"}]})], steps=[], targets=[])++[email protected]("viewer_id,role,visible", [(1, "member", True), (2, "member", True), (3, "admin", False), (4, "member", False)])+def test_team_task_money_is_owner_or_actor_only(viewer_id, role, visible):+ original = task_row()+ output = public_task(original, viewer=User(id=viewer_id, role=role), owner_user_id=1)+ assert output.billing_estimate_fen == (300 if visible else None)+ assert output.billing_charged_fen == (180 if visible else None)+ assert output.billing_refunded_fen == (120 if visible else None)+ if visible:+ assert output.events[0].payload["amount_fen"] == 180+ else:+ assert output.events[0].payload == {"result": {"video_url": "/video.mp4"}, "items": [{"label": "成功"}]}+ assert "1.80" not in output.events[0].message+ assert original.events[0].payload["amount_fen"] == 180+++async def test_cancel_uses_one_team_authorization_with_request_context(monkeypatch):+ task = SimpleNamespace(id=1, domain="drama", task_type="asset_image", payload={}, status="running", requested_by=2, team_id=91, cancelable=True, current_step_key="image")+ result = SimpleNamespace(scalar_one_or_none=lambda: task)+ db = SimpleNamespace(execute=AsyncMock(return_value=result), add=Mock(), commit=AsyncMock())+ access = AsyncMock(return_value=(Team(id=91, owner_user_id=1), TeamMember(team_id=91, user_id=3, role="admin", active=True)))+ monkeypatch.setattr("app.services.teams.access.get_team", access)+ context = {}+ await cancel_task_for_user(db, User(id=3), 1, access_context=context)+ access.assert_awaited_once()+ assert context[(91, 3)][0].owner_user_id == 1diff --git a/backend/tests/test_team_tasks.py b/backend/tests/test_team_tasks.pynew file mode 100644index 0000000..3e6558f--- /dev/null+++ b/backend/tests/test_team_tasks.py@@ -0,0 +1,301 @@+"""Team task scope is resolved from persisted resources and current membership."""+from unittest.mock import AsyncMock+import pytest+from fastapi import HTTPException+from sqlalchemy import select+from app.models_drama import DramaAsset, DramaProject+from app.models_tasks import TaskRun+from app.models_teams import TeamMember+from app.schemas_tasks import TaskCreateRequest+from app.services.tasks.service import _validate_task_scope, cancel_task_for_user, get_task_for_user, list_tasks_for_user+from test_team_billing import seed_team, enqueue+++async def test_task_derives_team_from_asset_and_rejects_mixed_scope(db_session):+ team, owner, member = await seed_team(db_session)+ project = DramaProject(user_id=owner.id, team_id=team.id, title="Team")+ db_session.add(project)+ await db_session.flush()+ asset = DramaAsset(project_id=project.id, name="角色", type="character")+ db_session.add(asset)+ await db_session.flush()+ body = TaskCreateRequest(task_type="asset_image", asset_id=asset.id)+ await _validate_task_scope(db_session, member, body)+ assert (body.team_id, body.drama_project_id) == (team.id, project.id)+ with pytest.raises(ValueError, match="团队不匹配"):+ await _validate_task_scope(db_session, member, TaskCreateRequest(task_type="asset_image", asset_id=asset.id, team_id=team.id + 1))+ personal = DramaProject(user_id=member.id, title="Personal")+ db_session.add(personal)+ await db_session.flush()+ with pytest.raises(ValueError, match="不匹配"):+ await _validate_task_scope(db_session, member, TaskCreateRequest(task_type="asset_image", asset_id=asset.id, drama_project_id=personal.id))+++async def test_team_task_read_and_cancel_roles_and_personal_list(db_session, monkeypatch):+ team, owner, member = await seed_team(db_session)+ task = await enqueue(db_session, member, team, monkeypatch)+ assert (await get_task_for_user(db_session, owner, task.id)).id == task.id+ rows, count = await list_tasks_for_user(db_session, member, page=1, page_size=20)+ assert count == 0+ rows, count = await list_tasks_for_user(db_session, owner, team_id=team.id, page=1, page_size=20)+ assert count == 1+ other = await enqueue(db_session, owner, team, monkeypatch)+ with pytest.raises(HTTPException) as exc:+ await cancel_task_for_user(db_session, member, other.id)+ assert exc.value.status_code == 403+ assert (await cancel_task_for_user(db_session, owner, task.id)).cancel_requested+++async def test_removed_member_loses_access_but_running_task_keeps_original_wallet(db_session, monkeypatch):+ from app.services.tasks.team_scope import cancel_removed_member_tasks, ensure_task_may_submit+ from app.models_team_billing import TeamMonthlyUsage+ team, owner, member = await seed_team(db_session)+ queued = await enqueue(db_session, member, team, monkeypatch)+ submitted = await enqueue(db_session, member, team, monkeypatch)+ submitted.provider_task_id = "already-submitted"+ submitted.status = "awaiting_poll"+ membership = (await db_session.execute(select(TeamMember).where(TeamMember.team_id == team.id, TeamMember.user_id == member.id))).scalar_one()+ membership.active = False+ assert await cancel_removed_member_tasks(db_session, team.id, member.id) == 1+ assert queued.status == "cancelled"+ assert submitted.status == "awaiting_poll"+ assert not submitted.cancel_requested+ with pytest.raises(HTTPException):+ await get_task_for_user(db_session, member, submitted.id)+ with pytest.raises(HTTPException):+ await ensure_task_may_submit(db_session, submitted)+ usage = (await db_session.execute(select(TeamMonthlyUsage).where(TeamMonthlyUsage.user_id == member.id))).scalar_one()+ assert usage.reserved_fen == 300++++async def test_removed_team_member_cannot_submit_but_can_finish_polling(db_session, monkeypatch):+ from types import SimpleNamespace+ import httpx+ from app.services.billing.context import billing_scope+ from app.services.tasks import upstream+ team, owner, member = await seed_team(db_session)+ task = await enqueue(db_session, member, team, monkeypatch)+ membership = (await db_session.execute(select(TeamMember).where(TeamMember.team_id == team.id, TeamMember.user_id == member.id))).scalar_one()+ membership.active = False+ await db_session.flush()+ monkeypatch.setattr(upstream, "_safe_record", AsyncMock())+ client = SimpleNamespace(post=AsyncMock(), get=AsyncMock(return_value=httpx.Response(200, json={"status": "succeeded"})))+ async with billing_scope(task.id, team_id=team.id), upstream.upstream_event_session(db_session):+ with pytest.raises(HTTPException):+ await upstream.observed_request(client, "POST", "https://stub.test/v1/videos", json={"model": "stub"})+ await upstream.observed_request(client, "GET", "https://stub.test/v1/videos/submitted")+ client.post.assert_not_awaited()+ client.get.assert_awaited_once()+++async def test_team_public_task_projection_hides_upstream_details(db_session, monkeypatch):+ from app.api.tasks import public_task+ from app.models_tasks import TaskEvent, TaskStep+ team, owner, member = await seed_team(db_session)+ task = await enqueue(db_session, member, team, monkeypatch)+ db_session.add_all([+ TaskEvent(task_id=task.id, event_type="upstream.request.accepted", payload={"cost_fen": 123}),+ TaskEvent(task_id=task.id, event_type="task.started", message="开始"),+ TaskStep(task_id=task.id, step_key="asset_image", input_payload={"provider": "internal"}, output_payload={"cost": 123}),+ ])+ await db_session.flush()+ loaded = await get_task_for_user(db_session, owner, task.id)+ output = public_task(loaded)+ assert [event.event_type for event in output.events] == ["task.started"]+ assert output.steps[0].input_payload is None+ assert output.steps[0].output_payload is None+ assert len(loaded.events) == 2+ assert loaded.steps[0].output_payload == {"cost": 123}+++async def test_background_child_inherits_team_actor_and_cannot_forge_scope(db_session, monkeypatch):+ from app.services.billing.context import billing_scope+ from app.services.tasks.service import create_task+ team, owner, member = await seed_team(db_session)+ project = DramaProject(user_id=owner.id, team_id=team.id, title="Team pipeline")+ db_session.add(project)+ await db_session.flush()+ parent = TaskRun(domain="drama", task_type="script_summary", status="running", team_id=team.id, drama_project_id=project.id, requested_by=member.id, payload={"_team_edit_resource": ["structure", 0]})+ db_session.add(parent)+ await db_session.flush()+ monkeypatch.setattr("app.services.billing.settlement.estimate_task_fen", AsyncMock(return_value=100))+ async with billing_scope(parent.id, team_id=team.id):+ child = await create_task(db_session, owner, TaskCreateRequest(task_type="episode_script", drama_project_id=project.id, payload={"episode_number": 1, "_team_edit_resource": ["asset", 999999]}), commit=False)+ assert child.requested_by == member.id+ assert child.team_id == team.id+ assert child.payload["_team_edit_resource"] == ["episode", 1]+ assert child.payload.get("_team_parent_task_id") == parent.id+++async def test_postgres_project_transfer_and_task_admission_are_serialized(db_session, monkeypatch):+ import asyncio+ from sqlalchemy import delete+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine+ from app.config import get_settings+ from app.models import User+ from app.models_tasks import TaskEvent, TaskStep, TaskTarget+ from app.models_teams import Team, TeamActivity+ from app.models_team_billing import TeamMonthlyUsage, TeamWallet, TeamWalletLedger+ from app.services.tasks.service import create_task+ from app.services.teams.content import transfer_project+ from conftest import _resolve_test_database_url+ url, _ = _resolve_test_database_url(get_settings().database_url)+ engine = create_async_engine(url)+ sessions = async_sessionmaker(engine, expire_on_commit=False)+ team_id, project_id, second_id = None, None, None+ user_ids = []+ monkeypatch.setattr("app.services.billing.settlement.estimate_task_fen", AsyncMock(return_value=100))+ try:+ async with sessions() as db:+ team, owner, member = await seed_team(db)+ first = DramaProject(user_id=owner.id, title="Task wins")+ second = DramaProject(user_id=owner.id, title="Transfer wins")+ db.add_all([first, second])+ await db.flush()+ team_id, project_id, second_id = team.id, first.id, second.id+ user_ids = [owner.id, member.id]+ owner_id = owner.id+ await db.commit()+ async with sessions() as task_db, sessions() as transfer_db:+ actor = await task_db.get(User, owner_id)+ queued = await create_task(task_db, actor, TaskCreateRequest(task_type="script_summary", drama_project_id=project_id), commit=False)+ assert queued.team_id is None+ attempted = asyncio.Event()+ original_execute = transfer_db.execute+ async def transfer_execute(statement, *args, **kwargs):+ if getattr(statement, "_for_update_arg", None) is not None and "drama_projects" in str(statement):+ attempted.set()+ return await original_execute(statement, *args, **kwargs)+ monkeypatch.setattr(transfer_db, "execute", transfer_execute)+ async def transfer():+ with pytest.raises(HTTPException) as exc:+ await transfer_project(transfer_db, team_id, owner_id, project_id)+ assert exc.value.status_code == 409+ await transfer_db.rollback()+ waiting = asyncio.create_task(transfer())+ await asyncio.wait_for(attempted.wait(), timeout=3)+ await task_db.commit()+ await asyncio.wait_for(waiting, timeout=3)+ async with sessions() as task_db, sessions() as transfer_db:+ actor = await task_db.get(User, owner_id)+ # Keep an old personal-space identity in this session, then let transfer win.+ await task_db.get(DramaProject, second_id)+ transferred, copier = await transfer_project(transfer_db, team_id, owner_id, second_id)+ attempted = asyncio.Event()+ original_execute = task_db.execute+ async def task_execute(statement, *args, **kwargs):+ if getattr(statement, "_for_update_arg", None) is not None and "drama_projects" in str(statement):+ attempted.set()+ return await original_execute(statement, *args, **kwargs)+ monkeypatch.setattr(task_db, "execute", task_execute)+ async def submit_stale():+ with pytest.raises(ValueError, match="归属已变化"):+ await create_task(task_db, actor, TaskCreateRequest(task_type="script_summary", drama_project_id=second_id), commit=False)+ await task_db.rollback()+ waiting = asyncio.create_task(submit_stale())+ await asyncio.wait_for(attempted.wait(), timeout=3)+ await transfer_db.commit()+ await asyncio.wait_for(waiting, timeout=3)+ assert transferred.team_id == team_id+ finally:+ if team_id is not None:+ async with sessions() as db:+ task_ids = select(TaskRun.id).where(TaskRun.drama_project_id.in_([project_id, second_id]))+ for model in (TaskEvent, TaskStep, TaskTarget):+ await db.execute(delete(model).where(model.task_id.in_(task_ids)))+ await db.execute(delete(TaskRun).where(TaskRun.drama_project_id.in_([project_id, second_id])))+ await db.execute(delete(TeamActivity).where(TeamActivity.team_id == team_id))+ await db.execute(delete(DramaProject).where(DramaProject.id.in_([project_id, second_id])))+ for model in (TeamMonthlyUsage, TeamWalletLedger, TeamWallet, TeamMember):+ await db.execute(delete(model).where(model.team_id == team_id))+ await db.execute(delete(Team).where(Team.id == team_id))+ from app.models import WalletLedger+ await db.execute(delete(WalletLedger).where(WalletLedger.user_id.in_(user_ids)))+ await db.execute(delete(User).where(User.id.in_(user_ids)))+ await db.commit()+ await engine.dispose()++[email protected]("succeed", [True, False])+async def test_team_ephemeral_releases_admission_locks_and_finishes_durably(db_session, monkeypatch, succeed):+ """No shared admission lock spans the executor, including commit=False callers."""+ from sqlalchemy import delete+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine+ from app.config import get_settings+ from app.models import User+ from app.models_tasks import TaskEvent, TaskStep+ from app.models_teams import Team+ from app.models_team_billing import TeamMonthlyUsage, TeamWallet, TeamWalletLedger+ from app.services.billing.ephemeral import run_billed_ephemeral+ from conftest import _resolve_test_database_url+ url, _ = _resolve_test_database_url(get_settings().database_url)+ engine = create_async_engine(url)+ sessions = async_sessionmaker(engine, expire_on_commit=False)+ team_id, project_id = None, None+ user_ids = []+ monkeypatch.setattr("app.services.billing.settlement.estimate_task_fen", AsyncMock(return_value=100))+ try:+ async with sessions() as db:+ team, owner, member = await seed_team(db)+ project = DramaProject(user_id=owner.id, team_id=team.id, title="Inline task")+ db.add(project)+ await db.flush()+ team_id, project_id, member_id = team.id, project.id, member.id+ user_ids = [owner.id, member.id]+ await db.commit()+ async with sessions() as db:+ actor = await db.get(User, member_id)+ async def executor():+ async with sessions() as check_db:+ # NOWAIT is a real PostgreSQL assertion: no lease/wallet lock is+ # allowed to remain held by the network task's admission phase.+ for model, filters in (+ (Team, [Team.id == team_id]),+ (TeamMember, [TeamMember.team_id == team_id, TeamMember.user_id == member_id]),+ (DramaProject, [DramaProject.id == project_id]),+ (TeamWallet, [TeamWallet.team_id == team_id]),+ ):+ assert (await check_db.execute(select(model).where(*filters).with_for_update(nowait=True))).scalar_one() is not None+ running = (await check_db.execute(select(TaskRun).where(TaskRun.drama_project_id == project_id))).scalar_one()+ assert running.status == "running"+ if not succeed:+ raise RuntimeError("stub upstream failure")+ return {"ok": True}+ if succeed:+ await run_billed_ephemeral(db, actor, domain="drama", task_type="agent_chat", drama_project_id=project_id, executor=executor, commit=False)+ else:+ with pytest.raises(RuntimeError, match="stub upstream failure"):+ await run_billed_ephemeral(db, actor, domain="drama", task_type="agent_chat", drama_project_id=project_id, executor=executor, commit=False)+ # A later caller rollback must not revive an accepted running task or freeze.+ await db.rollback()+ async with sessions() as db:+ finished = (await db.execute(select(TaskRun).where(TaskRun.drama_project_id == project_id))).scalar_one()+ assert finished.status == ("succeeded" if succeed else "failed")+ assert finished.billing_status == "settled"+ wallet = await db.get(TeamWallet, team_id)+ assert (wallet.balance_fen, wallet.frozen_fen) == (0, 0)+ finally:+ if team_id is not None:+ async with sessions() as db:+ ids = select(TaskRun.id).where(TaskRun.drama_project_id == project_id)+ for model in (TaskEvent, TaskStep):+ await db.execute(delete(model).where(model.task_id.in_(ids)))+ await db.execute(delete(TaskRun).where(TaskRun.drama_project_id == project_id))+ await db.execute(delete(DramaProject).where(DramaProject.id == project_id))+ for model in (TeamMonthlyUsage, TeamWalletLedger, TeamWallet, TeamMember):+ await db.execute(delete(model).where(model.team_id == team_id))+ await db.execute(delete(Team).where(Team.id == team_id))+ from app.models import WalletLedger+ await db.execute(delete(WalletLedger).where(WalletLedger.user_id.in_(user_ids)))+ await db.execute(delete(User).where(User.id.in_(user_ids)))+ await db.commit()+ await engine.dispose()diff --git a/backend/tests/test_team_tasks_api.py b/backend/tests/test_team_tasks_api.pynew file mode 100644index 0000000..ccfad97--- /dev/null+++ b/backend/tests/test_team_tasks_api.py@@ -0,0 +1,42 @@+"""The unified task list honors the central frontend workspace header."""+from unittest.mock import AsyncMock+import httpx+import pytest+from fastapi import FastAPI+from app.api import tasks+from app.database import get_db+from app.deps import get_current_user+from app.models import User++[email protected]("query,header,expected", [("", "91", 91), ("?team_id=91", None, 91), ("", None, None)])+async def test_task_list_resolves_workspace_header(monkeypatch, query, header, expected):+ app = FastAPI()+ app.include_router(tasks.router)+ async def db():+ yield object()+ app.dependency_overrides[get_db] = db+ app.dependency_overrides[get_current_user] = lambda: User(id=1)+ listing = AsyncMock(return_value=([], 0))+ monkeypatch.setattr(tasks, "list_tasks_for_user", listing)+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://test") as client:+ response = await client.get("/tasks" + query, headers={"X-Team-Id": header} if header else {})+ assert response.status_code == 200+ assert listing.await_args.kwargs["team_id"] == expected+++async def test_task_list_rejects_inconsistent_workspace(monkeypatch):+ app = FastAPI()+ app.include_router(tasks.router)+ async def db():+ yield object()+ app.dependency_overrides[get_db] = db+ app.dependency_overrides[get_current_user] = lambda: User(id=1)+ listing = AsyncMock(return_value=([], 0))+ monkeypatch.setattr(tasks, "list_tasks_for_user", listing)+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://test") as client:+ response = await client.get("/tasks?team_id=92", headers={"X-Team-Id": "91"})+ assert response.status_code == 422+ listing.assert_not_awaited()diff --git a/backend/tests/test_team_voice_billing.py b/backend/tests/test_team_voice_billing.pynew file mode 100644index 0000000..e0f2609--- /dev/null+++ b/backend/tests/test_team_voice_billing.py@@ -0,0 +1,67 @@+"""Offline contract checks for team voice generation's task billing wrapper."""+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock+import pytest+from fastapi import HTTPException+from app.models import User+from app.models_drama import DramaAsset, DramaProject+from app.schemas_drama import DramaVoiceGenerateRequest+from app.api.drama import generation++[email protected]("team_id", [None, 91])+async def test_voice_endpoint_bills_only_team_inline_tasks(monkeypatch, team_id):+ project = DramaProject(id=17, user_id=2, team_id=team_id)+ asset = DramaAsset(id=8, project_id=17, type="voice", asset_type="audio", name="音色", url="/static/voice.mp3", params={})+ db = SimpleNamespace(get=AsyncMock(return_value=asset), commit=AsyncMock(), refresh=AsyncMock(), flush=AsyncMock(), rollback=AsyncMock())+ monkeypatch.setattr(generation, "get_owned_drama_project", AsyncMock(return_value=project))+ synthesize = AsyncMock(return_value=asset)+ monkeypatch.setattr(generation, "generate_voice_asset_audio", synthesize)+ async def billed(_db, _user, **kwargs):+ db.commit.assert_not_awaited()+ assert kwargs["task_type"] == "voice_synthesis"+ assert (kwargs["drama_project_id"], kwargs["asset_id"]) == (17, 8)+ return SimpleNamespace(id=5), await kwargs["executor"]()+ billing = AsyncMock(side_effect=billed)+ monkeypatch.setattr(generation, "run_billed_ephemeral", billing)+ result = await generation.generate_voice(DramaVoiceGenerateRequest(project_id=17, asset_id=8, voice_prompt="沉稳的声音"), db=db, user=User(id=2))+ assert result["asset"]["id"] == 8+ assert billing.await_count == (0 if team_id is None else 1)+ synthesize.assert_awaited_once()+++async def test_team_voice_budget_failure_preserves_payment_status(monkeypatch):+ project = DramaProject(id=17, user_id=2, team_id=91)+ asset = DramaAsset(id=8, project_id=17, type="voice", asset_type="audio", params={})+ db = SimpleNamespace(get=AsyncMock(return_value=asset), commit=AsyncMock(), refresh=AsyncMock(), flush=AsyncMock(), rollback=AsyncMock())+ monkeypatch.setattr(generation, "get_owned_drama_project", AsyncMock(return_value=project))+ synthesize = AsyncMock()+ monkeypatch.setattr(generation, "generate_voice_asset_audio", synthesize)+ monkeypatch.setattr(generation, "run_billed_ephemeral", AsyncMock(side_effect=ValueError("团队余额不足,请联系所有者充值")))+ with pytest.raises(HTTPException) as exc:+ await generation.generate_voice(DramaVoiceGenerateRequest(project_id=17, asset_id=8, voice_prompt="声音"), db=db, user=User(id=2))+ assert exc.value.status_code == 402+ db.rollback.assert_awaited_once()+ db.commit.assert_not_awaited()+ synthesize.assert_not_awaited()+++async def test_new_team_voice_is_not_committed_before_budget_admission(monkeypatch):+ project = DramaProject(id=17, user_id=2, team_id=91)+ db = SimpleNamespace(add=Mock(), get=AsyncMock(), commit=AsyncMock(), refresh=AsyncMock(), flush=AsyncMock(), rollback=AsyncMock())+ db.add.side_effect = lambda asset: setattr(asset, "id", 8)+ monkeypatch.setattr(generation, "get_owned_drama_project", AsyncMock(return_value=project))+ async def rejected(*args, **kwargs):+ db.commit.assert_not_awaited()+ db.flush.assert_awaited()+ assert kwargs["asset_id"] == 8+ raise ValueError("团队余额不足,请联系所有者充值")+ monkeypatch.setattr(generation, "run_billed_ephemeral", rejected)+ with pytest.raises(HTTPException) as exc:+ await generation.generate_voice(DramaVoiceGenerateRequest(project_id=17, voice_prompt="新声音"), db=db, user=User(id=2))+ assert exc.value.status_code == 402+ db.rollback.assert_awaited_once()+ db.commit.assert_not_awaited()diff --git a/backend/tests/test_teams_api.py b/backend/tests/test_teams_api.pynew file mode 100644index 0000000..abb7e9c--- /dev/null+++ b/backend/tests/test_teams_api.py@@ -0,0 +1,348 @@+"""团队核心 HTTP 集成测试:独立 Postgres 测试库、事务回滚、邮件永不外发。"""+from __future__ import annotations++from datetime import UTC, datetime, timedelta+from types import SimpleNamespace+from unittest.mock import AsyncMock++import httpx+import pytest+import pytest_asyncio+from fastapi import FastAPI+from sqlalchemy import select++from app.api.teams import invitation_router, router+from app.database import get_db+from app.deps import get_current_user+from app.models_team_billing import TeamMonthlyUsage, TeamWallet+from app.models_teams import Team, TeamInvitation, TeamMember+from app.services.teams.access import get_team+from app.services.billing.team import billing_period+from tests.conftest import make_user+++@pytest_asyncio.fixture+async def teams_api(db_session, monkeypatch):+ """挂载真实团队路由,通过依赖覆盖共享回滚事务与可切换登录用户。"""+ owner, admin, member, outsider = [await make_user(db_session) for _ in range(4)]+ for user in (owner, admin, member, outsider):+ user.email = user.email.replace("@test.local", "@example.com")+ owner.nickname, admin.nickname, member.nickname = "所有者", "管理员", "创作者"+ await db_session.flush()+ auth = {"user": owner}+ app = FastAPI()+ app.include_router(router, prefix="/api")+ app.include_router(invitation_router, prefix="/api")++ async def session_override():+ """HTTP 请求沿用测试事务。"""+ yield db_session++ async def user_override():+ """切换当前请求的已认证用户,不产生真实登录 token。"""+ return auth["user"]++ app.dependency_overrides[get_db] = session_override+ app.dependency_overrides[get_current_user] = user_override+ monkeypatch.setattr("app.services.teams.invitations.send_email", AsyncMock(return_value=False))+ removed_tasks, removed_locks = AsyncMock(), AsyncMock()+ monkeypatch.setattr("app.services.tasks.team_scope.cancel_removed_member_tasks", removed_tasks)+ monkeypatch.setattr("app.services.teams.edit_locks.release_member_locks", removed_locks)+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test.local") as client:+ created = await client.post("/api/teams", json={"name": "青禾影像", "description": "一起创作", "color": "#435c4b"})+ assert created.status_code == 201, created.text+ team_id = created.json()["id"]+ db_session.add_all([+ TeamMember(team_id=team_id, user_id=admin.id, role="admin", active=True),+ TeamMember(team_id=team_id, user_id=member.id, role="member", active=True),+ ])+ await db_session.commit()+ yield SimpleNamespace(db=db_session, client=client, app=app, auth=auth, owner=owner, admin=admin, member=member, outsider=outsider, team_id=team_id, removed_tasks=removed_tasks, removed_locks=removed_locks)+++async def invite(api, email: str | None = None):+ """以当前操作者创建真实数据库邀请,但邮件已由 fixture 隔离。"""+ return await api.client.post(f"/api/teams/{api.team_id}/invitations", json={"email": email or api.outsider.email})+++async def test_teams_create_summary_pagination_and_wallet(teams_api):+ """创建团队同时建立所有者关系和零余额钱包;列表遵守分页。"""+ a = teams_api+ result = await a.client.get("/api/teams", params={"page_size": 1})+ assert result.status_code == 200+ data = result.json()+ assert data["meta"] == {"page": 1, "page_size": 1, "total": 1}+ assert data["items"][0]["my_role"] == "owner"+ assert data["items"][0]["viewer_id"] == a.owner.id+ assert data["items"][0]["member_count"] == 3+ wallet = await a.db.get(TeamWallet, a.team_id)+ assert wallet is None+ assert (await a.client.get("/api/teams", params={"page": 2})).json()["items"] == []+++async def test_teams_access_rechecks_membership_and_role(teams_api):+ """无成员资格返回 404;角色不足返回 403,不能用全站管理员越权。"""+ a = teams_api+ a.auth["user"] = a.outsider+ a.outsider.role = "admin"+ assert (await a.client.get(f"/api/teams/{a.team_id}")).status_code == 404+ assert (await a.client.get("/api/teams")).json()["meta"]["total"] == 0+ a.auth["user"] = a.member+ assert (await a.client.patch(f"/api/teams/{a.team_id}", json={"name": "越权"})).status_code == 403+ row = (await a.db.execute(select(TeamMember).where(TeamMember.team_id == a.team_id, TeamMember.user_id == a.member.id))).scalar_one()+ row.active = False+ await a.db.commit()+ assert (await a.client.get(f"/api/teams/{a.team_id}")).status_code == 404+++async def test_teams_schema_and_owner_update(teams_api):+ """空名、超长文本、非法颜色及小数金额在执行前被拒绝。"""+ a = teams_api+ for patch in ({"name": " "}, {"name": "长" * 41}, {"description": "长" * 181}, {"color": "red"}, {"name": None}):+ assert (await a.client.patch(f"/api/teams/{a.team_id}", json=patch)).status_code == 422+ result = await a.client.patch(f"/api/teams/{a.team_id}", json={"name": " 新团队 ", "description": " 新介绍 "})+ assert result.json()["name"] == "新团队"+ assert result.json()["description"] == "新介绍"+ assert (await a.client.get(f"/api/teams/{a.team_id}/activities")).json()["meta"]["total"] >= 2+++async def test_teams_member_finances_are_owner_or_self_only(teams_api):+ """非所有者仅本人获得财务数字,其他成员仍可正常查看基本信息。"""+ a = teams_api+ period = billing_period()+ a.db.add(TeamMonthlyUsage(team_id=a.team_id, user_id=a.member.id, period=period, spent_fen=321, reserved_fen=123))+ await a.db.commit()+ for viewer in (a.owner, a.admin, a.member):+ a.auth["user"] = viewer+ result = (await a.client.get(f"/api/teams/{a.team_id}/members")).json()+ rows = {item["id"]: item for item in result["items"]}+ assert result["meta"]["total"] == 3+ assert rows[a.member.id]["spent_fen"] == (321 if viewer in (a.owner, a.member) else None)+ assert rows[a.owner.id]["reserved_fen"] == (0 if viewer is a.owner else None)+ result = await a.client.get(f"/api/teams/{a.team_id}/members", params={"q": "管理员", "role": "admin", "page_size": 1})+ assert result.json()["meta"]["total"] == 1+ assert result.json()["items"][0]["id"] == a.admin.id+++async def test_teams_owner_sets_role_and_nullable_zero_limits(teams_api):+ """额度以整数分存储;0 禁止新增消费,null 不限额;管理员无权改额度。"""+ a = teams_api+ path = f"/api/teams/{a.team_id}/members/{a.member.id}"+ for amount in (-1, 0.5, True, 100_000_001):+ assert (await a.client.patch(path, json={"monthly_limit_fen": amount})).status_code == 422+ for amount in (0, 12345, None):+ response = await a.client.patch(path, json={"monthly_limit_fen": amount})+ assert response.status_code == 200, response.text+ assert response.json()["monthly_limit_fen"] == amount+ assert (await a.client.patch(path, json={"role": "admin"})).json()["role"] == "admin"+ assert (await a.client.patch(path, json={"role": None})).status_code == 422+ assert (await a.client.patch(f"/api/teams/{a.team_id}/members/{a.owner.id}", json={"role": "member"})).status_code == 409+ a.auth["user"] = a.admin+ assert (await a.client.patch(path, json={"monthly_limit_fen": 0})).status_code == 403+++async def test_teams_remove_and_leave_soft_delete_with_cleanup(teams_api):+ """移除与退出保留成员行,取消未开始任务并释放该成员编辑锁。"""+ a = teams_api+ assert (await a.client.delete(f"/api/teams/{a.team_id}/members/{a.owner.id}")).status_code == 409+ a.auth["user"] = a.admin+ assert (await a.client.delete(f"/api/teams/{a.team_id}/members/{a.owner.id}")).status_code == 403+ response = await a.client.delete(f"/api/teams/{a.team_id}/members/{a.member.id}")+ assert response.status_code == 200+ row = (await a.db.execute(select(TeamMember).where(TeamMember.team_id == a.team_id, TeamMember.user_id == a.member.id))).scalar_one()+ assert row.active is False+ a.removed_tasks.assert_awaited_with(a.db, a.team_id, a.member.id)+ a.removed_locks.assert_awaited_with(a.db, a.team_id, a.member.id)+ assert (await a.client.post(f"/api/teams/{a.team_id}/leave")).status_code == 200+ assert (await a.client.get(f"/api/teams/{a.team_id}")).status_code == 404+++async def test_teams_transfer_is_atomic_and_owner_authoritative(teams_api):+ """所有权转移后唯一 owner 与权威 owner_user_id 一致,旧所有者变为 admin。"""+ a = teams_api+ target_member = (await a.db.execute(select(TeamMember).where(TeamMember.team_id == a.team_id, TeamMember.user_id == a.member.id))).scalar_one()+ target_member.monthly_limit_fen = 0+ await a.db.commit()+ assert (await a.client.post(f"/api/teams/{a.team_id}/leave")).status_code == 409+ assert (await a.client.post(f"/api/teams/{a.team_id}/transfer-ownership", json={"user_id": a.owner.id})).status_code == 409+ assert (await a.client.post(f"/api/teams/{a.team_id}/transfer-ownership", json={"user_id": a.outsider.id})).status_code == 404+ result = await a.client.post(f"/api/teams/{a.team_id}/transfer-ownership", json={"user_id": a.member.id})+ assert result.status_code == 200, result.text+ team = await a.db.get(Team, a.team_id, populate_existing=True)+ rows = (await a.db.execute(select(TeamMember).where(TeamMember.team_id == a.team_id))).scalars().all()+ assert team.owner_user_id == a.member.id+ assert [row.user_id for row in rows if row.role == "owner"] == [a.member.id]+ assert next(row for row in rows if row.user_id == a.owner.id).role == "admin"+ assert next(row for row in rows if row.user_id == a.member.id).monthly_limit_fen == 0+ assert (await a.client.patch(f"/api/teams/{a.team_id}", json={"name": "旧所有者"})).status_code == 403+++async def test_teams_invitation_only_hash_stored_email_bound_and_single_use(teams_api):+ """邀请令牌仅哈希持久化、必须邮箱匹配、成功加入后不可重复消费。"""+ a = teams_api+ response = await invite(a)+ assert response.status_code == 201, response.text+ invitation = response.json()+ assert invitation["email_sent"] is False+ assert invitation["token"] in invitation["accept_url"]+ row = await a.db.get(TeamInvitation, invitation["invitation"]["id"])+ assert len(row.token_hash) == 64 and row.token_hash != invitation["token"]+ assert "token_hash" not in invitation["invitation"]+ a.auth["user"] = a.member+ assert (await a.client.post("/api/team-invitations/inspect", json={"token": invitation["token"]})).status_code == 403+ a.auth["user"] = a.outsider+ assert (await a.client.post("/api/team-invitations/inspect", json={"token": invitation["token"]})).json()["team_name"] == "青禾影像"+ accepted = await a.client.post("/api/team-invitations/accept", json={"token": invitation["token"]})+ assert accepted.status_code == 200+ assert accepted.json()["my_role"] == "member"+ assert (await a.client.post("/api/team-invitations/accept", json={"token": invitation["token"]})).status_code == 409+++async def test_teams_invitation_duplicate_resend_revoke_and_expiry(teams_api):+ """有效邀请不重复签发,重发轮换令牌,撤回及过期令牌不能使用。"""+ a = teams_api+ assert (await invite(a, a.member.email)).status_code == 409+ first = (await invite(a)).json()+ assert (await invite(a)).status_code == 409+ listing = (await a.client.get(f"/api/teams/{a.team_id}/invitations")).json()+ assert listing["meta"]["total"] == 1+ assert set(listing["items"][0]).isdisjoint({"token", "token_hash"})+ invite_id = first["invitation"]["id"]+ resent = await a.client.post(f"/api/teams/{a.team_id}/invitations/{invite_id}/resend")+ assert resent.status_code == 200+ assert resent.json()["token"] != first["token"]+ a.auth["user"] = a.outsider+ assert (await a.client.post("/api/team-invitations/accept", json={"token": first["token"]})).status_code == 404+ a.auth["user"] = a.owner+ assert (await a.client.post(f"/api/teams/{a.team_id}/invitations/{invite_id}/revoke")).status_code == 200+ a.auth["user"] = a.outsider+ assert (await a.client.post("/api/team-invitations/accept", json={"token": resent.json()["token"]})).status_code == 409+ a.auth["user"] = a.owner+ second = (await invite(a)).json()+ row = await a.db.get(TeamInvitation, second["invitation"]["id"])+ row.expires_at = datetime.now(UTC) - timedelta(seconds=1)+ await a.db.commit()+ a.auth["user"] = a.outsider+ assert (await a.client.post("/api/team-invitations/accept", json={"token": second["token"]})).status_code == 410+++async def test_teams_rejoin_preserves_limit_and_monthly_usage(teams_api):+ """软退出重新加入不得重置原有月消费或额度,重新加入角色为普通成员。"""+ a = teams_api+ row = (await a.db.execute(select(TeamMember).where(TeamMember.team_id == a.team_id, TeamMember.user_id == a.member.id))).scalar_one()+ row.monthly_limit_fen, row.active = 5000, False+ a.db.add(TeamMonthlyUsage(team_id=a.team_id, user_id=a.member.id, period=billing_period(), spent_fen=4000, reserved_fen=0))+ await a.db.commit()+ created = (await invite(a, a.member.email)).json()+ a.auth["user"] = a.member+ assert (await a.client.post("/api/team-invitations/accept", json={"token": created["token"]})).status_code == 200+ listing = (await a.client.get(f"/api/teams/{a.team_id}/members")).json()+ me = next(item for item in listing["items"] if item["id"] == a.member.id)+ assert (me["role"], me["monthly_limit_fen"], me["spent_fen"]) == ("member", 5000, 4000)+++async def test_teams_resend_expired_invite_cannot_duplicate_new_invite(teams_api):+ """过期后另发新邀请,旧邀请不能通过重发恢复出第二条有效链接。"""+ a = teams_api+ first = (await invite(a)).json()+ old = await a.db.get(TeamInvitation, first["invitation"]["id"])+ old.expires_at = datetime.now(UTC) - timedelta(seconds=1)+ await a.db.commit()+ second = (await invite(a)).json()+ path = f"/api/teams/{a.team_id}/invitations/{old.id}/resend"+ assert (await a.client.post(path)).status_code == 409+ a.auth["user"] = a.outsider+ assert (await a.client.post("/api/team-invitations/accept", json={"token": second["token"]})).status_code == 200+ a.auth["user"] = a.owner+ assert (await a.client.post(path)).status_code == 409+++async def test_teams_member_cannot_manage_invites_and_lists_require_auth(teams_api):+ """普通成员不能读邀请邮箱列表,未登录不能读任何团队接口。"""+ a = teams_api+ a.auth["user"] = a.member+ assert (await a.client.get(f"/api/teams/{a.team_id}/invitations")).status_code == 403+ assert (await invite(a)).status_code == 403+ a.app.dependency_overrides.pop(get_current_user)+ assert (await a.client.get("/api/teams")).status_code == 401+++async def test_owner_sets_total_and_own_member_budget_without_resetting_usage(teams_api):+ """所有者能设置两级额度;普通成员不能改团队上限,null 正确清除上限。"""+ a = teams_api+ url = f"/api/teams/{a.team_id}"+ for cap in (500, 0, None):+ assert (await a.client.patch(url, json={"monthly_limit_fen": cap})).status_code == 200+ team = await a.db.get(Team, a.team_id)+ assert team.monthly_limit_fen == cap+ assert (await a.client.patch(url + f"/members/{a.owner.id}", json={"monthly_limit_fen": 0})).status_code == 200+ assert (await a.client.patch(url + f"/members/{a.owner.id}", json={"role": "member"})).status_code == 409+ for cap in (-1, True, 1.5, "500", 100000001):+ assert (await a.client.patch(url, json={"monthly_limit_fen": cap})).status_code == 422+ a.auth["user"] = a.member+ assert (await a.client.patch(url, json={"monthly_limit_fen": 0})).status_code == 403++[email protected]("actor, expected", [("admin", 403), ("member", 403), ("outsider", 404)])+async def test_delete_team_requires_owner(teams_api, actor, expected):+ a = teams_api+ a.auth["user"] = getattr(a, actor)+ response = await a.client.delete(f"/api/teams/{a.team_id}")+ assert response.status_code == expected+ a.auth["user"] = a.owner+ assert (await a.client.get(f"/api/teams/{a.team_id}")).status_code == 200+++async def test_delete_team_revokes_access_invites_and_retains_history(teams_api):+ from app.models_tasks import TaskRun+ from app.models_teams import TeamActivity+ a = teams_api+ issued = await invite(a)+ assert issued.status_code == 201+ history = TaskRun(domain="drama", task_type="fragment_video", queue_type="video",+ requested_by=a.owner.id, team_id=a.team_id, status="succeeded")+ a.db.add(history)+ await a.db.commit()+ history_id = history.id+ response = await a.client.delete(f"/api/teams/{a.team_id}")+ assert response.status_code == 204, response.text+ for user in (a.owner, a.admin, a.member):+ a.auth["user"] = user+ assert (await a.client.get("/api/teams")).json()["items"] == []+ assert (await a.client.get(f"/api/teams/{a.team_id}")).status_code == 404+ assert (await a.client.delete(f"/api/teams/{a.team_id}")).status_code == 404+ invitation = await a.db.scalar(select(TeamInvitation).where(TeamInvitation.team_id == a.team_id))+ assert invitation.revoked_at is not None+ assert await a.db.get(Team, a.team_id) is not None+ assert (await a.db.get(TaskRun, history_id)).team_id == a.team_id+ assert await a.db.scalar(select(TeamActivity.id).where(TeamActivity.team_id == a.team_id, TeamActivity.action == "team.deleted"))+ assert a.removed_locks.await_count == 3++[email protected]("status", ["pending", "running", "awaiting_poll", "finalizing"])+async def test_delete_team_blocks_unfinished_generation(teams_api, status):+ from app.models_tasks import TaskRun+ a = teams_api+ a.db.add(TaskRun(domain="drama", task_type="fragment_video", queue_type="video",+ requested_by=a.member.id, team_id=a.team_id, status=status))+ await a.db.commit()+ response = await a.client.delete(f"/api/teams/{a.team_id}")+ assert response.status_code == 409, response.text+ assert (await a.client.get(f"/api/teams/{a.team_id}")).status_code == 200+ a.removed_locks.assert_not_awaited()diff --git a/backend/tests/test_teams_validation.py b/backend/tests/test_teams_validation.pynew file mode 100644index 0000000..92cebfb--- /dev/null+++ b/backend/tests/test_teams_validation.py@@ -0,0 +1,54 @@+"""团队核心输入边界与所有权权威判断,不连接数据库。"""+import pytest+from pydantic import ValidationError++from app.models_teams import Team, TeamInvitation, TeamMember+from app.schemas_teams import TeamCreate, TeamInvitationToken, TeamMemberPatch, TeamUpdate+from app.services.teams.access import member_role+from app.services.teams.invitations import hash_token, invitation_frontend_base+++def test_teams_inputs_trim_text_and_reject_unknown_or_empty_patches():+ """资料统一去空格;不允许 null 擦除资料或未知字段静默通过。"""+ assert TeamCreate(name=" 工作室 ").name == "工作室"+ assert TeamUpdate(description=" 简介 ").description == "简介"+ for body in ({}, {"name": None}, {"color": "#123"}, {"unexpected": "value"}):+ with pytest.raises(ValidationError):+ TeamUpdate.model_validate(body)+ for body in ({}, {"role": None}, {"role": "owner"}, {"monthly_limit_fen": "100"}, {"monthly_limit_fen": True}):+ with pytest.raises(ValidationError):+ TeamMemberPatch.model_validate(body)+ assert TeamMemberPatch(monthly_limit_fen=None).model_dump(exclude_unset=True) == {"monthly_limit_fen": None}+ assert TeamMemberPatch(monthly_limit_fen=0).monthly_limit_fen == 0+++def test_teams_owner_field_overrides_stale_member_owner_marker():+ """owner_user_id 不匹配时,残留 owner 标记不授予所有者权限。"""+ team = Team(owner_user_id=2)+ assert member_role(team, TeamMember(user_id=1, role="owner")) == "member"+ assert member_role(team, TeamMember(user_id=1, role="admin")) == "admin"+ assert member_role(team, TeamMember(user_id=2, role="member")) == "owner"+++def test_teams_tokens_are_bounded_and_only_hash_is_mapped():+ """数据库中无明文 token 列;摘要长度固定且输入令牌长度受限。"""+ token = "a" * 43+ digest = hash_token(token)+ assert len(digest) == 64 and digest != token+ assert hash_token(token) == digest+ assert "token" not in TeamInvitation.__table__.columns+ for invalid in ("", "short", "a" * 257):+ with pytest.raises(ValidationError):+ TeamInvitationToken(token=invalid)+++def test_teams_invite_links_only_use_allowlisted_frontend_origins(monkeypatch):+ """浏览器本地源生成可打开的前端链接,任意或畸形 Origin 不进入邀请邮件。"""+ from app.config import get_settings++ settings = get_settings()+ monkeypatch.setattr(settings, "public_base_url", "https://www.printfilm.com")+ monkeypatch.setattr(settings, "cors_origins", "http://127.0.0.1:5173,https://www.printfilm.com")+ assert invitation_frontend_base("http://127.0.0.1:5173") == "http://127.0.0.1:5173"+ for origin in (None, "https://evil.example", "http://127.0.0.1:5173/teams", "null", "http://127.0.0.1:[email protected]", "http://["):+ assert invitation_frontend_base(origin) == "https://www.printfilm.com"diff --git a/docs/TEAM_MODE.md b/docs/TEAM_MODE.mdnew file mode 100644index 0000000..ee04c9e--- /dev/null+++ b/docs/TEAM_MODE.md@@ -0,0 +1,59 @@+# 团队模式 V1++团队页 `/teams` 使用真实登录身份与 PostgreSQL 数据,不再使用示例团队或浏览器内模拟账单。团队空间仅覆盖漫剧项目和资产;短视频与独立工具仍属于个人空间。++## 成员与权限++用户可免费创建多个团队。所有有效成员可查看和创作团队内全部漫剧项目。所有者管理团队和成员月额度、任命管理员及所有权转让;管理员可邀请成员、移除普通成员、删除项目和取消队友任务;普通成员仅能取消本人任务。所有者必须先转让再退出。++邀请绑定收件邮箱,有效期 7 天,仅保存令牌摘要;重发会撤销旧令牌。接受时必须登录对应邮箱。已配置邮件服务时发送邀请,否则页面提供可复制链接。签发链接使用 CORS 白名单中的前端 Origin,后台调用回退 `PUBLIC_BASE_URL`。++成员退出或被移除后立即失去读写权限,人工编辑占用同时释放。未开始的任务取消并释放预留额度;已提交上游的任务继续取回结果并按受理时的付款账户结算并记入原团队,新生成请求重新核对有效成员关系。++## 创作与协作++团队列表均由服务端搜索、筛选和分页。旧漫剧资源接口通过数据库实际归属授权,不依赖客户端传来的空间标记。`X-Team-Id` 仅用于列表与创建时选择空间。++编辑租约有效期 120 秒,前端每 30 秒续租。资产按资产 ID 占用,正文与分镜按稳定集号共用占用;不同集、不同资产可并行。结构级修改与项目全部资源互斥,画布布局与独立资产内容分别保存。所有者/管理员可接管人工占用,不能接管尚在执行的系统任务。每次重新获取都会增加 fencing 版本,旧标签页提交返回冲突。++正文使用 `PATCH /api/drama/scripts/{project_id}/episodes/{episode_number}` 按集读改写并校验内容版本。团队接口拒绝整包覆盖 `episode_content`。模型调用期间不持有共享剧本 JSON 行锁,写回时锁定最新内容,仅合并对应集及状态。单集自动后续流程仅处理本集,不刷新其他集或已有资产。++个人项目可以整体、单向迁入当前团队,要求本人所有且没有活动任务或编辑占用。项目与子资源 ID 保持不变,历史个人任务和消费继续属于个人;新任务按团队计费。迁入和任务受理通过项目行锁避免竞争。++资产复制由后端创建新资产并清除任务、画布及强关联 ID;本地媒体复制到目标项目的新文件名。受控 OSS 的稳定对象引用保留,当前删除入口不删除媒体对象。服务端不会为复制请求下载任意 URL。源项目删除不会删除副本文件。媒体链接继续公开,不提供私有媒体访问控制。++## 计费与运行++团队无独立余额,新任务直接扣所有者个人钱包,消费归属保留团队、实际操作成员和项目。受理时保存不可由客户端指定的 billing_payer_user_id,转让所有权不改变已受理任务的付款人。个人钱包流水备注包含团队和实际操作者,个人消费页包含由本人付款的团队用量;成员在团队页查看本人消费。++受理时检查所有者个人可用余额(含该所有者的个人任务和全部团队的排队预留),同时检查团队总月上限与成员月上限。执行时预扣冻结,结束按实结算、退还差额。两级额度都按上海时区自然月统计,跨月任务计入受理月份。null 不限额,0 阻止新付费任务,所有者自己的成员额度也生效。降低上限不取消已受理任务;取消未开始任务释放预留;上游实际费用超过估算仍如实结算,后续任务按剩余额度拦截。关闭计费时不扣款、不占额度。++所有者在“消费与额度”设置团队总月上限,在“成员管理”设置每个成员上限;管理员和普通成员只能看本人额度与消费,用户接口不暴露他人余额和上游成本。团队充值入口和独立余额调账已停用(旧 POST 接口返回 410),所有者通过个人账户充值。历史团队钱包及流水保留只读;无付款快照的旧在途任务继续在旧钱包完成冻结/结算,不重复扣个人账户。旧团队订单若收到有效支付回调,幂等入账至原下单人的个人账户,团队归属保留用于审计。++`TASK_TEAM_MAX_CONCURRENCY` 默认 4,与全站及个人并发限制同时生效。后台派生任务继承可信父任务的发起人与团队,且只能写父任务覆盖的资源。++## 接口与迁移++主要入口:`/api/teams`、`/api/team-invitations/{inspect,accept}`,团队内的 `projects`、`assets`、`members`、`invitations`、`activities`、`usage`、`wallet`、`orders` 与 `edit-locks`。完整参数见运行中的 `/docs`。++新增表在 `models_teams.py`、`models_team_billing.py`、`models_team_locks.py`。按现有启动机制先 `init_db()`,再执行 `_apply_schema_patches()`;团队增量 DDL 位于 `app/team_schema.py`,可重复执行,不删除历史列或搬迁个人余额。若设置 `DATABASE_BOOTSTRAP_ENABLED=false`,更新服务前需显式运行这两步。++在仓库根目录使用现有虚拟环境运行 `backend/.venv/Scripts/python.exe backend/scripts/prepare_team_schema.py` 即可执行这两步,不启动生成任务、支付或邮件。该命令使用 `backend/.env` 的连接配置。++测试只使用 `backend/scripts/run_tests.py` 加载隔离的 `.env.test`,不得直接以业务数据库配置运行集成测试。支付、邮件、模型接口在测试中替换为 stub,不产生真实支付或生成费用。++V1 不提供自定义角色、审批、评论、团队解散和余额转出。++## 平台管理端查询++管理端 `/teams` 提供平台管理员专用的团队列表与详情,可按团队名称、ID、所有者昵称或邮箱搜索,并查看团队规模、所有者个人余额、团队月上限、本月及累计实际消费。++团队详情支持当前/已退出成员、角色和月份筛选,查看成员额度、已消费与预留金额;从成员行可进入该成员的团队消费记录。消费明细可按成员、项目/模型关键词、结算状态及上海日期范围筛选,筛选合计覆盖全部结果,待结算金额不计入已结算合计。团队概况取月度结算账,明细取模型调用用量记录,两者分别标明统计口径。++只读接口为 `GET /api/admin/teams`、`GET /api/admin/teams/{id}`、`GET /api/admin/teams/{id}/members`、`GET /api/admin/teams/{id}/usage-events`,全部要求平台 `role=admin`,无需加入团队。普通团队所有者没有此权限。列表均使用服务端分页;查询不创建钱包、不修改成员及账务,也不返回密码、邀请令牌或原始上游响应。++团队详情提供“设置消费上限”,成员行也可分别设置月额度(包含所有者)。接口为 PATCH /api/admin/teams/{id}/budget 与 PATCH /api/admin/teams/{id}/members/{user_id}/budget,正文 monthly_limit_fen 为非负整数分或 null,最大 100,000,000 分。仅平台管理员可用,成员必须有效;操作与入队共用团队行锁并记录审计动态,不改变钱包或既有消费。需要调整付款账户余额时,在用户管理中调整所有者个人账户。++“历史团队钱包流水”通过 GET /api/admin/teams/{id}/wallet-ledger 查看旧变动金额、变动后余额、操作人及备注,支持仅后台调账、关键词搜索和服务端分页。该历史记录与新任务的个人钱包流水分别保留,不合并或搬迁历史资金。++本次增量迁移新增 teams.monthly_limit_fen、task_runs.billing_payer_user_id 和 usage_events.billing_payer_user_id 及索引,均为可空列,不回填历史付款人。回滚需保留新增字段并使带付款快照的任务继续由新版结算,不能直接将这类任务交给旧版团队钱包结算逻辑。