From c51dec8a941beaed33f69672209d61b5888548e9 Mon Sep 17 00:00:00 2001 From: yml Date: Sat, 28 Nov 2026 22:22:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(fulfillment):=20=E5=B1=95=E7=A4=BA?= =?UTF-8?q?=E5=8F=AF=E5=88=86=E9=85=8D=E8=B4=A6=E5=8F=B7=E5=BA=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- pyproject.toml | 2 +- tests/test_platform_fulfillment.py | 144 ++++++++++ uv.lock | 2 +- web/backend/routers/platform_fulfillment.py | 11 + .../platform_fulfillment/availability.py | 260 ++++++++++++++++++ .../services/platform_fulfillment/service.py | 2 + web/frontend/src/api/platformFulfillment.ts | 8 + web/frontend/src/api/types.ts | 15 + .../src/pages/PlatformFulfillmentPage.tsx | 124 +++++++-- 10 files changed, 550 insertions(+), 20 deletions(-) create mode 100644 web/backend/services/platform_fulfillment/availability.py diff --git a/README.md b/README.md index 43da039..8e7f4bd 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 直播账号运营后台 -斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.16)。 +斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.17)。 ## 能做什么 diff --git a/pyproject.toml b/pyproject.toml index 1b12923..9a24cbc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "live-hub-py" -version = "0.4.16" +version = "0.4.17" description = "直播账号运营 Web 后台" readme = "README.md" requires-python = ">=3.12,<3.13" diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 9898e8e..e597831 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -188,6 +188,150 @@ class _Base: return row +class TestAccountAvailability(_Base): + COMMODITIES = ( + "bundle-commodity-a", + "bundle-commodity-b", + "bundle-commodity-c", + ) + + def setup_method(self): + super().setup_method() + setting = self.session.get(PlatformFulfillmentSetting, 1) + setting.allocation_policy_json = { + "sameRoleReuseEnabled": True, + "preserveBundlePool": True, + "bundleRules": [ + { + "id": "availability-bundle", + "name": "三商品全资格", + "enabled": True, + "mode": "prefer_all", + "commodityIds": list(self.COMMODITIES), + } + ], + } + self.session.commit() + + def commodity_account( + self, + name: str, + commodity_ids: tuple[str, ...], + *, + role_available_at: datetime | None = None, + ) -> Account: + account = Account( + username=name, + password="p", + email=f"{name}@example.com", + email_password="ep", + status="active", + ck_check_status="valid", + cookie="PHPSESSID=x", + elite_opened=True, + points=3000, + auto_managed=True, + role_change_available_at=role_available_at, + ) + self.session.add(account) + self.session.flush() + for commodity_id in commodity_ids: + self.session.add( + AccountCommodityState( + account_id=account.id, + platform="douyu", + scope="elite", + commodity_id=commodity_id, + commodity_name=commodity_id, + account_eligibility="eligible", + offer_state="active", + stock_state="in_stock", + availability="available", + observed_at=NOW, + valid_until=NOW + timedelta(hours=6), + source="test_fixture", + ) + ) + self.session.commit() + return account + + def test_counts_allocatable_bundle_and_unique_accounts(self): + self.commodity_account("availability-full", self.COMMODITIES) + leased = self.commodity_account("availability-leased", self.COMMODITIES) + self.commodity_account( + "availability-role-cooldown", + self.COMMODITIES, + role_available_at=NOW + timedelta(days=1), + ) + self.commodity_account( + "availability-single", + (self.COMMODITIES[0],), + ) + exchanged = self.commodity_account( + "availability-exchanged", + (self.COMMODITIES[0],), + ) + self.session.add( + AccountLease( + account_id=leased.id, + holder_user_id=self.admin_id, + purpose="platform_fulfillment", + status="active", + ) + ) + self.session.add( + AccountEvent( + account_id=exchanged.id, + event_type="exchange", + category="business", + occurred_at=NOW - timedelta(days=10), + subject_type="commodity", + subject_key=self.COMMODITIES[0], + source="test_fixture", + ) + ) + self.session.commit() + + result = service.get_account_availability( + self.session, + commodity_ids=list(self.COMMODITIES), + now=NOW, + ) + + assert result["uniqueAllocatable"] == 2 + for commodity_id in self.COMMODITIES: + item = result["items"][commodity_id] + assert item["bundleCommodityCount"] == 3 + assert item["fullBundleAllocatable"] == 1 + assert item["roleCooldown"] == 1 + assert item["leased"] == 1 + + assert result["items"][self.COMMODITIES[0]]["allocatable"] == 2 + assert result["items"][self.COMMODITIES[1]]["allocatable"] == 1 + assert result["items"][self.COMMODITIES[2]]["allocatable"] == 1 + + def test_availability_permission_excludes_support(self): + checker = require_permission("platform_fulfillment:admin") + support = User( + username="availability-support", + password_hash="h", + role="support", + is_active=True, + ) + operator = User( + username="availability-operator", + password_hash="h", + role="operation", + is_active=True, + ) + + with pytest.raises(HTTPException) as exc_info: + checker(current_user=support) + + assert exc_info.value.status_code == 403 + assert checker(current_user=operator) is operator + + class TestWorkbenchReadPath(_Base): def mapped_task(self, mapping: PlatformCommodityMapping, index: int): task = self.task(mapped=False) diff --git a/uv.lock b/uv.lock index f8bf051..35b0c78 100644 --- a/uv.lock +++ b/uv.lock @@ -381,7 +381,7 @@ wheels = [ [[package]] name = "live-hub-py" -version = "0.4.16" +version = "0.4.17" source = { editable = "." } dependencies = [ { name = "alembic" }, diff --git a/web/backend/routers/platform_fulfillment.py b/web/backend/routers/platform_fulfillment.py index a282b66..5ad8ed6 100644 --- a/web/backend/routers/platform_fulfillment.py +++ b/web/backend/routers/platform_fulfillment.py @@ -141,6 +141,17 @@ def list_tasks( ) +@router.get("/account-availability") +def get_account_availability( + commodity_ids: str = Query("", max_length=8192), + db: Session = Depends(get_db), + current: User = Depends(require_permission("platform_fulfillment:admin")), +) -> dict[str, Any]: + del current + ids = [item.strip() for item in commodity_ids.split(",") if item.strip()] + return service.get_account_availability(db, commodity_ids=ids) + + @router.post("/sync") def sync_tasks( limit: int = Query(100, ge=1, le=500), diff --git a/web/backend/services/platform_fulfillment/availability.py b/web/backend/services/platform_fulfillment/availability.py new file mode 100644 index 0000000..e7165a4 --- /dev/null +++ b/web/backend/services/platform_fulfillment/availability.py @@ -0,0 +1,260 @@ +"""直播账号履约:按商品统计当前可分配账号库存。""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from typing import Any + +from sqlalchemy import and_, case, func, or_, select +from sqlalchemy.orm import Session + +from ...models import Account, AccountCommodityState, AccountEvent +from ..account_query_filters import ( + active_collab_order_exists, + active_lease_exists, + assigned_to_pool_filter, + automatable_account_filter, + cookie_present_filter, + fresh_eligible_state_filter, + role_change_ready_filter, + valid_ck_filter, +) +from .account_selector import ( + EXCHANGE_COOLDOWN_DAYS, + _co_commodity_eligible_exists, +) +from .common import SCOPE_ELITE, TARGET_PLATFORM, _jsonable, _now +from .policy import bundle_requirements_for_commodity, normalize_allocation_policy +from .runtime import get_settings + + +def _clean_commodity_ids(values: list[str] | tuple[str, ...]) -> tuple[str, ...]: + cleaned: list[str] = [] + for value in values: + commodity_id = str(value or "").strip()[:64] + if commodity_id and commodity_id not in cleaned: + cleaned.append(commodity_id) + return tuple(cleaned[:100]) + + +def _allocatable_pool_filter(now: datetime): + return and_( + cookie_present_filter(), + valid_ck_filter(), + automatable_account_filter(), + assigned_to_pool_filter(), + role_change_ready_filter(now), + ~active_lease_exists(), + ~active_collab_order_exists(), + ) + + +def _recent_exchange_exists( + *, + since: datetime, + commodity_ids: tuple[str, ...], +): + return ( + select(AccountEvent.id) + .where( + AccountEvent.account_id == Account.id, + AccountEvent.event_type == "exchange", + AccountEvent.subject_key.in_(commodity_ids), + AccountEvent.occurred_at >= since, + ) + .exists() + ) + + +def _recent_exchange_for_joined_state_exists(*, since: datetime): + return ( + select(AccountEvent.id) + .where( + AccountEvent.account_id == Account.id, + AccountEvent.event_type == "exchange", + AccountEvent.subject_key == AccountCommodityState.commodity_id, + AccountEvent.occurred_at >= since, + ) + .exists() + ) + + +def _bundle_group( + policy: dict[str, Any], + commodity_id: str, +) -> tuple[str, ...]: + required, preferred = bundle_requirements_for_commodity(policy, commodity_id) + return tuple(dict.fromkeys((commodity_id, *required, *preferred))) + + +def _full_bundle_allocatable_count( + db: Session, + *, + group: tuple[str, ...], + scope: str, + now: datetime, +) -> int: + commodity_id = group[0] + since = now - timedelta(days=EXCHANGE_COOLDOWN_DAYS) + query = ( + db.query(func.count(func.distinct(Account.id))) + .join( + AccountCommodityState, + AccountCommodityState.account_id == Account.id, + ) + .filter( + AccountCommodityState.platform == TARGET_PLATFORM, + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id == commodity_id, + fresh_eligible_state_filter(now, allow_before_open=True), + or_( + AccountCommodityState.last_exchange_at.is_(None), + AccountCommodityState.last_exchange_at < since, + ), + _allocatable_pool_filter(now), + ~_recent_exchange_exists(since=since, commodity_ids=group), + ) + ) + for peer_id in group[1:]: + query = query.filter( + _co_commodity_eligible_exists( + peer_id, + scope=scope, + moment=now, + since=since, + ) + ) + return int(query.scalar() or 0) + + +def get_account_availability( + db: Session, + *, + commodity_ids: list[str] | tuple[str, ...], + scope: str = SCOPE_ELITE, + now: datetime | None = None, +) -> dict[str, Any]: + """返回当前页商品的可分配库存,并按账号去重汇总。""" + ids = _clean_commodity_ids(commodity_ids) + moment = now or _now() + if not ids: + return { + "items": {}, + "uniqueAllocatable": 0, + "updatedAt": _jsonable(moment), + } + + since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS) + allocatable_filter = _allocatable_pool_filter(moment) + rows = ( + db.query( + AccountCommodityState.commodity_id.label("commodity_id"), + func.count(func.distinct(Account.id)).label("eligible"), + func.count( + func.distinct( + case((role_change_ready_filter(moment), Account.id)) + ) + ).label("role_ready"), + func.count( + func.distinct( + case((active_lease_exists(), Account.id)) + ) + ).label("leased"), + func.count( + func.distinct( + case((active_collab_order_exists(), Account.id)) + ) + ).label("active_collab"), + func.count( + func.distinct( + case( + ( + and_( + allocatable_filter, + ~_recent_exchange_for_joined_state_exists( + since=since + ), + ), + Account.id, + ) + ) + ) + ).label("allocatable"), + ) + .join(Account, Account.id == AccountCommodityState.account_id) + .filter( + AccountCommodityState.platform == TARGET_PLATFORM, + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id.in_(ids), + fresh_eligible_state_filter(moment, allow_before_open=True), + or_( + AccountCommodityState.last_exchange_at.is_(None), + AccountCommodityState.last_exchange_at < since, + ), + ) + .group_by(AccountCommodityState.commodity_id) + .all() + ) + counts = {str(row.commodity_id): row for row in rows} + + policy = normalize_allocation_policy(get_settings(db).get("allocationPolicy")) + bundle_groups: dict[str, tuple[str, ...]] = {} + bundle_counts: dict[tuple[str, ...], int] = {} + for commodity_id in ids: + group = _bundle_group(policy, commodity_id) + bundle_groups[commodity_id] = group + if len(group) > 1 and group not in bundle_counts: + bundle_counts[group] = _full_bundle_allocatable_count( + db, + group=group, + scope=scope, + now=moment, + ) + + items: dict[str, dict[str, int]] = {} + for commodity_id in ids: + row = counts.get(commodity_id) + eligible = int(getattr(row, "eligible", 0) or 0) + role_ready = int(getattr(row, "role_ready", 0) or 0) + allocatable = int(getattr(row, "allocatable", 0) or 0) + group = bundle_groups[commodity_id] + items[commodity_id] = { + "allocatable": allocatable, + "fullBundleAllocatable": ( + bundle_counts.get(group, 0) if len(group) > 1 else allocatable + ), + "bundleCommodityCount": len(group), + "roleCooldown": max(0, eligible - role_ready), + "leased": int(getattr(row, "leased", 0) or 0), + "activeCollab": int(getattr(row, "active_collab", 0) or 0), + } + + unique_allocatable = int( + db.query(func.count(func.distinct(Account.id))) + .join( + AccountCommodityState, + AccountCommodityState.account_id == Account.id, + ) + .filter( + AccountCommodityState.platform == TARGET_PLATFORM, + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id.in_(ids), + fresh_eligible_state_filter(moment, allow_before_open=True), + or_( + AccountCommodityState.last_exchange_at.is_(None), + AccountCommodityState.last_exchange_at < since, + ), + allocatable_filter, + ~_recent_exchange_exists(since=since, commodity_ids=ids), + ) + .scalar() + or 0 + ) + return { + "items": items, + "uniqueAllocatable": unique_allocatable, + "updatedAt": _jsonable(moment), + } + + +__all__ = ["get_account_availability"] diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index 7bac055..bff9728 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -26,6 +26,7 @@ from .allocation import ( # noqa: F401 allocate_task, prepare_manual_allocation, ) +from .availability import get_account_availability from .binding import ( # noqa: F401 confirm_binding, confirm_binding_sync, @@ -156,6 +157,7 @@ __all__ = [ "customer_start_binding", "delete_mapping", "ensure_customer_session", + "get_account_availability", "get_settings", "get_task_detail", "list_mappings", diff --git a/web/frontend/src/api/platformFulfillment.ts b/web/frontend/src/api/platformFulfillment.ts index eace26c..d40f0af 100644 --- a/web/frontend/src/api/platformFulfillment.ts +++ b/web/frontend/src/api/platformFulfillment.ts @@ -2,6 +2,7 @@ import api from './client'; import type { PlatformFulfillmentAllocationPolicy, PlatformFulfillmentAllocationResult, + PlatformFulfillmentAccountAvailability, PlatformFulfillmentDetail, PlatformFulfillmentCollabSyncResult, PlatformFulfillmentListResponse, @@ -65,6 +66,13 @@ export const platformFulfillmentApi = { '/platform-fulfillment/tasks', { params }, ), + getAccountAvailability: (commodityIds: string[]) => + api.get< + PlatformFulfillmentAccountAvailability, + PlatformFulfillmentAccountAvailability + >('/platform-fulfillment/account-availability', { + params: { commodity_ids: commodityIds.join(',') }, + }), sync: (limit = 100) => api.post<{ fetched: number; created: number; updated: number }, { fetched: number; created: number; updated: number }>( '/platform-fulfillment/sync', diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 601977d..2c5c0b8 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -2580,6 +2580,21 @@ export interface PlatformFulfillmentAllocationPolicy { bundleRules: PlatformFulfillmentBundleRule[]; } +export interface PlatformFulfillmentCommodityAvailability { + allocatable: number; + fullBundleAllocatable: number; + bundleCommodityCount: number; + roleCooldown: number; + leased: number; + activeCollab: number; +} + +export interface PlatformFulfillmentAccountAvailability { + items: Record; + uniqueAllocatable: number; + updatedAt: string | null; +} + export interface PlatformFulfillmentSettings { leaseDurationMinutes: number | null; completedReleaseDelayMinutes: number | null; diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index 5d2fac0..c6d4bc1 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -6,7 +6,7 @@ import { Alert, Button, Card, Col, DatePicker, Descriptions, Drawer, Empty, Imag import { ArrowDownOutlined, ArrowUpOutlined, CheckCircleOutlined, CopyOutlined, CreditCardOutlined, DeleteOutlined, DownloadOutlined, GiftOutlined, LinkOutlined, PlusOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons'; import type { ColumnsType } from 'antd/es/table'; import { douyuApi, platformFulfillmentApi } from '../api/modules'; -import type { DouyuGoodsItem, DouyuTaskItem, PlatformFulfillmentBindingLog, PlatformFulfillmentBundleRule, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules'; +import type { DouyuGoodsItem, DouyuTaskItem, PlatformFulfillmentAccountAvailability, PlatformFulfillmentBindingLog, PlatformFulfillmentBundleRule, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules'; import ExchangeResultImage from '../components/ExchangeResultImage'; import { copyImageToClipboard, fetchExchangeImageBlob, getExchangeImage, isExchangeTask } from '../utils/exchangeImage'; import { TASK_STATUS_COLORS, TASK_STATUS_LABELS, taskQrUrl } from './douyu-tasks/config'; @@ -584,6 +584,8 @@ export default function PlatformFulfillmentPage() { const [pageSize, setPageSize] = useState(20); const [rows, setRows] = useState([]); const [total, setTotal] = useState(0); + const [accountAvailability, setAccountAvailability] = useState(null); + const [accountAvailabilityLoading, setAccountAvailabilityLoading] = useState(false); const [loading, setLoading] = useState(false); const [syncing, setSyncing] = useState(false); const [collabSyncing, setCollabSyncing] = useState(false); @@ -681,12 +683,38 @@ export default function PlatformFulfillmentPage() { }); setRows(result.items); setTotal(result.pagination.total); + if (!can('platform_fulfillment:admin')) { + setAccountAvailability(null); + setAccountAvailabilityLoading(false); + } else { + const commodityIds = Array.from( + new Set(result.items.map((task) => task.commodityId.trim()).filter(Boolean)), + ); + if (commodityIds.length === 0) { + setAccountAvailability({ + items: {}, + uniqueAllocatable: 0, + updatedAt: new Date().toISOString(), + }); + setAccountAvailabilityLoading(false); + } else { + setAccountAvailabilityLoading(true); + try { + const availability = await platformFulfillmentApi.getAccountAvailability(commodityIds); + setAccountAvailability(availability); + } catch (error) { + if (!silent) message.error(getErrorMessage(error)); + } finally { + setAccountAvailabilityLoading(false); + } + } + } } catch (error) { if (!silent) message.error(getErrorMessage(error)); } finally { if (!silent) setLoading(false); } - }, [keyword, page, pageSize, queueBucket, saleModeTab]); + }, [can, keyword, page, pageSize, queueBucket, saleModeTab]); const loadDetail = useCallback(async (taskId: number, silent = false) => { if (!silent) setDetailLoading(true); @@ -1606,23 +1634,53 @@ export default function PlatformFulfillmentPage() { title: '账号', key: 'account', width: 190, - render: (_, task) => - task.account ? ( - - {task.account.nickname || task.account.username} - - 积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'} - - - 租约 {task.lease ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'} - - {task.sharedLeaseTaskIds?.length ? ( - 同角色共享 #{task.sharedLeaseTaskIds.join(', #')} + render: (_, task) => { + if (task.account) { + return ( + + {task.account.nickname || task.account.username} + + 积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'} + + + 租约 {task.lease ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'} + + {task.sharedLeaseTaskIds?.length ? ( + 同角色共享 #{task.sharedLeaseTaskIds.join(', #')} + ) : null} + + ); + } + const availability = accountAvailability?.items[task.commodityId]; + const canViewAvailability = can('platform_fulfillment:admin'); + return ( + + 未分配 + {canViewAvailability && availability ? ( + <> + + 0 ? 'green' : 'red'}> + 可用账号 {availability.allocatable} + + {availability.bundleCommodityCount > 1 ? ( + 0 ? 'cyan' : 'orange'}> + 全资格 {availability.fullBundleAllocatable} + + ) : null} + + {availability.roleCooldown > 0 || + availability.leased > 0 || + availability.activeCollab > 0 ? ( + + 占用:冷却 {availability.roleCooldown} · 租约 {availability.leased} · 台账{' '} + {availability.activeCollab} + + ) : null} + ) : null} - ) : ( - 未分配 - ), + ); + }, }, { title: '用户角色绑定', @@ -1978,6 +2036,21 @@ export default function PlatformFulfillmentPage() { ) : null; + const pendingAllocationCount = rows.filter( + (task) => + !task.account && + task.commodityId && + !['completed', 'cancelled'].includes(task.executionStatus), + ).length; + const availabilityTagColor = + accountAvailability == null + ? 'default' + : accountAvailability.uniqueAllocatable >= pendingAllocationCount + ? 'green' + : accountAvailability.uniqueAllocatable > 0 + ? 'orange' + : 'red'; + return ( @@ -1989,6 +2062,23 @@ export default function PlatformFulfillmentPage() { 系统自动检测账号并选号;只有缺货、CK 异常或资格失败时转人工处理。客户扫码绑定后,运营可直接开通宝典、充值或兑换皮肤。 + {can('platform_fulfillment:admin') ? ( + + 当前页待分配 {pendingAllocationCount} · 可分配库存{' '} + {accountAvailability + ? accountAvailability.uniqueAllocatable + : accountAvailabilityLoading + ? '计算中' + : '-'} + + ) : null} 进行中租约:{leaseDurationLabel(settings?.leaseDurationMinutes)} 订单起算:{settings?.orderMatchStartedAt ? formatTime(settings.orderMatchStartedAt) : '-'}