From 98aa046c7e61f91d550b91ad07d31a8cbe8caed1 Mon Sep 17 00:00:00 2001 From: yml Date: Thu, 26 Nov 2026 20:28:29 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96(=E8=B4=A6=E5=8F=B7=E5=88=86?= =?UTF-8?q?=E9=85=8D):=20=E9=87=8D=E6=9E=84=E6=99=BA=E8=83=BD=E5=80=99?= =?UTF-8?q?=E9=80=89=E6=B1=A0=E4=B8=8E=E5=AE=9A=E9=87=8F=E5=8F=91=E6=94=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按生命周期、租约、预售台账、积分、宝典和皮肤能力筛选账号池;支持指定客服定量发放、手工分配撤回,并为后续自助领取复用同一发放链路。 --- tests/test_account_assign_filter.py | 145 +++- web/backend/routers/accounts.py | 394 +++++++++- web/backend/schemas.py | 31 + web/frontend/src/api/accounts.ts | 15 + web/frontend/src/api/types.ts | 38 + web/frontend/src/pages/AssignmentsPage.tsx | 859 ++++++++++++++------- 6 files changed, 1191 insertions(+), 291 deletions(-) diff --git a/tests/test_account_assign_filter.py b/tests/test_account_assign_filter.py index 6277491..4a71826 100644 --- a/tests/test_account_assign_filter.py +++ b/tests/test_account_assign_filter.py @@ -18,14 +18,22 @@ import pytest from fastapi import HTTPException from tests.support.db import get_test_engine, make_test_session -from web.backend.models import Account, User +from web.backend.models import ( + Account, + AccountCommodityState, + AccountLease, + DouyuExternalOrder, + User, +) from web.backend.routers.accounts import ( assign_account, + assignment_options, assignments_summary, batch_assign_accounts, + dispatch_assignments, list_accounts, ) -from web.backend.schemas import AccountAssign, BatchAssign +from web.backend.schemas import AccountAssign, AssignmentDispatch, BatchAssign class _Base: @@ -197,6 +205,139 @@ class TestAssignablePool(_Base): assert "有效 CK 检测" in exc_info.value.detail +class TestAssignmentPools(_Base): + def test_occupancy_filter_excludes_lease_and_collab(self): + free = self.make_account("pool-free") + leased = self.make_account("pool-leased") + collab = self.make_account("pool-collab") + self.session.add( + AccountLease( + account_id=leased.id, + holder_user_id=self.admin.id, + purpose="platform_fulfillment", + status="active", + ) + ) + self.session.add( + DouyuExternalOrder( + order_no="ASSIGN-POOL-COLLAB", + account_id=collab.id, + account_username=collab.username, + status="incomplete", + ) + ) + self.session.commit() + + assert self.names( + assign_status="unassigned", + assignable_only=True, + occupancy="free", + ) == [free.username] + assert set( + self.names( + assign_status="unassigned", + assignable_only=True, + occupancy="no_collab", + ) + ) == {free.username, leased.username} + + def test_commodity_filter_uses_fresh_eligible_capability(self): + match = self.make_account("pool-skin-match") + stale = self.make_account("pool-skin-stale") + self.session.add_all( + [ + AccountCommodityState( + account_id=match.id, + platform="douyu", + scope="elite", + commodity_id="skin-001", + commodity_name="测试皮肤", + availability="available", + account_eligibility="eligible", + offer_state="active", + valid_until=self.now + timedelta(hours=1), + ), + AccountCommodityState( + account_id=stale.id, + platform="douyu", + scope="elite", + commodity_id="skin-001", + commodity_name="测试皮肤", + availability="available", + account_eligibility="eligible", + offer_state="active", + valid_until=self.now - timedelta(hours=1), + ), + ] + ) + self.session.commit() + + assert self.names( + assign_status="unassigned", + assignable_only=True, + commodity_id="skin-001", + ) == [match.username] + + def test_dispatch_selects_requested_quantity_from_free_pool(self): + free = [self.make_account(f"dispatch-free-{index}") for index in range(3)] + leased = self.make_account("dispatch-leased") + self.session.add( + AccountLease( + account_id=leased.id, + holder_user_id=self.admin.id, + purpose="platform_fulfillment", + status="active", + ) + ) + self.session.commit() + + result = dispatch_assignments( + AssignmentDispatch( + assigned_to=self.support.id, + quantity=2, + occupancy="free", + ), + db=self.session, + current=self.admin, + ) + + assert result["count"] == 2 + assigned = [ + account + for account in free + if self.session.get(Account, account.id).assigned_to == self.support.id + ] + self.session.refresh(leased) + assert len(assigned) == 2 + assert leased.assigned_to is None + + def test_assignment_options_exposes_skin_counts(self): + account = self.make_account("options-skin") + self.session.add( + AccountCommodityState( + account_id=account.id, + platform="douyu", + scope="elite", + commodity_id="skin-options", + commodity_name="选项皮肤", + availability="available", + account_eligibility="eligible", + offer_state="active", + valid_until=self.now + timedelta(hours=1), + ) + ) + self.session.commit() + + result = assignment_options(db=self.session, current=self.admin) + + assert result["occupancy"]["free"] == 1 + skin = next( + item for item in result["skins"] if item["commodity_id"] == "skin-options" + ) + assert skin["commodity_name"] == "选项皮肤" + assert skin["account_count"] == 1 + + class TestAllMatchingAssign(_Base): def test_assigns_every_matching_unassigned(self): free = [self.make_account(f"mf-{i}") for i in range(3)] diff --git a/web/backend/routers/accounts.py b/web/backend/routers/accounts.py index 1e9567d..1bc1e63 100644 --- a/web/backend/routers/accounts.py +++ b/web/backend/routers/accounts.py @@ -13,8 +13,10 @@ from ..models import ( Account, AccountCommodityState, AccountEvent, + AccountLease, AccountSupplyProfile, AuditLog, + DouyuExternalOrder, DouyuTask, User, ) @@ -30,10 +32,16 @@ from ..schemas import ( AccountOut, AccountRemark, AccountTag, + AssignmentDispatch, BatchAssign, ) from ..services.account_binding import bind_payload -from ..services.account_capability_service import account_capability_counts +from ..services.account_capability_service import ( + ACCOUNT_ELIGIBILITY_ELIGIBLE, + OFFER_STATE_ACTIVE, + OFFER_STATE_BEFORE, + account_capability_counts, +) from ..services.account_deletion import AccountDeleteBlocked, delete_accounts from ..services.account_events_service import ( CATEGORY_OPS, @@ -60,6 +68,11 @@ from ..services.account_lifecycle import ( STATUS_MANUAL, set_manual_state, ) +from ..services.account_query_filters import ( + ACTIVE_COLLAB_STATUSES, + active_collab_order_exists, + active_lease_exists, +) from ..services.account_service import parse_and_build_accounts from ..services.account_value import ( high_value_unknown_expr, @@ -101,6 +114,17 @@ def _assignable_account_filter(): ) +def _assignment_support_target(db: Session, user_id: int) -> User: + target = db.query(User).filter(User.id == user_id).first() + if target is None: + raise HTTPException(status_code=404, detail="目标用户不存在") + if target.role != "support": + raise HTTPException(status_code=400, detail="只能分配给客服角色") + if not target.is_active: + raise HTTPException(status_code=400, detail="目标客服已停用") + return target + + def _query_str(value) -> str: """把查询参数安全地取成字符串。 @@ -154,6 +178,9 @@ def _filter_accounts_query( elite_opened: bool | None = None, esports_opened: bool | None = None, role_bind_status: str = "", + occupancy: str = "", + commodity_id: str = "", + commodity_scope: str = "elite", ): """复用列表筛选条件,供分页列表和全量批量操作保持一致。""" if _query_bool(has_cookie): @@ -205,6 +232,45 @@ def _filter_accounts_query( if role_bind: query = query.filter(Account.role_bind_status == role_bind) + occupancy_value = _query_str(occupancy) + if occupancy_value: + has_lease = active_lease_exists() + in_collab = active_collab_order_exists() + if occupancy_value == "free": + query = query.filter(~has_lease, ~in_collab) + elif occupancy_value == "no_lease": + query = query.filter(~has_lease) + elif occupancy_value == "no_collab": + query = query.filter(~in_collab) + elif occupancy_value == "leased": + query = query.filter(has_lease) + elif occupancy_value == "collab": + query = query.filter(in_collab) + + commodity_value = _query_str(commodity_id) + if commodity_value: + now = datetime.now(UTC) + commodity_filters = [ + AccountCommodityState.account_id == Account.id, + AccountCommodityState.platform == "douyu", + AccountCommodityState.commodity_id == commodity_value, + AccountCommodityState.account_eligibility + == ACCOUNT_ELIGIBILITY_ELIGIBLE, + AccountCommodityState.offer_state.in_( + (OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE) + ), + AccountCommodityState.valid_until.isnot(None), + AccountCommodityState.valid_until > now, + ] + scope_value = _query_str(commodity_scope) + if scope_value: + commodity_filters.append(AccountCommodityState.scope == scope_value) + query = query.filter( + db.query(AccountCommodityState.id) + .filter(*commodity_filters) + .exists() + ) + # 高价值套装筛选 hv = _query_str(high_value_filter) if hv: @@ -271,37 +337,45 @@ def _filter_accounts_query( return query +def _selection_query(db: Session, current: User, req: AccountBulkSelection): + """把批量操作请求还原成与账号列表完全一致的筛选查询。""" + return _filter_accounts_query( + db, + _visible_accounts_query(db, current), + current, + assigned_only=req.assigned_only, + assign_status=req.assign_status, + assigned_user_id=req.assigned_user_id, + assignable_only=req.assignable_only, + tag=req.tag, + has_cookie=req.has_cookie, + search=req.search, + account_names=req.account_names, + status=req.status, + ck_status=req.ck_status, + failure_kind=req.failure_kind, + bind_status=req.bind_status, + high_value_filter=req.high_value_filter, + min_points=req.min_points, + max_points=req.max_points, + min_gold=req.min_gold, + max_gold=req.max_gold, + elite_opened=req.elite_opened, + esports_opened=req.esports_opened, + role_bind_status=req.role_bind_status, + occupancy=req.occupancy, + commodity_id=req.commodity_id, + commodity_scope=req.commodity_scope, + ) + + def _selected_account_ids( db: Session, current: User, req: AccountBulkSelection ) -> list[int]: """解析批量操作目标:当前筛选全部或显式选择的 ID。""" if req.all_matching: rows = ( - _filter_accounts_query( - db, - _visible_accounts_query(db, current), - current, - assigned_only=req.assigned_only, - assign_status=req.assign_status, - assigned_user_id=req.assigned_user_id, - assignable_only=req.assignable_only, - tag=req.tag, - has_cookie=req.has_cookie, - search=req.search, - account_names=req.account_names, - status=req.status, - ck_status=req.ck_status, - failure_kind=req.failure_kind, - bind_status=req.bind_status, - high_value_filter=req.high_value_filter, - min_points=req.min_points, - max_points=req.max_points, - min_gold=req.min_gold, - max_gold=req.max_gold, - elite_opened=req.elite_opened, - esports_opened=req.esports_opened, - role_bind_status=req.role_bind_status, - ) + _selection_query(db, current, req) .with_entities(Account.id) .order_by(None) .all() @@ -472,6 +546,12 @@ def list_accounts( role_bind_status: str = Query( "", description="精英角色绑定状态: unknown/unbound/pending/bound" ), + occupancy: str = Query( + "", + description="占用筛选:free/no_lease/no_collab/leased/collab;空=不限", + ), + commodity_id: str = Query("", description="指定斗鱼商品/皮肤能力 ID"), + commodity_scope: str = Query("elite", description="商品能力作用域,默认 elite"), sort: str = Query( "", description="排序:username/status/bind/points/high_value/exchange/tag;空=按 id", @@ -508,6 +588,9 @@ def list_accounts( elite_opened=elite_opened, esports_opened=esports_opened, role_bind_status=role_bind_status, + occupancy=occupancy, + commodity_id=commodity_id, + commodity_scope=commodity_scope, ) total = None @@ -563,6 +646,38 @@ def list_accounts( # 而不是 `douyu_tasks` 的 JSON —— 后者是执行日志,S5 起业务事实已经在事件里了。 exchange_stats: dict[int, tuple[int, Any, str]] = {} ids = [acc.id for acc in accounts] + lease_map: dict[int, AccountLease] = {} + collab_account_ids: set[int] = set() + if ids: + priority = {"platform_fulfillment": 0, "douyu_collab": 1} + for lease in ( + db.query(AccountLease) + .filter( + AccountLease.account_id.in_(ids), + AccountLease.status == "active", + ) + .all() + ): + account_id = int(lease.account_id) + current = lease_map.get(account_id) + if current is None or priority.get( + str(lease.purpose), 9 + ) < priority.get(str(current.purpose), 9): + lease_map[account_id] = lease + collab_account_ids = { + int(account_id) + for (account_id,) in ( + db.query(DouyuExternalOrder.account_id) + .filter( + DouyuExternalOrder.account_id.in_(ids), + DouyuExternalOrder.archived_at.is_(None), + DouyuExternalOrder.status.in_(ACTIVE_COLLAB_STATUSES), + ) + .distinct() + .all() + ) + if account_id is not None + } if ids: # ① 次数 + 最近一次时间(分组聚合,走 (account_id, event_type, occurred_at) 复合索引) for account_id, count, last_at in ( @@ -656,6 +771,8 @@ def list_accounts( ck_checked_at=acc.ck_checked_at, points=acc.points, gold_balance=acc.gold_balance, + elite_opened=acc.elite_opened, + esports_opened=acc.esports_opened, exchange_count=exchange_stats.get(acc.id, (0, None, ""))[0], last_exchange_at=exchange_stats.get(acc.id, (0, None, ""))[1], last_exchange_name=exchange_stats.get(acc.id, (0, None, ""))[2], @@ -675,6 +792,13 @@ def list_accounts( ck_remaining_hours=( profile_map[acc.id].ck_remaining_hours if acc.id in profile_map else None ), + active_lease_purpose=( + str(lease_map[acc.id].purpose or "") if acc.id in lease_map else "" + ), + active_lease_expires_at=( + lease_map[acc.id].expires_at if acc.id in lease_map else None + ), + in_active_collab=acc.id in collab_account_ids, ) # 只有管理员可看完整字段(密码、邮箱等) if can_include_sensitive: @@ -715,6 +839,9 @@ def list_account_ids( elite_opened: bool | None = Query(None), esports_opened: bool | None = Query(None), role_bind_status: str = Query(""), + occupancy: str = Query(""), + commodity_id: str = Query(""), + commodity_scope: str = Query("elite"), db: Session = Depends(get_db), current: User = Depends(get_current_user), ): @@ -746,6 +873,9 @@ def list_account_ids( elite_opened=elite_opened, esports_opened=esports_opened, role_bind_status=role_bind_status, + occupancy=occupancy, + commodity_id=commodity_id, + commodity_scope=commodity_scope, ) selected_names = _parse_account_names(_query_str(account_names)) if selected_names: @@ -1195,6 +1325,121 @@ def batch_assign_accounts( } +@router.post("/assignments/dispatch") +def dispatch_assignments( + req: AssignmentDispatch, + db: Session = Depends(get_db), + current: User = Depends(require_permission("account:assign")), +): + """按候选池筛选定量分配账号。 + + 这是当前“管理员手工发送账号”的执行链路。后续客服自助领取可以复用 + 同一筛选与锁行逻辑,只把目标客服改为当前登录客服,并增加领取配额。 + """ + target = _assignment_support_target(db, req.assigned_to) + query = ( + _selection_query(db, current, req) + .filter( + Account.assigned_to.is_(None), + _assignable_account_filter(), + ) + ) + if req.strategy == "points": + query = query.order_by( + Account.points.is_(None).asc(), + Account.points.desc(), + Account.id.asc(), + ) + elif req.strategy == "fresh_ck": + query = query.order_by( + Account.ck_checked_at.is_(None).asc(), + Account.ck_checked_at.desc(), + Account.id.asc(), + ) + elif req.strategy == "oldest": + query = query.order_by(Account.id.asc()) + else: + query = query.order_by( + Account.value_tier.is_(None).asc(), + Account.value_tier.asc(), + Account.ck_checked_at.is_(None).asc(), + Account.ck_checked_at.desc(), + Account.id.asc(), + ) + + candidate_ids = [ + int(account_id) + for (account_id,) in ( + query.with_for_update(skip_locked=True) + .limit(req.quantity) + .with_entities(Account.id) + .all() + ) + ] + if not candidate_ids: + raise HTTPException(status_code=400, detail="当前候选池没有可分配账号") + + accounts = ( + db.query(Account) + .filter(Account.id.in_(candidate_ids)) + .order_by(Account.id.asc()) + .all() + ) + db.query(Account).filter(Account.id.in_(candidate_ids)).update( + {Account.assigned_to: req.assigned_to}, + synchronize_session=False, + ) + db.query(DouyuTask).filter(DouyuTask.account_id.in_(candidate_ids)).update( + {DouyuTask.account_assigned_to: req.assigned_to}, + synchronize_session=False, + ) + record_audit( + db, + current, + action="account:assign", + target=f"定向分配给 {target.username} {len(candidate_ids)} 个账号", + detail={ + "assigned_to": req.assigned_to, + "assigned_username": target.username, + "quantity": req.quantity, + "count": len(candidate_ids), + "strategy": req.strategy, + "occupancy": req.occupancy, + "commodity_id": req.commodity_id, + "mode": "manual_dispatch", + }, + ) + emit_bulk( + db, + [ + { + "account_id": account.id, + "event_type": EVENT_ASSIGNED, + "title": f"定向分配:{target.username}", + "category": CATEGORY_OPS, + "detail": { + "assigned_to": req.assigned_to, + "assigned_username": target.username, + "mode": "manual_dispatch", + }, + "source": "audit", + "actor_type": "user", + "actor_id": current.id, + } + for account in accounts + ], + ) + db.commit() + return { + "success": True, + "count": len(candidate_ids), + "assigned_to": req.assigned_to, + "assigned_username": target.username, + "account_ids": candidate_ids, + "message": f"已从候选池分配 {len(candidate_ids)} 个账号给 {target.username}", + } + + @router.get("/assignments/summary") def assignments_summary( db: Session = Depends(get_db), @@ -1240,6 +1485,103 @@ def assignments_summary( } +@router.get("/assignments/options") +def assignment_options( + db: Session = Depends(get_db), + current: User = Depends(require_permission("account:assign")), +): + """分配中心的候选池统计与可用皮肤能力。""" + del current + now = datetime.now(UTC) + base_filters = [ + Account.assigned_to.is_(None), + _assignable_account_filter(), + ] + has_lease = active_lease_exists() + in_collab = active_collab_order_exists() + + def count_with(*filters) -> int: + return int( + db.query(func.count(Account.id)) + .filter(*base_filters, *filters) + .scalar() + or 0 + ) + + occupancy = { + "assignable": count_with(), + "free": count_with(~has_lease, ~in_collab), + "no_lease": count_with(~has_lease), + "no_collab": count_with(~in_collab), + "leased": count_with(has_lease), + "collab": count_with(in_collab), + } + presets = { + "zero_points": count_with( + Account.points.isnot(None), + Account.points <= 0, + ~has_lease, + ~in_collab, + ), + "elite_points": count_with( + Account.elite_opened.is_(True), + Account.points > 0, + ~has_lease, + ~in_collab, + ), + "high_value": count_with( + or_( + suit_available_expr("bairimeng"), + suit_available_expr("mengtu"), + ), + ~has_lease, + ~in_collab, + ), + } + + skin_rows = ( + db.query( + AccountCommodityState.commodity_id, + func.max(AccountCommodityState.commodity_name).label("commodity_name"), + AccountCommodityState.scope, + func.count(func.distinct(AccountCommodityState.account_id)).label( + "account_count" + ), + ) + .join(Account, Account.id == AccountCommodityState.account_id) + .filter( + AccountCommodityState.platform == "douyu", + AccountCommodityState.account_eligibility + == ACCOUNT_ELIGIBILITY_ELIGIBLE, + AccountCommodityState.offer_state.in_( + (OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE) + ), + AccountCommodityState.valid_until.isnot(None), + AccountCommodityState.valid_until > now, + *base_filters, + ~has_lease, + ~in_collab, + ) + .group_by(AccountCommodityState.commodity_id, AccountCommodityState.scope) + .order_by(func.count(func.distinct(AccountCommodityState.account_id)).desc()) + .limit(200) + .all() + ) + return { + "occupancy": occupancy, + "presets": presets, + "skins": [ + { + "commodity_id": str(commodity_id), + "commodity_name": str(commodity_name or commodity_id), + "scope": str(scope or "elite"), + "account_count": int(account_count or 0), + } + for commodity_id, commodity_name, scope, account_count in skin_rows + ], + } + + @router.put("/{account_id}/lifecycle") def set_account_lifecycle( account_id: int, diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 9fcf6df..618075c 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -227,6 +227,12 @@ class AccountBulkSelection(BaseModel): elite_opened: bool | None = None esports_opened: bool | None = None role_bind_status: str = "" + #: 账号占用:free=无租约且不在预售台账 / no_lease / no_collab / + #: leased=有生效租约 / collab=在活动预售台账 / 空=不限制 + occupancy: str = "" + #: 指定斗鱼商品/皮肤能力;只匹配新鲜且账号级可兑换的快照 + commodity_id: str = "" + commodity_scope: str = "elite" class AccountExportRequest(AccountBulkSelection): @@ -246,6 +252,21 @@ class BatchAssign(AccountBulkSelection): assigned_to: int | None = None +class AssignmentDispatch(AccountBulkSelection): + """按当前候选池定量发放给指定客服。 + + 这是人工“发送账号”的统一入口;后续客服自助领取可以复用同一组筛选和 + 定量选择逻辑,只替换权限与目标客服来源。 + """ + + assign_status: str = "unassigned" + assignable_only: bool = True + occupancy: str = "free" + assigned_to: int = Field(..., gt=0) + quantity: int = Field(10, ge=1, le=500) + strategy: str = Field("balanced", pattern="^(balanced|points|fresh_ck|oldest)$") + + class AccountBulkTag(AccountBulkSelection): tag_value: str = "" @@ -303,6 +324,8 @@ class AccountOut(BaseModel): ck_checked_at: datetime | None = None points: int | None = None gold_balance: int | None = None + elite_opened: bool | None = None + esports_opened: bool | None = None role_bind_status: str = "unknown" role_bind_label: str = "" esports_bind_status: str = "unknown" @@ -321,6 +344,9 @@ class AccountOut(BaseModel): quality_score: int | None = None redundancy_class: str = "" ck_remaining_hours: int | None = None + active_lease_purpose: str = "" + active_lease_expires_at: datetime | None = None + in_active_collab: bool = False model_config = ConfigDict(from_attributes=True) @@ -349,6 +375,8 @@ class AccountOut(BaseModel): "ck_checked_at": _isoformat(self.ck_checked_at), "points": self.points, "gold_balance": self.gold_balance, + "elite_opened": self.elite_opened, + "esports_opened": self.esports_opened, "role_bind_status": self.role_bind_status, "role_bind_label": self.role_bind_label, "esports_bind_status": self.esports_bind_status, @@ -367,6 +395,9 @@ class AccountOut(BaseModel): "quality_score": self.quality_score, "redundancy_class": self.redundancy_class, "ck_remaining_hours": self.ck_remaining_hours, + "active_lease_purpose": self.active_lease_purpose, + "active_lease_expires_at": _isoformat(self.active_lease_expires_at), + "in_active_collab": self.in_active_collab, } diff --git a/web/frontend/src/api/accounts.ts b/web/frontend/src/api/accounts.ts index a6eca72..82eea23 100644 --- a/web/frontend/src/api/accounts.ts +++ b/web/frontend/src/api/accounts.ts @@ -8,6 +8,8 @@ import type { AccountBulkTagRequest, AccountExportRequest, AccountOverview, + AssignmentDispatchRequest, + AssignmentOptions, AssignmentsSummary, BasicSummary, BatchAssignRequest, @@ -42,6 +44,9 @@ export const accountApi = { elite_opened?: boolean; esports_opened?: boolean; role_bind_status?: string; + occupancy?: string; + commodity_id?: string; + commodity_scope?: string; sort?: 'username' | 'status' | 'bind' | 'points' | 'high_value' | 'exchange' | 'tag'; order?: 'asc' | 'desc'; }, @@ -69,6 +74,9 @@ export const accountApi = { esports_opened?: boolean; role_bind_status?: string; account_names?: string; + occupancy?: string; + commodity_id?: string; + commodity_scope?: string; }, ) => api.get< @@ -87,6 +95,13 @@ export const accountApi = { // 同一接口的选择集版本:可带筛选条件(all_matching),供「按筛选全选」分配 batchAssignSelection: (data: BatchAssignRequest) => api.post('/accounts/batch-assign', data), + dispatchAssignments: (data: AssignmentDispatchRequest) => + api.post< + MessageCountResponse & { account_ids: number[]; assigned_username: string }, + MessageCountResponse & { account_ids: number[]; assigned_username: string } + >('/accounts/assignments/dispatch', data), + assignmentOptions: () => + api.get('/accounts/assignments/options'), assignmentsSummary: () => api.get('/accounts/assignments/summary'), setRemark: (id: number, remark: string) => diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 0fe701c..658ae10 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -51,6 +51,9 @@ export interface AccountBulkSelection { elite_opened?: boolean; esports_opened?: boolean; role_bind_status?: string; + occupancy?: string; + commodity_id?: string; + commodity_scope?: string; } export interface AccountExportRequest extends AccountBulkSelection { @@ -66,6 +69,12 @@ export interface BatchAssignRequest extends AccountBulkSelection { assigned_to?: number | null; } +export interface AssignmentDispatchRequest extends AccountBulkSelection { + assigned_to: number; + quantity: number; + strategy?: 'balanced' | 'points' | 'fresh_ck' | 'oldest'; +} + export interface PaginatedResponse { items: T[]; total: number; @@ -439,6 +448,8 @@ export interface AccountItem { ck_checked_at: string | null; points: number | null; gold_balance: number | null; + elite_opened: boolean | null; + esports_opened: boolean | null; role_bind_status: BindStatus; role_bind_label: string; esports_bind_status: BindStatus; @@ -457,6 +468,9 @@ export interface AccountItem { quality_score?: number | null; redundancy_class?: string; ck_remaining_hours?: number | null; + active_lease_purpose: string; + active_lease_expires_at: string | null; + in_active_collab: boolean; } export interface AssignmentsSummary { @@ -472,6 +486,30 @@ export interface SupportUserItem { assigned_count: number; } +export interface AssignmentSkinOption { + commodity_id: string; + commodity_name: string; + scope: string; + account_count: number; +} + +export interface AssignmentOptions { + occupancy: { + assignable: number; + free: number; + no_lease: number; + no_collab: number; + leased: number; + collab: number; + }; + presets: { + zero_points: number; + elite_points: number; + high_value: number; + }; + skins: AssignmentSkinOption[]; +} + // ==================== Login Task ==================== export interface LoginTaskLogItem { diff --git a/web/frontend/src/pages/AssignmentsPage.tsx b/web/frontend/src/pages/AssignmentsPage.tsx index bf59fc1..f9b2fac 100644 --- a/web/frontend/src/pages/AssignmentsPage.tsx +++ b/web/frontend/src/pages/AssignmentsPage.tsx @@ -1,51 +1,169 @@ -import { useEffect, useState, useCallback, useRef } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { - Card, Table, Button, Select, Input, Tag, Row, Col, Statistic, - Space, Tabs, Typography, Badge, theme, Tooltip, + Badge, + Button, + Card, + Col, + Input, + InputNumber, + Popconfirm, + Row, + Segmented, + Select, + Space, + Statistic, + Table, + Tabs, + Tag, + Typography, + theme, } from 'antd'; -import { message } from '../utils/antdMessage'; import { - UserOutlined, CheckCircleOutlined, TeamOutlined, - SwapOutlined, ClearOutlined, UsergroupAddOutlined, ReloadOutlined, + CheckCircleOutlined, + ClearOutlined, + ReloadOutlined, + SearchOutlined, + SendOutlined, + SwapOutlined, + TeamOutlined, + UserOutlined, + UsergroupAddOutlined, } from '@ant-design/icons'; + import { accountApi, type AccountItem, - type SupportUserItem, + type AssignmentOptions, type AssignmentsSummary, + type SupportUserItem, } from '../api/modules'; import { getErrorMessage } from '../utils/error'; +import { message } from '../utils/antdMessage'; const { Text } = Typography; const STORAGE_KEY_SELECTED_USER = 'assignments_selected_user_id'; +type PoolPreset = 'free' | 'zero_points' | 'elite_points' | 'high_value' | 'custom'; +type AssignmentTab = 'candidate' | 'assigned'; + +const POOL_PRESETS: Array<{ value: PoolPreset; label: string }> = [ + { value: 'free', label: '空闲号' }, + { value: 'zero_points', label: '无积分' }, + { value: 'elite_points', label: '精英令 + 积分' }, + { value: 'high_value', label: '高价值皮肤' }, + { value: 'custom', label: '自定义' }, +]; + +const HIGH_VALUE_OPTIONS = [ + { value: 'both_available', label: '白日梦 + 萌兔均可换' }, + { value: 'can_bairimeng', label: '可换白日梦' }, + { value: 'can_mengtu', label: '可换萌兔' }, + { value: 'owned_bairimeng', label: '已有白日梦' }, + { value: 'owned_mengtu', label: '已有萌兔' }, + { value: 'high_value_unknown', label: '高价值待确认' }, +]; + +const SUPPLY_ROLE_LABELS: Record = { + fulfillment_protected: '履约保护', + collab_protected: '预售台账保护', + onboarding: '待首次登录', + repair: '待重登', + supply_high: '高价值供给', + supply_ordinary: '普通供给', + cold: '冷库存', + manual_hold: '人工', +}; + +function occupancyLabel(record: AccountItem): string { + if (record.active_lease_purpose === 'platform_fulfillment') return '履约中'; + if (record.active_lease_purpose === 'douyu_collab' || record.in_active_collab) { + return '预售台账中'; + } + if (record.active_lease_purpose) return '租约占用'; + return '空闲'; +} + +function highValueTags(record: AccountItem) { + const items = [ + record.high_value?.bairimeng === 'available' ? '白日梦可换' : '', + record.high_value?.bairimeng === 'owned' ? '已有白日梦' : '', + record.high_value?.mengtu === 'available' ? '萌兔可换' : '', + record.high_value?.mengtu === 'owned' ? '已有萌兔' : '', + ].filter(Boolean); + if (items.length === 0) return -; + return ( + + {items.map((item) => ( + + {item} + + ))} + + ); +} + export default function AssignmentsPage() { const { token } = theme.useToken(); const [summary, setSummary] = useState(null); + const [options, setOptions] = useState(null); const [supportUsers, setSupportUsers] = useState([]); const [selectedUser, setSelectedUser] = useState(null); const [allTags, setAllTags] = useState([]); - // 表格分页与筛选状态 + const [activeTab, setActiveTab] = useState('candidate'); + const [poolPreset, setPoolPreset] = useState('free'); + const [occupancy, setOccupancy] = useState('free'); + const [searchText, setSearchText] = useState(''); + const [filterTag, setFilterTag] = useState(); + const [commodityId, setCommodityId] = useState(); + const [highValueFilter, setHighValueFilter] = useState(); + const [eliteOpened, setEliteOpened] = useState(); + const [minPoints, setMinPoints] = useState(null); + const [maxPoints, setMaxPoints] = useState(null); + const [dispatchQuantity, setDispatchQuantity] = useState(10); + const [pagedAccounts, setPagedAccounts] = useState([]); const [totalCount, setTotalCount] = useState(0); const [tableLoading, setTableLoading] = useState(false); const [selectedRowKeys, setSelectedRowKeys] = useState([]); - const [searchText, setSearchText] = useState(''); - const [filterTag, setFilterTag] = useState(undefined); - const [activeTab, setActiveTab] = useState<'unassigned' | 'assigned'>('unassigned'); const [assigning, setAssigning] = useState(false); + const [dispatching, setDispatching] = useState(false); const [refreshing, setRefreshing] = useState(false); const summaryRequestRef = useRef(0); const pagedRequestRef = useRef(0); - const [pageSize, setPageSize] = useState(() => { - const v = localStorage.getItem('assignment_page_size'); - return v ? Number(v) || 15 : 15; - }); const [currentPage, setCurrentPage] = useState(1); + const [pageSize, setPageSize] = useState(() => { + const saved = Number(localStorage.getItem('assignment_page_size')); + return [15, 30, 50, 100].includes(saved) ? saved : 15; + }); + + const candidateFilters = useMemo( + () => ({ + assignable_only: true, + assign_status: 'unassigned', + occupancy: occupancy || undefined, + search: searchText.trim() || undefined, + tag: filterTag, + commodity_id: commodityId, + commodity_scope: commodityId ? 'elite' : undefined, + high_value_filter: highValueFilter, + elite_opened: eliteOpened, + min_points: minPoints ?? undefined, + max_points: maxPoints ?? undefined, + }), + [ + commodityId, + eliteOpened, + filterTag, + highValueFilter, + maxPoints, + minPoints, + occupancy, + searchText, + ], + ); - // 加载分配概览统计 const loadSummary = useCallback(async (silent = false) => { const requestId = ++summaryRequestRef.current; try { @@ -54,25 +172,31 @@ export default function AssignmentsPage() { setSummary(data); setSupportUsers(data.support_users); return data.support_users; - } catch (e: unknown) { - if (requestId === summaryRequestRef.current && !silent) { - message.error(getErrorMessage(e)); + } catch (error) { + if (!silent && requestId === summaryRequestRef.current) { + message.error(getErrorMessage(error)); } return []; } }, []); - // 加载标签列表 - const loadTags = useCallback(async () => { + const loadOptions = useCallback(async (silent = false) => { try { - const tags = await accountApi.listTags(); - setAllTags(tags); + const data = await accountApi.assignmentOptions(); + setOptions(data); + } catch (error) { + if (!silent) message.error(getErrorMessage(error)); + } + }, []); + + const loadTags = useCallback(async () => { + try { + setAllTags(await accountApi.listTags()); } catch { - // 忽略标签加载异常 + // 标签加载失败不阻断分配。 } }, []); - // 分页按需加载账号(服务端过滤与分页) const loadPagedAccounts = useCallback(async (silent = false) => { const requestId = ++pagedRequestRef.current; if (!silent) setTableLoading(true); @@ -80,51 +204,55 @@ export default function AssignmentsPage() { const params: Parameters[0] = { page: currentPage, page_size: pageSize, - // 分配池只收当前 Cookie 已通过新鲜 CK 检测的账号。 - assignable_only: true, - include_sensitive: false, search: searchText.trim() || undefined, - tag: filterTag || undefined, + tag: filterTag, }; - - if (activeTab === 'unassigned') { - params.assign_status = 'unassigned'; + if (activeTab === 'candidate') { + Object.assign(params, candidateFilters); } else if (selectedUser) { params.assigned_user_id = selectedUser.id; + params.assignable_only = true; } - const data = await accountApi.listPaged(params); if (requestId !== pagedRequestRef.current) return; setPagedAccounts(data.items); setTotalCount(data.total); - } catch (e: unknown) { - if (requestId === pagedRequestRef.current && !silent) { - message.error(getErrorMessage(e)); + } catch (error) { + if (!silent && requestId === pagedRequestRef.current) { + message.error(getErrorMessage(error)); } } finally { - if (requestId === pagedRequestRef.current) { - setTableLoading(false); - } + if (requestId === pagedRequestRef.current) setTableLoading(false); } - }, [activeTab, selectedUser, currentPage, pageSize, searchText, filterTag]); + }, [ + activeTab, + candidateFilters, + currentPage, + filterTag, + pageSize, + searchText, + selectedUser, + ]); - // 初始化加载 useEffect(() => { const init = async () => { - loadTags(); - const users = await loadSummary(); + const [, users] = await Promise.all([ + loadOptions(), + loadSummary(), + loadTags(), + ]); if (users.length > 0) { - const savedId = localStorage.getItem(STORAGE_KEY_SELECTED_USER); - const savedUser = savedId ? users.find((u) => u.id === Number(savedId)) : null; - setSelectedUser(savedUser || users[0]); + const savedId = Number(localStorage.getItem(STORAGE_KEY_SELECTED_USER)); + setSelectedUser( + users.find((user) => user.id === savedId) || users[0], + ); } }; - init(); - }, [loadSummary, loadTags]); + void init(); + }, [loadOptions, loadSummary, loadTags]); - // 当筛选或选中客服变化时触发分页请求 useEffect(() => { - loadPagedAccounts(); + void loadPagedAccounts(); }, [loadPagedAccounts]); useEffect(() => { @@ -133,144 +261,220 @@ export default function AssignmentsPage() { void loadSummary(true); void loadPagedAccounts(true); }; - const timer = window.setInterval(refreshVisibleData, 15000); - const handleVisibility = () => { - if (document.visibilityState === 'visible') refreshVisibleData(); - }; - document.addEventListener('visibilitychange', handleVisibility); + const timer = window.setInterval(refreshVisibleData, 15_000); + document.addEventListener('visibilitychange', refreshVisibleData); window.addEventListener('focus', refreshVisibleData); return () => { window.clearInterval(timer); - document.removeEventListener('visibilitychange', handleVisibility); + document.removeEventListener('visibilitychange', refreshVisibleData); window.removeEventListener('focus', refreshVisibleData); }; }, [loadPagedAccounts, loadSummary]); + const resetPaging = () => { + setCurrentPage(1); + setSelectedRowKeys([]); + }; + + const applyPreset = (preset: PoolPreset) => { + setPoolPreset(preset); + resetPaging(); + if (preset === 'free') { + setOccupancy('free'); + setCommodityId(undefined); + setHighValueFilter(undefined); + setEliteOpened(undefined); + setMinPoints(null); + setMaxPoints(null); + } else if (preset === 'zero_points') { + setOccupancy('free'); + setCommodityId(undefined); + setHighValueFilter(undefined); + setEliteOpened(undefined); + setMinPoints(0); + setMaxPoints(0); + } else if (preset === 'elite_points') { + setOccupancy('free'); + setCommodityId(undefined); + setHighValueFilter(undefined); + setEliteOpened(true); + setMinPoints(1); + setMaxPoints(null); + } else if (preset === 'high_value') { + setOccupancy('free'); + setCommodityId(undefined); + setHighValueFilter('both_available'); + setEliteOpened(undefined); + setMinPoints(null); + setMaxPoints(null); + } + }; + + const markCustom = () => { + setPoolPreset('custom'); + resetPaging(); + }; + const handleRefresh = async () => { setRefreshing(true); try { - await Promise.all([loadSummary(), loadPagedAccounts()]); + await Promise.all([ + loadSummary(), + loadOptions(), + loadPagedAccounts(), + ]); } finally { setRefreshing(false); } }; - // 切换客服 - const handleSelectUser = (user: SupportUserItem) => { + const refreshAfterAssignment = async () => { + await Promise.all([ + loadSummary(), + loadOptions(true), + loadPagedAccounts(), + ]); + }; + + const selectUser = (user: SupportUserItem) => { setSelectedUser(user); setSelectedRowKeys([]); setCurrentPage(1); localStorage.setItem(STORAGE_KEY_SELECTED_USER, String(user.id)); }; - // 批量分配选中账号 const handleBatchAssign = async () => { - if (selectedRowKeys.length === 0) { - message.warning('请先选择账号'); - return; - } - if (!selectedUser) { - message.warning('请先选择客服'); - return; - } + if (!selectedUser || selectedRowKeys.length === 0) return; setAssigning(true); try { await accountApi.batchAssign(selectedRowKeys, selectedUser.id); - message.success(`已将 ${selectedRowKeys.length} 个账号分配给 ${selectedUser.username}`); + message.success( + `已将 ${selectedRowKeys.length} 个账号分配给 ${selectedUser.username}`, + ); setSelectedRowKeys([]); - await loadSummary(); - await loadPagedAccounts(); - } catch (e: unknown) { - message.error(getErrorMessage(e)); + await refreshAfterAssignment(); + } catch (error) { + message.error(getErrorMessage(error)); } finally { setAssigning(false); } }; - // 批量取消分配 const handleBatchUnassign = async () => { - if (selectedRowKeys.length === 0) { - message.warning('请先选择账号'); - return; - } + if (selectedRowKeys.length === 0) return; setAssigning(true); try { await accountApi.batchAssign(selectedRowKeys, null); message.success(`已取消 ${selectedRowKeys.length} 个账号的分配`); setSelectedRowKeys([]); - await loadSummary(); - await loadPagedAccounts(); - } catch (e: unknown) { - message.error(getErrorMessage(e)); + await refreshAfterAssignment(); + } catch (error) { + message.error(getErrorMessage(error)); } finally { setAssigning(false); } }; - // 一键将当前未分配(含搜索/标签筛选)全部分配给选中客服 - const handleAssignAllUnassigned = async () => { + const handleDispatch = async () => { if (!selectedUser) { message.warning('请先选择客服'); return; } if (totalCount === 0) { - message.info('当前筛选下没有未分配的账号'); + message.warning('当前候选池没有可分配账号'); return; } - setAssigning(true); + setDispatching(true); try { - const res = await accountApi.batchAssignSelection({ + const result = await accountApi.dispatchAssignments({ + ...candidateFilters, all_matching: true, - assign_status: 'unassigned', - assignable_only: true, - tag: filterTag || undefined, - search: searchText.trim() || undefined, assigned_to: selectedUser.id, + quantity: dispatchQuantity, + strategy: 'balanced', }); - message.success(res.message || `已全部分配给 ${selectedUser.username}`); + message.success(result.message); setSelectedRowKeys([]); - await loadSummary(); - await loadPagedAccounts(); - } catch (e: unknown) { - message.error(getErrorMessage(e)); + await refreshAfterAssignment(); + } catch (error) { + message.error(getErrorMessage(error)); } finally { - setAssigning(false); + setDispatching(false); } }; - // 统计数据 + const selectedUserAssignedCount = + supportUsers.find((user) => user.id === selectedUser?.id)?.assigned_count + ?? selectedUser?.assigned_count + ?? 0; const assignedCount = summary?.assigned_count ?? 0; const unassignedCount = summary?.unassigned_count ?? 0; - const totalAccountCount = summary?.total_count ?? (assignedCount + unassignedCount); - - // 获取当前选中客服已分配总数 - const currentSelectedUserAssignedCount = - (selectedUser ? supportUsers.find((u) => u.id === selectedUser.id)?.assigned_count : 0) ?? - selectedUser?.assigned_count ?? - 0; + const totalAccountCount = summary?.total_count ?? assignedCount + unassignedCount; const columns = [ - { title: 'ID', dataIndex: 'id', width: 70 }, + { title: 'ID', dataIndex: 'id', width: 72 }, { - title: '用户名', + title: '账号', dataIndex: 'username', - render: (text: string) => {text}, + width: 190, + render: (_: string, record: AccountItem) => ( + + {record.username} + {record.tag ? {record.tag} : null} + + ), }, { - title: '标签', - dataIndex: 'tag', - width: 120, - render: (tag: string) => (tag ? {tag} : -), + title: '占用', + width: 110, + render: (_: unknown, record: AccountItem) => { + const label = occupancyLabel(record); + return ( + {label} + ); + }, }, { title: '积分 / 鱼翅', - dataIndex: 'points', - width: 140, + width: 150, render: (_: unknown, record: AccountItem) => ( - - 积分 {record.points ?? '-'} + + 积分 {record.points ?? '-'} - / 鱼翅 {record.gold_balance ?? '-'} + 鱼翅 {record.gold_balance ?? '-'} + + + ), + }, + { + title: '宝典', + width: 130, + render: (_: unknown, record: AccountItem) => ( + + + 精英令{record.elite_opened ? '已开' : '未开'} + + + 电竞{record.esports_opened ? '已开' : '未开'} + + + ), + }, + { + title: '皮肤能力', + width: 220, + render: (_: unknown, record: AccountItem) => highValueTags(record), + }, + { + title: '供给画像', + width: 130, + render: (_: unknown, record: AccountItem) => ( + + + {SUPPLY_ROLE_LABELS[record.supply_role || ''] || record.supply_role || '未生成'} + + + 质量 {record.quality_score ?? '-'} · CK {record.ck_remaining_hours ?? '-'}h ), @@ -278,7 +482,7 @@ export default function AssignmentsPage() { { title: '状态', dataIndex: 'status', - width: 110, + width: 100, render: (status: string, record: AccountItem) => ( {record.status_label || status || '-'} @@ -288,44 +492,61 @@ export default function AssignmentsPage() { ]; return ( -
-
-

分配管理

-
- {/* 统计卡片 */} - + - } /> + } /> - + } + styles={{ content: { color: token.colorSuccess } }} /> - + - - } - /> - + } + styles={{ content: { color: token.colorError } }} + /> - + + + } + /> + + + - {/* 主体区域 */} - {/* 左栏:客服列表 */} - + -
+ {supportUsers.map((user) => { - const isSelected = selectedUser?.id === user.id; + const active = selectedUser?.id === user.id; return (
handleSelectUser(user)} + onClick={() => selectUser(user)} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', - padding: '10px 14px', + padding: '9px 12px', borderRadius: 6, cursor: 'pointer', - border: `1px solid ${isSelected ? token.colorPrimary : token.colorBorderSecondary}`, - background: isSelected ? token.colorPrimaryBg : token.colorBgContainer, - transition: 'all 0.2s', - }} - onMouseEnter={(e) => { - if (!isSelected) (e.currentTarget as HTMLElement).style.borderColor = token.colorPrimary; - }} - onMouseLeave={(e) => { - if (!isSelected) (e.currentTarget as HTMLElement).style.borderColor = token.colorBorderSecondary; + border: `1px solid ${active ? token.colorPrimary : token.colorBorderSecondary}`, + background: active ? token.colorPrimaryBg : token.colorBgContainer, }} > {user.username} - - - +
); })} - {supportUsers.length === 0 && ( - + {supportUsers.length === 0 ? ( + 暂无客服用户 - )} -
+ ) : null} +
- {/* 右栏:账号表格 */} - + - {selectedUser ? ( - <> - 已选中客服: - - {selectedUser.username}(已分配 {currentSelectedUserAssignedCount} 个) - - - ) : ( - 请选择左侧客服进行操作 - )} + selectedUser ? ( + + 目标客服 + + {selectedUser.username}({selectedUserAssignedCount}) + + + ) : ( + 请选择客服 + ) + } + extra={ + + 发放数量 + setDispatchQuantity(Number(value) || 1)} + style={{ width: 86 }} + /> + void handleDispatch()} + > + + } - style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }} - styles={{ body: { flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, padding: 0 } }} + style={{ height: '100%', display: 'flex', flexDirection: 'column' }} + styles={{ body: { flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', padding: 0 } }} > - {/* 筛选栏 */}
- { - setSearchText(e.target.value); - setCurrentPage(1); - }} - style={{ width: 200 }} - size="small" - /> - { + setFilterTag(value); + markCustom(); + }} + style={{ width: 140 }} + options={allTags.map((tag) => ({ value: tag, label: tag }))} + /> + { + setCommodityId(value); + markCustom(); + }} + style={{ width: 220 }} + filterOption={(input, option) => + String(option?.label || '').toLowerCase().includes(input.toLowerCase()) + } + options={(options?.skins || []).map((skin) => ({ + value: skin.commodity_id, + label: `${skin.commodity_name} · ${skin.account_count}`, + }))} + /> + { + setEliteOpened(value); + markCustom(); + }} + style={{ width: 115 }} + options={[ + { value: true, label: '已开通' }, + { value: false, label: '未开通' }, + ]} + /> + { + setMinPoints(value === null ? null : Number(value)); + markCustom(); + }} + style={{ width: 110 }} + /> + { + setMaxPoints(value === null ? null : Number(value)); + markCustom(); + }} + style={{ width: 110 }} + /> + +
- {/* Tab 切换 */} { - setActiveTab(key as 'unassigned' | 'assigned'); - setSelectedRowKeys([]); - setCurrentPage(1); + setActiveTab(key as AssignmentTab); + resetPaging(); }} - style={{ padding: '0 16px', flexShrink: 0, marginBottom: 0 }} + style={{ padding: '0 14px', flexShrink: 0, marginBottom: 0 }} items={[ { - key: 'unassigned', - label: `未分配 (${unassignedCount})`, + key: 'candidate', + label: `候选池 (${activeTab === 'candidate' ? totalCount : options?.occupancy.assignable ?? 0})`, }, { key: 'assigned', label: selectedUser - ? `已分配给 ${selectedUser.username} (${currentSelectedUserAssignedCount})` + ? `${selectedUser.username} 名下 (${selectedUserAssignedCount})` : '已分配账号', disabled: !selectedUser, }, ]} /> - {/* 操作按钮 */} -
- - {activeTab === 'unassigned' && selectedUser && ( - <> - - - - )} - {activeTab === 'assigned' && selectedUser && ( +
+ + {activeTab === 'candidate' && selectedUser ? ( + + ) : null} + {activeTab === 'assigned' && selectedUser ? ( - )} + ) : null} + + 当前筛选共 {totalCount} 个 · 已选 {selectedRowKeys.length} 个 +
- {/* 表格 */} setSelectedRowKeys(keys.map(Number)), + }} pagination={{ current: currentPage, pageSize, total: totalCount, size: 'small', showSizeChanger: true, - showTotal: (t) => `共 ${t} 条`, + showTotal: (count) => `共 ${count} 条`, onChange: (page, size) => { - setCurrentPage(page); + setCurrentPage(size === pageSize ? page : 1); if (size !== pageSize) { setPageSize(size); localStorage.setItem('assignment_page_size', String(size)); - setCurrentPage(1); } }, }} - rowSelection={{ - selectedRowKeys, - onChange: (keys) => setSelectedRowKeys(keys as number[]), - }} - scroll={{ y: 'calc(100vh - 460px)' }} + scroll={{ x: 1180, y: 'calc(100vh - 475px)' }} + locale={{ emptyText: '当前候选池没有账号' }} />