fix(test-round): 测试清单一批 bug 修复 + 团队月限额持久化
后端: - accounts: 团队级月限额持久化(Team.monthly_credit_limit 三态 + PATCH/GET /api/auth/team/settings/,刷新不丢,PMC#12);头像上传 500→502 可读错误; 设备下线真失效(删并重建 token,旧 token 401) - assets: 审核类目加 model_portrait,消除三视图"无需审核"误报 - ai/projects/products: 模特已有三视图复用、产品三视图同步回商品库 (metadata.view=three_view)、真人模特三视图回写 前端: - 商品图删除判断改用真实图片数;团队成员弹窗禁点外部关闭 - 图片预览骨架铺满占位;平台套图左侧栏折叠改导航同款;收件箱长文换行对齐 - 团队月限额改真落库(乐观更新+失败回滚) 测试:新增 TeamSettingsTests(5 条),accounts 全套 36 tests 通过;前端 build 0 error Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
# Generated by Django 5.1.15 on 2026-06-29 10:44
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("accounts", "0006_teammember_daily_credit_limit_and_more"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="team",
|
||||
name="monthly_credit_limit",
|
||||
field=models.DecimalField(
|
||||
blank=True, decimal_places=2, default=None, max_digits=12, null=True
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -32,6 +32,9 @@ class Team(TimeStampedModel):
|
||||
name = models.CharField(max_length=128)
|
||||
status = models.CharField(max_length=24, choices=Status.choices, default=Status.ACTIVE)
|
||||
owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name="owned_teams")
|
||||
# 团队级月限额(超管在团队页设置,自然月重置)。语义三态,与成员级 0=不限 不同:
|
||||
# None = 未设置(前端按成员月度额度累加作团队月限额)· -1 = 不限 · >=0 = 固定上限。
|
||||
monthly_credit_limit = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True, default=None)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.name
|
||||
|
||||
@@ -38,7 +38,7 @@ class LoginSessionSerializer(serializers.ModelSerializer):
|
||||
class TeamSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Team
|
||||
fields = ["id", "name", "status", "owner", "created_at", "updated_at"]
|
||||
fields = ["id", "name", "status", "owner", "monthly_credit_limit", "created_at", "updated_at"]
|
||||
read_only_fields = ["id", "status", "owner", "created_at", "updated_at"]
|
||||
|
||||
|
||||
|
||||
@@ -404,3 +404,171 @@ class ValidateInviteTests(TestCase):
|
||||
self.assertEqual(r.status_code, 200)
|
||||
self.assertFalse(r.data["valid"])
|
||||
|
||||
|
||||
class AvatarUploadTests(TestCase):
|
||||
"""bug(9):上传新头像点「确认使用」弹 500。真因之一=对象存储上传异常裸抛 500;
|
||||
现改为捕获后回 502 + 人话,成功路径回 200 + 新 avatar_url。"""
|
||||
|
||||
def setUp(self):
|
||||
from rest_framework.authtoken.models import Token
|
||||
|
||||
self.user = User.objects.create_user(username="av-user", password="strong-password")
|
||||
self.token = Token.objects.create(user=self.user)
|
||||
self.client = APIClient()
|
||||
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
|
||||
|
||||
def _png(self):
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
|
||||
# 1x1 PNG 字节(够 multipart 上传,内容无所谓,storage 被 mock)
|
||||
png = (
|
||||
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
|
||||
b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00"
|
||||
b"\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82"
|
||||
)
|
||||
return SimpleUploadedFile("avatar.png", png, content_type="image/png")
|
||||
|
||||
def test_upload_success_returns_200_and_sets_url(self):
|
||||
from unittest import mock
|
||||
|
||||
with mock.patch("apps.assets.storage.TosStorage") as MockStorage:
|
||||
inst = MockStorage.return_value
|
||||
inst.upload_fileobj.return_value = None
|
||||
inst.public_url.return_value = "https://bucket.example.com/users/x/avatar/abc.png"
|
||||
r = self.client.post("/api/auth/me/avatar/", {"file": self._png()}, format="multipart")
|
||||
self.assertEqual(r.status_code, 200, r.data)
|
||||
self.user.refresh_from_db()
|
||||
self.assertEqual(self.user.avatar_url, "https://bucket.example.com/users/x/avatar/abc.png")
|
||||
|
||||
def test_upload_storage_failure_returns_502_not_bare_500(self):
|
||||
from unittest import mock
|
||||
|
||||
with mock.patch("apps.assets.storage.TosStorage") as MockStorage:
|
||||
MockStorage.return_value.upload_fileobj.side_effect = RuntimeError("TOS unreachable")
|
||||
r = self.client.post("/api/auth/me/avatar/", {"file": self._png()}, format="multipart")
|
||||
self.assertEqual(r.status_code, 502)
|
||||
self.assertIn("detail", r.data)
|
||||
|
||||
def test_upload_without_file_returns_400(self):
|
||||
r = self.client.post("/api/auth/me/avatar/", {}, format="multipart")
|
||||
self.assertEqual(r.status_code, 400)
|
||||
|
||||
|
||||
class DeviceRevokeTests(TestCase):
|
||||
"""bug(10):在用设备点「下线」提示成功但实际没下线。真因=只标记 LoginSession.revoked_at
|
||||
没动 token(单 token 体系),被下线设备旧 token 仍有效。现改为旋转 token,旧 token 立即 401。"""
|
||||
|
||||
def setUp(self):
|
||||
from rest_framework.authtoken.models import Token
|
||||
|
||||
self.user = User.objects.create_user(username="dev-user", password="strong-password")
|
||||
# 模拟登录拿到 token(被下线的「目标设备」用的就是这个)
|
||||
self.token = Token.objects.create(user=self.user)
|
||||
|
||||
def test_revoke_session_invalidates_old_token(self):
|
||||
from apps.accounts.models import LoginSession
|
||||
|
||||
session = LoginSession.objects.create(user=self.user, user_agent="OtherDevice", ip_address="1.1.1.1")
|
||||
old_key = self.token.key
|
||||
|
||||
client = APIClient()
|
||||
client.credentials(HTTP_AUTHORIZATION=f"Token {old_key}")
|
||||
r = client.post(f"/api/auth/me/sessions/{session.id}/revoke/")
|
||||
self.assertEqual(r.status_code, 200)
|
||||
# 必须真正吊销:旧 token 已失效,再用它访问受保护接口应 401
|
||||
self.assertIn("token", r.data)
|
||||
self.assertNotEqual(r.data["token"], old_key)
|
||||
|
||||
stale = APIClient()
|
||||
stale.credentials(HTTP_AUTHORIZATION=f"Token {old_key}")
|
||||
self.assertEqual(stale.get("/api/auth/me/").status_code, 401)
|
||||
|
||||
# 会话被标记下线
|
||||
session.refresh_from_db()
|
||||
self.assertIsNotNone(session.revoked_at)
|
||||
|
||||
def test_revoke_unknown_session_no_op(self):
|
||||
import uuid as _uuid
|
||||
|
||||
client = APIClient()
|
||||
client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
|
||||
r = client.post(f"/api/auth/me/sessions/{_uuid.uuid4()}/revoke/")
|
||||
self.assertEqual(r.status_code, 200)
|
||||
self.assertEqual(r.data.get("revoked"), 0)
|
||||
|
||||
|
||||
class TeamSettingsTests(TestCase):
|
||||
"""PMC#12:团队月限额持久化。设置后落库,刷新(重新 GET)仍在;成员不可改;清空回到「未设置」。"""
|
||||
|
||||
def _register(self, client, username, **extra):
|
||||
return client.post(
|
||||
"/api/auth/register/",
|
||||
{"username": username, "password": "strong-password", **extra},
|
||||
format="json",
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.owner_client = APIClient()
|
||||
r = self._register(self.owner_client, "ts-owner", team_name="TS Team", invite_code=make_create_team_code())
|
||||
self.assertEqual(r.status_code, 201)
|
||||
self.team = Team.objects.get(name="TS Team")
|
||||
self.owner_client.credentials(HTTP_AUTHORIZATION=f"Token {r.data['token']}")
|
||||
# 注册返回体里团队月限额默认未设置(null)
|
||||
self.assertIsNone(r.data["team"].get("monthly_credit_limit"))
|
||||
|
||||
def test_owner_sets_limit_persists(self):
|
||||
res = self.owner_client.patch(
|
||||
"/api/auth/team/settings/", {"monthly_credit_limit": 3000}, format="json"
|
||||
)
|
||||
self.assertEqual(res.status_code, 200, res.content)
|
||||
self.assertEqual(Decimal(res.data["monthly_credit_limit"]), Decimal("3000"))
|
||||
# 落库
|
||||
self.team.refresh_from_db()
|
||||
self.assertEqual(self.team.monthly_credit_limit, Decimal("3000"))
|
||||
# 「刷新」= 重新 GET,值仍在(PMC#12 核心)
|
||||
got = self.owner_client.get("/api/auth/team/settings/")
|
||||
self.assertEqual(Decimal(got.data["monthly_credit_limit"]), Decimal("3000"))
|
||||
|
||||
def test_unlimited_minus_one_stored_as_is(self):
|
||||
res = self.owner_client.patch(
|
||||
"/api/auth/team/settings/", {"monthly_credit_limit": -1}, format="json"
|
||||
)
|
||||
self.assertEqual(res.status_code, 200, res.content)
|
||||
self.team.refresh_from_db()
|
||||
self.assertEqual(self.team.monthly_credit_limit, Decimal("-1"))
|
||||
|
||||
def test_empty_clears_to_unset(self):
|
||||
self.owner_client.patch("/api/auth/team/settings/", {"monthly_credit_limit": 3000}, format="json")
|
||||
res = self.owner_client.patch(
|
||||
"/api/auth/team/settings/", {"monthly_credit_limit": ""}, format="json"
|
||||
)
|
||||
self.assertEqual(res.status_code, 200, res.content)
|
||||
self.team.refresh_from_db()
|
||||
self.assertIsNone(self.team.monthly_credit_limit)
|
||||
|
||||
def test_invalid_number_rejected(self):
|
||||
res = self.owner_client.patch(
|
||||
"/api/auth/team/settings/", {"monthly_credit_limit": "abc"}, format="json"
|
||||
)
|
||||
self.assertEqual(res.status_code, 400)
|
||||
|
||||
def test_member_cannot_change_limit(self):
|
||||
self.owner_client.post(
|
||||
"/api/auth/team/members/",
|
||||
{"username": "ts-member", "password": "strong-password", "role": "member"},
|
||||
format="json",
|
||||
)
|
||||
member_client = APIClient()
|
||||
login = member_client.post(
|
||||
"/api/auth/login/", {"username": "ts-member", "password": "strong-password"}, format="json"
|
||||
)
|
||||
member_client.credentials(HTTP_AUTHORIZATION=f"Token {login.data['token']}")
|
||||
# 成员可读
|
||||
self.assertEqual(member_client.get("/api/auth/team/settings/").status_code, 200)
|
||||
# 但不可改
|
||||
res = member_client.patch(
|
||||
"/api/auth/team/settings/", {"monthly_credit_limit": 9999}, format="json"
|
||||
)
|
||||
self.assertEqual(res.status_code, 403)
|
||||
self.team.refresh_from_db()
|
||||
self.assertIsNone(self.team.monthly_credit_limit)
|
||||
|
||||
@@ -15,6 +15,7 @@ from .views import (
|
||||
team_member_detail,
|
||||
team_member_password,
|
||||
team_members,
|
||||
team_settings,
|
||||
update_avatar,
|
||||
validate_invite,
|
||||
)
|
||||
@@ -32,6 +33,7 @@ urlpatterns = [
|
||||
path("me/sessions/", login_sessions, name="auth-sessions"),
|
||||
path("me/sessions/revoke-others/", revoke_other_sessions, name="auth-sessions-revoke-others"),
|
||||
path("me/sessions/<uuid:session_id>/revoke/", revoke_login_session, name="auth-session-revoke"),
|
||||
path("team/settings/", team_settings, name="team-settings"),
|
||||
path("team/members/", team_members, name="team-members"),
|
||||
path("team/members/<uuid:member_id>/", team_member_detail, name="team-member-detail"),
|
||||
path("team/members/<uuid:member_id>/password/", team_member_password, name="team-member-password"),
|
||||
|
||||
@@ -213,12 +213,24 @@ def update_avatar(request):
|
||||
user = request.user
|
||||
suffix = Path(upload.name or "").suffix.lower() or ".png"
|
||||
object_key = f"users/{user.id}/avatar/{uuid.uuid4()}{suffix}"
|
||||
# 对象存储上传是唯一会抛异常的环节(凭证/网络/桶不可达)。不捕获则裸抛 500,
|
||||
# 前端只看到「服务器错误 500」查不到真因(与全站「raise_for_status 吞 body」同类坑)。
|
||||
# 捕获后回 502 + 人话,既不掩盖问题(日志仍有栈)又让前端 toast 可读。
|
||||
try:
|
||||
storage = TosStorage()
|
||||
storage.upload_fileobj(
|
||||
fileobj=upload.file,
|
||||
object_key=object_key,
|
||||
content_type=upload.content_type or "image/png",
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 — 对象存储故障归一成可读错误,不裸 500
|
||||
import logging
|
||||
|
||||
logging.getLogger(__name__).exception("avatar upload to TOS failed: %s", exc)
|
||||
return Response(
|
||||
{"detail": "头像上传失败,请稍后重试(对象存储不可用)"},
|
||||
status=status.HTTP_502_BAD_GATEWAY,
|
||||
)
|
||||
# 桶公读,存稳定的虚拟主机式直链(全站资产同款 public_url)——不存预签名 URL:
|
||||
# 预签名 URL 带一长串 SigV4 查询参数(常 >300 字符),会超出 avatar_url 这个 URLField
|
||||
# 的默认 max_length=200,MySQL 严格模式下 save 抛 DataError(Data too long)→ 500;
|
||||
@@ -320,6 +332,32 @@ def team_members(request):
|
||||
return Response(TeamMemberSerializer(member).data, status=status.HTTP_201_CREATED)
|
||||
|
||||
|
||||
@api_view(["GET", "PATCH"])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def team_settings(request):
|
||||
"""团队级设置:目前承载「设置月限额」(团队页超管设置,刷新后持久化 · PMC#12)。
|
||||
GET 任意成员可读;PATCH 仅超管/团管(can_manage_team)。
|
||||
monthly_credit_limit 三态:null=未设置(按成员累加)· -1=不限 · >=0=固定上限。"""
|
||||
team = get_current_team(request.user)
|
||||
if request.method == "GET":
|
||||
return Response(TeamSerializer(team).data)
|
||||
|
||||
if not can_manage_team(request.user, team):
|
||||
return Response({"detail": "permission denied"}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if "monthly_credit_limit" in request.data:
|
||||
raw = request.data.get("monthly_credit_limit")
|
||||
if raw is None or (isinstance(raw, str) and not raw.strip()):
|
||||
team.monthly_credit_limit = None # 清空 = 回到「未设置(按成员累加)」
|
||||
else:
|
||||
try:
|
||||
team.monthly_credit_limit = Decimal(str(raw))
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
return Response({"monthly_credit_limit": ["invalid number"]}, status=status.HTTP_400_BAD_REQUEST)
|
||||
team.save(update_fields=["monthly_credit_limit", "updated_at"])
|
||||
return Response(TeamSerializer(team).data)
|
||||
|
||||
|
||||
@api_view(["GET", "POST"])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def team_invitations(request):
|
||||
@@ -462,7 +500,14 @@ def login_sessions(request):
|
||||
@permission_classes([IsAuthenticated])
|
||||
def revoke_login_session(request, session_id):
|
||||
"""下线单个设备:把同一台设备(UA + IP)下的所有未下线会话一并下线,
|
||||
否则去重展示的一台设备点「下线」后,底层其它重复会话仍存活会再次冒出来。"""
|
||||
否则去重展示的一台设备点「下线」后,底层其它重复会话仍存活会再次冒出来。
|
||||
|
||||
关键:DRF TokenAuthentication 是「一用户一 token」(authtoken 共享一行),
|
||||
只标记 LoginSession.revoked_at 根本不动 token —— 被下线的设备仍拿着有效 token,
|
||||
继续访问畅通无阻(bug:提示「设备已下线」但实际没下线)。单 token 体系下无法
|
||||
只吊销某一台,唯一能真正下线的做法 = 旋转 token(删旧 + 发新),令所有端旧 token
|
||||
立即失效,再把新 token 发回当前设备(同 revoke_other_sessions 的思路)。
|
||||
被下线的目标设备下次请求即 401,真正离线。"""
|
||||
from django.utils import timezone
|
||||
|
||||
target = LoginSession.objects.filter(user=request.user, id=session_id).first()
|
||||
@@ -474,7 +519,12 @@ def revoke_login_session(request, session_id):
|
||||
ip_address=target.ip_address,
|
||||
revoked_at__isnull=True,
|
||||
).update(revoked_at=timezone.now())
|
||||
return Response({"revoked": updated})
|
||||
# 真正吊销:旋转用户 token(令被下线设备旧 token 立即失效),再发新 token 给当前设备。
|
||||
Token.objects.filter(user=request.user).delete()
|
||||
token, _ = Token.objects.get_or_create(user=request.user)
|
||||
# 刷新当前设备这条会话(旋转后当前设备等价于「重新登录」),避免它被自己下线后又冒出来
|
||||
record_login_session(request, request.user)
|
||||
return Response({"revoked": updated, "token": token.key})
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
|
||||
@@ -1317,16 +1317,28 @@ def run_base_asset_task(*, task_id: str) -> None:
|
||||
BaseAssetGroup.Kind.PERSON: Asset.Category.PERSON,
|
||||
BaseAssetGroup.Kind.SCENE: Asset.Category.SCENE,
|
||||
}[kind]
|
||||
# 商品基础资产 = 商品三视图(prompt 即「生成同一件商品的三视图」):名字带「三视图」并打
|
||||
# metadata.view=three_view + product_id,让商品库的三视图查询(products is_triview / ?product 过滤)
|
||||
# 能认出并回填——否则视频项目生成的商品三视图同步不回商品库,商品库永远显示「尚未生成」(ZWQ#5)。
|
||||
is_product = kind == BaseAssetGroup.Kind.PRODUCT
|
||||
asset_name = f"{project.name}-商品三视图" if is_product else f"{project.name}-{kind}"
|
||||
asset = _store_generated_media(
|
||||
team=project.team,
|
||||
user=user,
|
||||
project=project,
|
||||
task=task,
|
||||
media=media,
|
||||
name=f"{project.name}-{kind}",
|
||||
name=asset_name,
|
||||
category=category,
|
||||
asset_type=Asset.Type.IMAGE,
|
||||
)
|
||||
if is_product:
|
||||
meta = dict(asset.metadata or {})
|
||||
meta["view"] = "three_view"
|
||||
if project.product_id:
|
||||
meta["product_id"] = str(project.product_id)
|
||||
asset.metadata = meta
|
||||
asset.save(update_fields=["metadata", "updated_at"])
|
||||
# 复用同实体的组:追加候选 + 采用最新(版本=candidate_assets,采用=adopted_asset);无则新建
|
||||
group = _find_entity_group(project, kind, label, group_id)
|
||||
if group is None:
|
||||
@@ -1423,12 +1435,15 @@ def run_triview_task(*, task_id: str) -> None:
|
||||
group.candidate_assets.add(asset)
|
||||
group.adopted_asset = asset
|
||||
group.save(update_fields=["adopted_asset", "updated_at"])
|
||||
# B 路(期3):视频流程新生成的「角色」立绘 + 三视图成套 → 自动加入模特库(团队级可复用)。
|
||||
# 幂等:同一立绘只建一次 Model;best-effort,不影响主链路。
|
||||
# B 路(期3):视频流程新生成的「角色」立绘 + 三视图成套 → 自动加入/更新模特库(团队级可复用)。
|
||||
# 幂等:同一立绘只建一次 Model;已存在该立绘的 Model(尤其「真人上传」模特,upload 时只建了 portrait、
|
||||
# 还没 triview)→ 回写 triview_asset,否则模特库永远显示「无三视图」(ZWQ#7:AI 角色能更新、真人上传不更新)。
|
||||
from apps.assets.models import Model as ModelEntity
|
||||
|
||||
portrait = Asset.objects.filter(id=asset_key).first()
|
||||
if portrait is not None and not ModelEntity.objects.filter(portrait_asset=portrait).exists():
|
||||
if portrait is not None:
|
||||
existing_model = ModelEntity.objects.filter(portrait_asset=portrait, is_deleted=False).first()
|
||||
if existing_model is None:
|
||||
ModelEntity.objects.create(
|
||||
team=project.team, created_by=user,
|
||||
name=(portrait.name or f"{project.name}-角色").split("·")[0].strip()[:255] or "角色",
|
||||
@@ -1436,6 +1451,10 @@ def run_triview_task(*, task_id: str) -> None:
|
||||
portrait_asset=portrait, triview_asset=asset,
|
||||
metadata={"from_project": str(project.id), "auto_enrolled": True},
|
||||
)
|
||||
elif existing_model.triview_asset_id != asset.id:
|
||||
# 真人上传 / 已有模特补三视图:回写新三视图(应用后模特库即刷新三视图)
|
||||
existing_model.triview_asset = asset
|
||||
existing_model.save(update_fields=["triview_asset", "updated_at"])
|
||||
# 合规(期3):三视图含人脸,视频生成前必须过火山审核 → 事务提交后静默送审(best-effort)
|
||||
from apps.assets.review import submit_asset_for_review
|
||||
|
||||
|
||||
@@ -34,10 +34,12 @@ class Asset(TeamOwnedModel):
|
||||
FREE_CREATE = "free_create", "Free Create" # 自由创作(图片趴)
|
||||
STORYBOARD = "storyboard", "Storyboard" # 分镜图(视频趴·送审)
|
||||
|
||||
# 送审范围(火山人像审核):视频趴含人脸 = 角色定妆照 / 三视图 / 分镜图 / 场景 / 商品图。
|
||||
# 送审范围(火山人像审核):视频趴含人脸 = 角色定妆照 / 模特形象图 / 三视图 / 分镜图 / 场景 / 商品图。
|
||||
# model_portrait(模特库形象图,尤其真人上传)与 person 同样是真人脸,必须可送审——否则新增模特后在
|
||||
# 基础资产点「待审核」会被判「该素材无需审核」(ZWQ#6:AI 角色 person 可审、上传模特 model_portrait 报无需审核)。
|
||||
# 场景图与商品图也可能出现真人(模特出镜/上身),不送审则视频路只能传原始直链 → 火山判「疑似真人」拒;
|
||||
# 送审后拿到 remote_id,视频路换 asset:// 素材库引用即可放行。图片趴(上身图/套图/创作)仍不送审。
|
||||
REVIEW_CATEGORIES = ("person", "tri_view", "storyboard", "scene", "product_image")
|
||||
REVIEW_CATEGORIES = ("person", "model_portrait", "tri_view", "storyboard", "scene", "product_image")
|
||||
|
||||
name = models.CharField(max_length=255)
|
||||
asset_type = models.CharField(max_length=24, choices=Type.choices)
|
||||
|
||||
@@ -182,7 +182,8 @@ class SubmitReviewTests(TestCase):
|
||||
self.client = APIClient()
|
||||
self.client.force_authenticate(self.user)
|
||||
self.person = Asset.objects.create(team=self.team, name="角色", asset_type="image", source="ai_generated", category=Asset.Category.PERSON)
|
||||
self.product = Asset.objects.create(team=self.team, name="商品图", asset_type="image", source="upload", category=Asset.Category.PRODUCT_IMAGE)
|
||||
# 图片趴(模特上身图)= 非送审类,用于校验 submit-review 对其拒绝(product_image/scene 现已属送审类)
|
||||
self.tryon = Asset.objects.create(team=self.team, name="上身图", asset_type="image", source="ai_generated", category=Asset.Category.MODEL_TRYON)
|
||||
|
||||
def test_submit_review_person_ok(self):
|
||||
with patch("apps.assets.review.submit_asset_for_review") as sub:
|
||||
@@ -192,7 +193,7 @@ class SubmitReviewTests(TestCase):
|
||||
self.assertIn("review_status", res.json())
|
||||
|
||||
def test_submit_review_rejects_non_review_category(self):
|
||||
res = self.client.post(f"/api/assets/{self.product.id}/submit-review/")
|
||||
res = self.client.post(f"/api/assets/{self.tryon.id}/submit-review/")
|
||||
self.assertEqual(res.status_code, 400)
|
||||
|
||||
def test_submit_review_503_when_submission_did_not_start(self):
|
||||
@@ -218,22 +219,26 @@ class SubmitReviewTests(TestCase):
|
||||
|
||||
|
||||
class ReviewScopeTests(TestCase):
|
||||
"""送审范围 = 角色定妆照(person)/ 三视图(tri_view)/ 分镜图(storyboard);图片趴不送审。"""
|
||||
"""送审范围 = 含人脸资产:角色定妆照(person)/ 模特形象图(model_portrait)/ 三视图(tri_view)/
|
||||
分镜图(storyboard)/ 场景(scene)/ 商品图(product_image);图片趴(上身图/套图/创作)不送审。"""
|
||||
|
||||
def test_review_categories_constant(self):
|
||||
self.assertEqual(Asset.REVIEW_CATEGORIES, ("person", "tri_view", "storyboard"))
|
||||
self.assertEqual(
|
||||
Asset.REVIEW_CATEGORIES,
|
||||
("person", "model_portrait", "tri_view", "storyboard", "scene", "product_image"),
|
||||
)
|
||||
|
||||
def test_poll_team_reviews_only_scans_review_categories(self):
|
||||
from apps.assets import review
|
||||
|
||||
_, team = _mk_team("uc", "TeamC")
|
||||
keep = {}
|
||||
for cat in ("person", "tri_view", "storyboard"):
|
||||
for cat in ("person", "model_portrait", "tri_view", "storyboard", "scene", "product_image"):
|
||||
a = Asset.objects.create(team=team, name=cat, asset_type="image", source="ai_generated",
|
||||
category=cat, review_status="processing")
|
||||
keep[cat] = str(a.id)
|
||||
# 图片趴 / 场景:不应进送审队列
|
||||
for cat in ("model_tryon", "model_portrait", "scene"):
|
||||
# 图片趴:不应进送审队列
|
||||
for cat in ("model_tryon", "platform_kit", "free_create"):
|
||||
Asset.objects.create(team=team, name=cat, asset_type="image", source="ai_generated",
|
||||
category=cat, review_status="processing")
|
||||
with patch("apps.assets.review.assets_client.is_enabled", return_value=False):
|
||||
|
||||
@@ -82,8 +82,12 @@ class ProductViewSet(TeamScopedViewSetMixin, ModelViewSet):
|
||||
def ref_count(asset):
|
||||
return BaseAssetGroup.objects.filter(Q(adopted_asset=asset) | Q(candidate_assets=asset)).values("project").distinct().count()
|
||||
|
||||
# 三视图:tri_view 类 / 老数据(metadata.view=three_view 或名字含三视图)
|
||||
# 人物三视图(给角色卡配对用):tri_view 类 / 老数据(metadata.view=three_view 或名字含三视图)。
|
||||
# 排除 product_image —— 商品三视图(ZWQ#5)也带 view=three_view,但它属商品图而非人物角色,
|
||||
# 否则会被当成孤儿角色卡误列进「角色」区(同时它已在 product_images 区正常展示)。
|
||||
def is_triview(a):
|
||||
if a.category == "product_image":
|
||||
return False
|
||||
return a.category == "tri_view" or (a.metadata or {}).get("view") == "three_view" or "三视图" in (a.name or "")
|
||||
|
||||
triviews = [a for a in assets if is_triview(a)]
|
||||
|
||||
@@ -596,9 +596,58 @@ class ProjectViewSet(TeamScopedViewSetMixin, ModelViewSet):
|
||||
from apps.assets.review import submit_asset_for_review
|
||||
|
||||
transaction.on_commit(lambda a=asset: submit_asset_for_review(a))
|
||||
# ZWQ#4 · 沿用模特库已有三视图:选了「已带三视图」的模特(官方/自有)作角色时,
|
||||
# 把该模特的三视图也挂进项目(triview_of=本组采用立绘 id),前端即判定「已有三视图」、
|
||||
# 不再要求点「AI 生成三视图」。仅对人物组生效;asset_id 传的是模特的 portrait_asset(原始 id),
|
||||
# 故按原始 portrait_asset 反查 Model;官方模特三视图同立绘一样克隆进本团队再挂(team 隔离)。
|
||||
if asset.category in (Asset.Category.PERSON, Asset.Category.MODEL_PORTRAIT):
|
||||
self._attach_existing_model_triview(project, group, asset, source_portrait_id=asset_id, user=request.user)
|
||||
promote_base_asset_stage_if_ready(project)
|
||||
return Response(BaseAssetGroupSerializer(group).data)
|
||||
|
||||
def _attach_existing_model_triview(self, project, portrait_group, portrait_asset, *, source_portrait_id, user):
|
||||
"""若被采用的立绘来自「已带三视图」的模特,把该三视图挂进项目并采用(triview_of=立绘 id)。
|
||||
幂等:已存在该立绘的三视图组就跳过,不重复挂。best-effort,出错不阻断主采用流程。"""
|
||||
from apps.assets.models import Model as ModelEntity
|
||||
|
||||
# source_portrait_id = 前端传的资产 id(模特的原始 portrait_asset);官方模特会被克隆,
|
||||
# 故 portrait_asset 可能是克隆体。两边都查一遍找到对应 Model。
|
||||
candidate_ids = {str(portrait_asset.id)}
|
||||
if source_portrait_id:
|
||||
candidate_ids.add(str(source_portrait_id))
|
||||
model = (
|
||||
ModelEntity.objects.filter(portrait_asset_id__in=candidate_ids, is_deleted=False)
|
||||
.exclude(triview_asset__isnull=True)
|
||||
.select_related("triview_asset")
|
||||
.first()
|
||||
)
|
||||
if model is None or model.triview_asset is None:
|
||||
return
|
||||
portrait_key = str(portrait_asset.id)
|
||||
# 已有该立绘的三视图组?幂等跳过。
|
||||
existing = next(
|
||||
(g for g in project.base_asset_groups.filter(kind=BaseAssetGroup.Kind.PERSON)
|
||||
if (g.metadata or {}).get("triview_of") == portrait_key),
|
||||
None,
|
||||
)
|
||||
if existing is not None:
|
||||
return
|
||||
tri_asset = model.triview_asset
|
||||
# 官方模特三视图跨团队 → 克隆进本团队再挂(与立绘同款);本团队三视图直接用。
|
||||
if tri_asset.team_id != project.team_id:
|
||||
tri_asset = _clone_asset_into_team(tri_asset, team=project.team, user=user)
|
||||
tri_group = BaseAssetGroup.objects.create(
|
||||
project=project, kind=BaseAssetGroup.Kind.PERSON, prompt="",
|
||||
metadata={"label": "·三视图", "triview_of": portrait_key, "adopt": "adopted"},
|
||||
)
|
||||
tri_group.candidate_assets.add(tri_asset)
|
||||
tri_group.adopted_asset = tri_asset
|
||||
tri_group.save(update_fields=["adopted_asset", "updated_at"])
|
||||
if tri_asset.category in Asset.REVIEW_CATEGORIES and tri_asset.review_status != "active":
|
||||
from apps.assets.review import submit_asset_for_review
|
||||
|
||||
transaction.on_commit(lambda a=tri_asset: submit_asset_for_review(a))
|
||||
|
||||
@action(detail=True, methods=["post"], url_path="generate-triview")
|
||||
def generate_triview(self, request, pk=None):
|
||||
"""流程步骤4 · 据某一版立绘资产生成它配套的三视图(image_edit 锁角色一致性,三视图绑定该立绘)。"""
|
||||
|
||||
@@ -197,7 +197,10 @@ export function App() {
|
||||
}
|
||||
|
||||
async function revokeSession(id: string) {
|
||||
await action(() => api.revokeSession(id), "设备已下线");
|
||||
// 后端旋转 token 真正吊销目标设备(单 token 体系),回传新 token 给当前设备 —— 必须存下,
|
||||
// 否则当前设备旧 token 已失效会把自己也踢下线
|
||||
const res = await action(() => api.revokeSession(id), "设备已下线");
|
||||
if (res?.token) setToken(res.token);
|
||||
setSessions(await api.loginSessions().catch(() => []));
|
||||
}
|
||||
|
||||
|
||||
@@ -649,16 +649,49 @@
|
||||
/* 胶囊在框底 → 下拉菜单向上弹,避免被框/CTA 遮住 */
|
||||
.image-workbench .iw-model-pill .chip-menu { top: auto; bottom: calc(100% + 4px); }
|
||||
|
||||
/* ── YYX#17:左侧商品栏折叠 ── */
|
||||
.image-workbench .iw-side-top .iw-side-collapse {
|
||||
margin-left: auto;
|
||||
width: 28px; height: 28px;
|
||||
display: grid; place-items: center;
|
||||
border: 1px solid var(--border-faint); border-radius: var(--r-md);
|
||||
background: var(--surface); color: var(--black-alpha-48); cursor: pointer;
|
||||
transition: background var(--t-base), color var(--t-base), border-color var(--t-base);
|
||||
/* ── YYX#17:左侧商品栏折叠 —— 复用导航栏(app-shell .sidebar-toggle)同款视觉/交互 ──
|
||||
贴商品栏右边缘的竖条按钮:平时隐形(chevron opacity 0),hover 才浮现 chevron + 浅底,
|
||||
点击切换收/展。不用原来那个带边框的方块丑按钮。 */
|
||||
.image-workbench .iw-prod-space { position: relative; }
|
||||
.image-workbench .iw-side-toggle {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
z-index: 5;
|
||||
width: 28px;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
color: var(--black-alpha-48);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
transition: color var(--t-base), background var(--t-base);
|
||||
}
|
||||
.image-workbench .iw-side-top .iw-side-collapse:hover { background: var(--heat-12); color: var(--heat); border-color: var(--heat-20); }
|
||||
.image-workbench .iw-side-toggle:hover,
|
||||
.image-workbench .iw-side-toggle:focus-visible {
|
||||
background: var(--black-alpha-4);
|
||||
backdrop-filter: blur(4px);
|
||||
-webkit-backdrop-filter: blur(4px);
|
||||
color: var(--accent-black);
|
||||
outline: none;
|
||||
}
|
||||
.image-workbench .iw-side-toggle-icon {
|
||||
display: block;
|
||||
opacity: 0;
|
||||
line-height: 1;
|
||||
transition: opacity var(--t-base);
|
||||
}
|
||||
.image-workbench .iw-side-toggle:hover .iw-side-toggle-icon,
|
||||
.image-workbench .iw-side-toggle:focus-visible .iw-side-toggle-icon { opacity: 1; }
|
||||
.image-workbench .iw-side-toggle-icon--expand { display: none; }
|
||||
.image-workbench .iw-prod-space.collapsed .iw-side-toggle-icon--collapse { display: none; }
|
||||
.image-workbench .iw-prod-space.collapsed .iw-side-toggle-icon--expand { display: block; }
|
||||
/* 展开态:列表/头部右侧给竖条让位(28px),避免竖条覆盖商品行右侧的点击区 */
|
||||
.image-workbench .iw-prod-space:not(.collapsed) .iw-side-top { padding-right: 30px; }
|
||||
.image-workbench .iw-prod-space:not(.collapsed) .iw-ps-list { padding-right: 28px; }
|
||||
/* 收起后整列变窄,只剩商品图 */
|
||||
.image-workbench .iw-layout:has(.iw-prod-space.collapsed) { grid-template-columns: 76px minmax(0, 1fr); }
|
||||
.image-workbench .iw-prod-space.collapsed .back-pill,
|
||||
@@ -666,7 +699,6 @@
|
||||
.image-workbench .iw-prod-space.collapsed .iw-list-h,
|
||||
.image-workbench .iw-prod-space.collapsed .iw-prod-item .body { display: none; }
|
||||
.image-workbench .iw-prod-space.collapsed .iw-side-top { justify-content: center; padding: 12px 0 10px; }
|
||||
.image-workbench .iw-prod-space.collapsed .iw-side-top .iw-side-collapse { margin-left: 0; }
|
||||
.image-workbench .iw-prod-space.collapsed .iw-ps-list { padding-left: 0; padding-right: 0; align-items: center; }
|
||||
.image-workbench .iw-prod-space.collapsed .iw-prod-item { justify-content: center; padding: 4px; }
|
||||
|
||||
@@ -851,16 +883,20 @@
|
||||
/* 不在此裁切:否则「更多」气泡(.gen-bubble)作为后代会被 overflow:hidden 切掉。
|
||||
改为给图片/占位各自圆角,卡片保持圆角的同时让气泡能溢出展示。 */
|
||||
cursor: pointer;
|
||||
/* YYX#13:容器自带铺满的 skeleton 占位底(网纹 + 灰底),图片加载前/加载中不留空白;
|
||||
真图(.gen-image-img)叠在其上,加载完盖住占位底。复用 .placeholder 同款网纹纹理。 */
|
||||
background:
|
||||
repeating-linear-gradient(135deg, rgba(0, 0, 0, 0.025) 0 1px, transparent 1px 12px),
|
||||
var(--black-alpha-4);
|
||||
}
|
||||
.image-workbench .gen-image .placeholder { position: absolute; inset: 0; border-radius: var(--r-md); overflow: hidden; }
|
||||
/* 生成结果真图 · 填满 .gen-image(比例由容器 aspect-ratio 控制) */
|
||||
/* 生成结果真图 · 填满 .gen-image(比例由容器 aspect-ratio 控制) · 透明背景让容器 skeleton 占位透出,加载完图片自身盖住 */
|
||||
.image-workbench .gen-image-img {
|
||||
position: absolute; inset: 0;
|
||||
width: 100%; height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
border-radius: var(--r-md);
|
||||
background: var(--black-alpha-4);
|
||||
}
|
||||
/* 右上浮层按钮组(§4.18 .gen-image-actions) */
|
||||
.image-workbench .gen-image-actions {
|
||||
|
||||
@@ -164,7 +164,8 @@ export const api = {
|
||||
return request<LoginSession[]>("/api/auth/me/sessions/");
|
||||
},
|
||||
revokeSession(id: string) {
|
||||
return request<{ revoked: number }>(`/api/auth/me/sessions/${id}/revoke/`, { method: "POST" });
|
||||
// 后端旋转 token 真正吊销被下线设备(单 token 体系),回传新 token 给当前设备保活
|
||||
return request<{ revoked: number; token?: string }>(`/api/auth/me/sessions/${id}/revoke/`, { method: "POST" });
|
||||
},
|
||||
revokeOtherSessions() {
|
||||
return request<{ token: string }>("/api/auth/me/sessions/revoke-others/", { method: "POST" });
|
||||
@@ -175,6 +176,10 @@ export const api = {
|
||||
teamMembers() {
|
||||
return request<TeamMember[]>("/api/auth/team/members/");
|
||||
},
|
||||
// 团队级月限额持久化(超管在团队页设置 · PMC#12);monthly_credit_limit: 数值 / null(清空)
|
||||
updateTeamSettings(payload: { monthly_credit_limit?: number | string | null }) {
|
||||
return request<Team>("/api/auth/team/settings/", { method: "PATCH", body: JSON.stringify(payload) });
|
||||
},
|
||||
createTeamMember(payload: {
|
||||
username: string;
|
||||
password: string;
|
||||
|
||||
@@ -128,7 +128,7 @@ export function TeamModal({ open, title, subtitle, icon, close, children, footer
|
||||
);
|
||||
}
|
||||
|
||||
export function ConfirmModal({ open, title, detail, confirmText, subtitle = "// CONFIRM", icon, onCancel, onConfirm }: {
|
||||
export function ConfirmModal({ open, title, detail, confirmText, subtitle = "// CONFIRM", icon, onCancel, onConfirm, dismissable = true }: {
|
||||
open: boolean;
|
||||
title: string;
|
||||
detail: string;
|
||||
@@ -137,13 +137,15 @@ export function ConfirmModal({ open, title, detail, confirmText, subtitle = "//
|
||||
icon?: ReactNode;
|
||||
onCancel: () => void;
|
||||
onConfirm: () => void | Promise<unknown>;
|
||||
/** 是否允许点击遮罩关闭弹窗。默认 true(保持原有行为);传 false 则点遮罩不响应。 */
|
||||
dismissable?: boolean;
|
||||
}) {
|
||||
useBodyScrollLock(open);
|
||||
const { mounted, show } = useOverlayTransition(open, onCancel);
|
||||
if (!mounted) return null;
|
||||
// 挂到 body:脱离 .content(z-index:1)层叠上下文,遮罩才能盖住头部/侧栏
|
||||
return createPortal(
|
||||
<div className={`modal-bg${show ? " show" : ""}`} onClick={onCancel}>
|
||||
<div className={`modal-bg${show ? " show" : ""}`} onClick={dismissable ? onCancel : undefined}>
|
||||
<div className="modal" onClick={(event) => event.stopPropagation()}>
|
||||
<span className="corner-tr">+</span><span className="corner-bl">+</span>
|
||||
<div className="modal-h"><div className="ic-m">{icon ?? <Shield size={16} />}</div><div className="ti">{title}<span>{subtitle}</span></div></div>
|
||||
|
||||
@@ -301,6 +301,7 @@
|
||||
font-weight: 600;
|
||||
letter-spacing: -.012em;
|
||||
color: var(--accent-black);
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
.msg-detail-title .meta {
|
||||
display: flex;
|
||||
@@ -317,6 +318,7 @@
|
||||
color: var(--accent-black);
|
||||
font-size: 14px;
|
||||
line-height: 1.75;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
.msg-props {
|
||||
display: grid;
|
||||
@@ -338,6 +340,7 @@
|
||||
min-width: 0;
|
||||
color: var(--accent-black);
|
||||
font-size: 13px;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
.msg-props .v a { color: var(--heat); }
|
||||
.msg-timeline {
|
||||
@@ -370,6 +373,7 @@
|
||||
color: var(--black-alpha-72);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.55;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
.msg-log {
|
||||
margin-top: 14px;
|
||||
|
||||
@@ -7,14 +7,14 @@ import {
|
||||
Bookmark,
|
||||
Check,
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Download,
|
||||
Grid2X2,
|
||||
ImagePlus,
|
||||
LayoutGrid,
|
||||
List,
|
||||
MoreHorizontal,
|
||||
PanelLeftClose,
|
||||
PanelLeftOpen,
|
||||
Pencil,
|
||||
Plus,
|
||||
Quote,
|
||||
@@ -1683,15 +1683,24 @@ export function ImageWorkbenchPage({
|
||||
<div className="iw-layout">
|
||||
{/* 最左 · 商品空间(YYX#17:可折叠 → 收起后只剩商品图) */}
|
||||
<aside className={`iw-prod-space${sideCollapsed ? " collapsed" : ""}`}>
|
||||
{/* YYX#17:折叠/展开左侧商品栏 —— 复用导航栏(app-shell .sidebar-toggle)同款交互:
|
||||
贴右边缘的竖条按钮,hover 才显 chevron,点击切换;收起后只剩商品图。 */}
|
||||
<button
|
||||
className="iw-side-toggle"
|
||||
type="button"
|
||||
aria-pressed={sideCollapsed}
|
||||
title={sideCollapsed ? "展开商品栏" : "收起商品栏"}
|
||||
aria-label={sideCollapsed ? "展开商品栏" : "收起商品栏"}
|
||||
onClick={() => setSideCollapsed((v) => !v)}
|
||||
>
|
||||
<span className="iw-side-toggle-icon iw-side-toggle-icon--collapse"><ChevronLeft size={18} strokeWidth={1.8} /></span>
|
||||
<span className="iw-side-toggle-icon iw-side-toggle-icon--expand"><ChevronRight size={18} strokeWidth={1.8} /></span>
|
||||
</button>
|
||||
<div className="iw-side-top">
|
||||
<button className="back-pill" type="button" onClick={onBack}>
|
||||
<ArrowLeft size={14} />
|
||||
返回
|
||||
</button>
|
||||
{/* YYX#17:折叠/展开左侧商品栏 */}
|
||||
<button className="iw-side-collapse" type="button" title={sideCollapsed ? "展开商品栏" : "收起商品栏"} aria-label={sideCollapsed ? "展开商品栏" : "收起商品栏"} onClick={() => setSideCollapsed((v) => !v)}>
|
||||
{sideCollapsed ? <PanelLeftOpen size={15} /> : <PanelLeftClose size={15} />}
|
||||
</button>
|
||||
</div>
|
||||
<div className="iw-ps-search">
|
||||
<Search size={13} />
|
||||
|
||||
@@ -787,7 +787,10 @@ export function ProductDetailPage({ product, projects, initialTab = "assets", na
|
||||
|
||||
const visibleProductImages = productImages.filter((im) => !deletedImageKeys.has(im.key));
|
||||
// 可删的图(有 ProductImage 关联)数量:只剩一张时锁住最后一张,不允许删到没图
|
||||
const deletableImageCount = visibleProductImages.filter((im) => im.imageId).length;
|
||||
// 用 productImages(真实数量)而非 visibleProductImages(乐观隐藏后数量):
|
||||
// 乐观隐藏一张不应影响其他图的 canDelete 判断,否则乐观隐藏 → deletableImageCount 减少 →
|
||||
// 其余图的 canDelete 变 false → hover 删除图标全部消失(Bug#1b 根因)。
|
||||
const deletableImageCount = productImages.filter((im) => im.imageId).length;
|
||||
|
||||
// AI 生成素材 · 服务端已按 ?product 把「该商品」的素材(metadata.product_id / origin_task→project→product /
|
||||
// ProductImage 关联)懒加载到 productAssets;这里只按可显示的图片类型过滤。
|
||||
|
||||
@@ -136,8 +136,34 @@ export function TeamPage({ team, user, billing, navigate, onCreateMember: onCrea
|
||||
// 团队充值
|
||||
const [rechargeAmt, setRechargeAmt] = useState("500");
|
||||
|
||||
// 设置月限额
|
||||
// 设置月限额:savedMonthlyLimit 持久化已保存值(-1=不限,0=未设置/跟成员累加),limitVal 为弹窗编辑中间态
|
||||
// 初值取后端团队设置(team.monthly_credit_limit:null=未设置→0),刷新后不再丢(PMC#12)
|
||||
const [savedMonthlyLimit, setSavedMonthlyLimit] = useState(
|
||||
team.monthly_credit_limit == null ? 0 : Number(team.monthly_credit_limit),
|
||||
);
|
||||
const [limitVal, setLimitVal] = useState("3000");
|
||||
const [limitBusy, setLimitBusy] = useState(false);
|
||||
// team prop 异步刷新(/me/ 回来)后同步已保存月限额
|
||||
useEffect(() => {
|
||||
setSavedMonthlyLimit(team.monthly_credit_limit == null ? 0 : Number(team.monthly_credit_limit));
|
||||
}, [team.monthly_credit_limit]);
|
||||
|
||||
// 保存团队月限额:乐观更新 + 落库;失败回滚到原值(PMC#12)
|
||||
async function saveLimit() {
|
||||
const v = limitVal.trim() === "" ? -1 : Number(limitVal);
|
||||
if (Number.isNaN(v)) return;
|
||||
const prev = savedMonthlyLimit;
|
||||
setSavedMonthlyLimit(v);
|
||||
setLimitBusy(true);
|
||||
try {
|
||||
await api.updateTeamSettings({ monthly_credit_limit: v });
|
||||
setModal("");
|
||||
} catch {
|
||||
setSavedMonthlyLimit(prev); // 落库失败回滚,避免显示假成功
|
||||
} finally {
|
||||
setLimitBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
// 分享凭据弹窗(创建成功 / 重置成功后弹):captured creds(仅展示一次)
|
||||
const [share, setShare] = useState<{ mode: "create" | "reset"; name: string; username: string; password: string } | null>(null);
|
||||
@@ -157,7 +183,9 @@ export function TeamPage({ team, user, billing, navigate, onCreateMember: onCrea
|
||||
const balance = Number(billing?.account.balance || 0);
|
||||
const used = Number(billing?.charged_total || 0);
|
||||
const teamLimit = Number(limitVal) >= 0 ? Number(limitVal) : -1;
|
||||
const limit = rows.reduce((sum, member) => sum + Math.max(0, Number(member.monthly_credit_limit || 0)), 0) || balance;
|
||||
// limit:优先用已保存的团队月限额(savedMonthlyLimit !== 0);-1 表示不限(显示余额);未设置则用成员额度累加
|
||||
const memberLimitSum = rows.reduce((sum, member) => sum + Math.max(0, Number(member.monthly_credit_limit || 0)), 0);
|
||||
const limit = savedMonthlyLimit === -1 ? balance : (savedMonthlyLimit > 0 ? savedMonthlyLimit : (memberLimitSum || balance));
|
||||
const left = Math.max(0, limit - used);
|
||||
const pct = limit > 0 ? Math.min(100, (used / limit) * 100) : 0;
|
||||
// 月限额弹窗实时剩余(按弹窗内输入值预演)
|
||||
@@ -199,7 +227,9 @@ export function TeamPage({ team, user, billing, navigate, onCreateMember: onCrea
|
||||
}
|
||||
|
||||
function openLimit() {
|
||||
setLimitVal(limit > 0 ? String(Math.round(limit)) : "3000");
|
||||
// 打开时回填已保存的团队月限额;若未设置则 fallback 成员累加值或默认 3000
|
||||
const current = savedMonthlyLimit !== 0 ? savedMonthlyLimit : (limit > 0 ? Math.round(limit) : 3000);
|
||||
setLimitVal(String(current));
|
||||
setModal("limit");
|
||||
}
|
||||
|
||||
@@ -518,7 +548,7 @@ export function TeamPage({ team, user, billing, navigate, onCreateMember: onCrea
|
||||
icon={<CircleDollarSign size={16} />}
|
||||
close={() => setModal("")}
|
||||
dismissable={false}
|
||||
footer={<button className="btn btn-primary" type="button" onClick={() => setModal("")}>保存</button>}
|
||||
footer={<button className="btn btn-primary" type="button" disabled={limitBusy} onClick={saveLimit}>{limitBusy ? "保存中…" : "保存"}</button>}
|
||||
>
|
||||
<div className="limit-modal">
|
||||
<div className="field">
|
||||
@@ -662,6 +692,7 @@ export function TeamPage({ team, user, billing, navigate, onCreateMember: onCrea
|
||||
icon={<UserPlus size={16} />}
|
||||
close={() => setEditTarget(null)}
|
||||
footer={<button className="btn btn-primary" type="button" onClick={submitEdit}>保存</button>}
|
||||
dismissable={false}
|
||||
>
|
||||
<div className="edit-member-modal">
|
||||
<div className="field">
|
||||
@@ -702,6 +733,7 @@ export function TeamPage({ team, user, billing, navigate, onCreateMember: onCrea
|
||||
icon={<KeyRound size={16} />}
|
||||
close={() => setResetTarget(null)}
|
||||
footer={<button className="btn btn-primary" type="button" onClick={submitReset}>确认重置</button>}
|
||||
dismissable={false}
|
||||
>
|
||||
<div className="reset-pwd-modal">
|
||||
<div className="reset-pwd-warn">
|
||||
@@ -726,6 +758,7 @@ export function TeamPage({ team, user, billing, navigate, onCreateMember: onCrea
|
||||
confirmText="移除"
|
||||
onCancel={() => setRemoveTarget(null)}
|
||||
onConfirm={submitRemove}
|
||||
dismissable={false}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -10,6 +10,8 @@ export type Team = {
|
||||
id: string;
|
||||
name: string;
|
||||
status: string;
|
||||
// 团队级月限额(自然月)· null=未设置(按成员累加) · "-1"=不限 · ">=0"=固定上限
|
||||
monthly_credit_limit?: string | null;
|
||||
};
|
||||
|
||||
export type TeamMember = {
|
||||
|
||||
Reference in New Issue
Block a user