feat(fulfillment): 展示可分配账号库存
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
# 直播账号运营后台
|
# 直播账号运营后台
|
||||||
|
|
||||||
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.16)。
|
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.17)。
|
||||||
|
|
||||||
## 能做什么
|
## 能做什么
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "live-hub-py"
|
name = "live-hub-py"
|
||||||
version = "0.4.16"
|
version = "0.4.17"
|
||||||
description = "直播账号运营 Web 后台"
|
description = "直播账号运营 Web 后台"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.12,<3.13"
|
requires-python = ">=3.12,<3.13"
|
||||||
|
|||||||
@@ -188,6 +188,150 @@ class _Base:
|
|||||||
return row
|
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):
|
class TestWorkbenchReadPath(_Base):
|
||||||
def mapped_task(self, mapping: PlatformCommodityMapping, index: int):
|
def mapped_task(self, mapping: PlatformCommodityMapping, index: int):
|
||||||
task = self.task(mapped=False)
|
task = self.task(mapped=False)
|
||||||
|
|||||||
@@ -381,7 +381,7 @@ wheels = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "live-hub-py"
|
name = "live-hub-py"
|
||||||
version = "0.4.16"
|
version = "0.4.17"
|
||||||
source = { editable = "." }
|
source = { editable = "." }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "alembic" },
|
{ name = "alembic" },
|
||||||
|
|||||||
@@ -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")
|
@router.post("/sync")
|
||||||
def sync_tasks(
|
def sync_tasks(
|
||||||
limit: int = Query(100, ge=1, le=500),
|
limit: int = Query(100, ge=1, le=500),
|
||||||
|
|||||||
@@ -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"]
|
||||||
@@ -26,6 +26,7 @@ from .allocation import ( # noqa: F401
|
|||||||
allocate_task,
|
allocate_task,
|
||||||
prepare_manual_allocation,
|
prepare_manual_allocation,
|
||||||
)
|
)
|
||||||
|
from .availability import get_account_availability
|
||||||
from .binding import ( # noqa: F401
|
from .binding import ( # noqa: F401
|
||||||
confirm_binding,
|
confirm_binding,
|
||||||
confirm_binding_sync,
|
confirm_binding_sync,
|
||||||
@@ -156,6 +157,7 @@ __all__ = [
|
|||||||
"customer_start_binding",
|
"customer_start_binding",
|
||||||
"delete_mapping",
|
"delete_mapping",
|
||||||
"ensure_customer_session",
|
"ensure_customer_session",
|
||||||
|
"get_account_availability",
|
||||||
"get_settings",
|
"get_settings",
|
||||||
"get_task_detail",
|
"get_task_detail",
|
||||||
"list_mappings",
|
"list_mappings",
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import api from './client';
|
|||||||
import type {
|
import type {
|
||||||
PlatformFulfillmentAllocationPolicy,
|
PlatformFulfillmentAllocationPolicy,
|
||||||
PlatformFulfillmentAllocationResult,
|
PlatformFulfillmentAllocationResult,
|
||||||
|
PlatformFulfillmentAccountAvailability,
|
||||||
PlatformFulfillmentDetail,
|
PlatformFulfillmentDetail,
|
||||||
PlatformFulfillmentCollabSyncResult,
|
PlatformFulfillmentCollabSyncResult,
|
||||||
PlatformFulfillmentListResponse,
|
PlatformFulfillmentListResponse,
|
||||||
@@ -65,6 +66,13 @@ export const platformFulfillmentApi = {
|
|||||||
'/platform-fulfillment/tasks',
|
'/platform-fulfillment/tasks',
|
||||||
{ params },
|
{ params },
|
||||||
),
|
),
|
||||||
|
getAccountAvailability: (commodityIds: string[]) =>
|
||||||
|
api.get<
|
||||||
|
PlatformFulfillmentAccountAvailability,
|
||||||
|
PlatformFulfillmentAccountAvailability
|
||||||
|
>('/platform-fulfillment/account-availability', {
|
||||||
|
params: { commodity_ids: commodityIds.join(',') },
|
||||||
|
}),
|
||||||
sync: (limit = 100) =>
|
sync: (limit = 100) =>
|
||||||
api.post<{ fetched: number; created: number; updated: number }, { fetched: number; created: number; updated: number }>(
|
api.post<{ fetched: number; created: number; updated: number }, { fetched: number; created: number; updated: number }>(
|
||||||
'/platform-fulfillment/sync',
|
'/platform-fulfillment/sync',
|
||||||
|
|||||||
@@ -2580,6 +2580,21 @@ export interface PlatformFulfillmentAllocationPolicy {
|
|||||||
bundleRules: PlatformFulfillmentBundleRule[];
|
bundleRules: PlatformFulfillmentBundleRule[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PlatformFulfillmentCommodityAvailability {
|
||||||
|
allocatable: number;
|
||||||
|
fullBundleAllocatable: number;
|
||||||
|
bundleCommodityCount: number;
|
||||||
|
roleCooldown: number;
|
||||||
|
leased: number;
|
||||||
|
activeCollab: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlatformFulfillmentAccountAvailability {
|
||||||
|
items: Record<string, PlatformFulfillmentCommodityAvailability>;
|
||||||
|
uniqueAllocatable: number;
|
||||||
|
updatedAt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface PlatformFulfillmentSettings {
|
export interface PlatformFulfillmentSettings {
|
||||||
leaseDurationMinutes: number | null;
|
leaseDurationMinutes: number | null;
|
||||||
completedReleaseDelayMinutes: number | null;
|
completedReleaseDelayMinutes: number | null;
|
||||||
|
|||||||
@@ -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 { 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 type { ColumnsType } from 'antd/es/table';
|
||||||
import { douyuApi, platformFulfillmentApi } from '../api/modules';
|
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 ExchangeResultImage from '../components/ExchangeResultImage';
|
||||||
import { copyImageToClipboard, fetchExchangeImageBlob, getExchangeImage, isExchangeTask } from '../utils/exchangeImage';
|
import { copyImageToClipboard, fetchExchangeImageBlob, getExchangeImage, isExchangeTask } from '../utils/exchangeImage';
|
||||||
import { TASK_STATUS_COLORS, TASK_STATUS_LABELS, taskQrUrl } from './douyu-tasks/config';
|
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 [pageSize, setPageSize] = useState(20);
|
||||||
const [rows, setRows] = useState<PlatformFulfillmentTask[]>([]);
|
const [rows, setRows] = useState<PlatformFulfillmentTask[]>([]);
|
||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
|
const [accountAvailability, setAccountAvailability] = useState<PlatformFulfillmentAccountAvailability | null>(null);
|
||||||
|
const [accountAvailabilityLoading, setAccountAvailabilityLoading] = useState(false);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [syncing, setSyncing] = useState(false);
|
const [syncing, setSyncing] = useState(false);
|
||||||
const [collabSyncing, setCollabSyncing] = useState(false);
|
const [collabSyncing, setCollabSyncing] = useState(false);
|
||||||
@@ -681,12 +683,38 @@ export default function PlatformFulfillmentPage() {
|
|||||||
});
|
});
|
||||||
setRows(result.items);
|
setRows(result.items);
|
||||||
setTotal(result.pagination.total);
|
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) {
|
} catch (error) {
|
||||||
if (!silent) message.error(getErrorMessage(error));
|
if (!silent) message.error(getErrorMessage(error));
|
||||||
} finally {
|
} finally {
|
||||||
if (!silent) setLoading(false);
|
if (!silent) setLoading(false);
|
||||||
}
|
}
|
||||||
}, [keyword, page, pageSize, queueBucket, saleModeTab]);
|
}, [can, keyword, page, pageSize, queueBucket, saleModeTab]);
|
||||||
|
|
||||||
const loadDetail = useCallback(async (taskId: number, silent = false) => {
|
const loadDetail = useCallback(async (taskId: number, silent = false) => {
|
||||||
if (!silent) setDetailLoading(true);
|
if (!silent) setDetailLoading(true);
|
||||||
@@ -1606,23 +1634,53 @@ export default function PlatformFulfillmentPage() {
|
|||||||
title: '账号',
|
title: '账号',
|
||||||
key: 'account',
|
key: 'account',
|
||||||
width: 190,
|
width: 190,
|
||||||
render: (_, task) =>
|
render: (_, task) => {
|
||||||
task.account ? (
|
if (task.account) {
|
||||||
<Space direction="vertical" size={2}>
|
return (
|
||||||
<Text>{task.account.nickname || task.account.username}</Text>
|
<Space direction="vertical" size={2}>
|
||||||
<Text type="secondary">
|
<Text>{task.account.nickname || task.account.username}</Text>
|
||||||
积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'}
|
<Text type="secondary">
|
||||||
</Text>
|
积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'}
|
||||||
<Text type="secondary">
|
</Text>
|
||||||
租约 {task.lease ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'}
|
<Text type="secondary">
|
||||||
</Text>
|
租约 {task.lease ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'}
|
||||||
{task.sharedLeaseTaskIds?.length ? (
|
</Text>
|
||||||
<Tag color="cyan">同角色共享 #{task.sharedLeaseTaskIds.join(', #')}</Tag>
|
{task.sharedLeaseTaskIds?.length ? (
|
||||||
|
<Tag color="cyan">同角色共享 #{task.sharedLeaseTaskIds.join(', #')}</Tag>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const availability = accountAvailability?.items[task.commodityId];
|
||||||
|
const canViewAvailability = can('platform_fulfillment:admin');
|
||||||
|
return (
|
||||||
|
<Space direction="vertical" size={3}>
|
||||||
|
<Text type="secondary">未分配</Text>
|
||||||
|
{canViewAvailability && availability ? (
|
||||||
|
<>
|
||||||
|
<Space size={4} wrap>
|
||||||
|
<Tag color={availability.allocatable > 0 ? 'green' : 'red'}>
|
||||||
|
可用账号 {availability.allocatable}
|
||||||
|
</Tag>
|
||||||
|
{availability.bundleCommodityCount > 1 ? (
|
||||||
|
<Tag color={availability.fullBundleAllocatable > 0 ? 'cyan' : 'orange'}>
|
||||||
|
全资格 {availability.fullBundleAllocatable}
|
||||||
|
</Tag>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
{availability.roleCooldown > 0 ||
|
||||||
|
availability.leased > 0 ||
|
||||||
|
availability.activeCollab > 0 ? (
|
||||||
|
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||||
|
占用:冷却 {availability.roleCooldown} · 租约 {availability.leased} · 台账{' '}
|
||||||
|
{availability.activeCollab}
|
||||||
|
</Text>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
</Space>
|
</Space>
|
||||||
) : (
|
);
|
||||||
<Text type="secondary">未分配</Text>
|
},
|
||||||
),
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '用户角色绑定',
|
title: '用户角色绑定',
|
||||||
@@ -1978,6 +2036,21 @@ export default function PlatformFulfillmentPage() {
|
|||||||
</Space>
|
</Space>
|
||||||
) : null;
|
) : 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 (
|
return (
|
||||||
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
||||||
<Card size="small">
|
<Card size="small">
|
||||||
@@ -1989,6 +2062,23 @@ export default function PlatformFulfillmentPage() {
|
|||||||
<Text type="secondary">系统自动检测账号并选号;只有缺货、CK 异常或资格失败时转人工处理。客户扫码绑定后,运营可直接开通宝典、充值或兑换皮肤。</Text>
|
<Text type="secondary">系统自动检测账号并选号;只有缺货、CK 异常或资格失败时转人工处理。客户扫码绑定后,运营可直接开通宝典、充值或兑换皮肤。</Text>
|
||||||
</div>
|
</div>
|
||||||
<Space wrap>
|
<Space wrap>
|
||||||
|
{can('platform_fulfillment:admin') ? (
|
||||||
|
<Tag
|
||||||
|
color={availabilityTagColor}
|
||||||
|
title={
|
||||||
|
accountAvailability?.updatedAt
|
||||||
|
? `库存更新时间:${formatTime(accountAvailability.updatedAt)}`
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
当前页待分配 {pendingAllocationCount} · 可分配库存{' '}
|
||||||
|
{accountAvailability
|
||||||
|
? accountAvailability.uniqueAllocatable
|
||||||
|
: accountAvailabilityLoading
|
||||||
|
? '计算中'
|
||||||
|
: '-'}
|
||||||
|
</Tag>
|
||||||
|
) : null}
|
||||||
<Tag>进行中租约:{leaseDurationLabel(settings?.leaseDurationMinutes)}</Tag>
|
<Tag>进行中租约:{leaseDurationLabel(settings?.leaseDurationMinutes)}</Tag>
|
||||||
<Tag>订单起算:{settings?.orderMatchStartedAt ? formatTime(settings.orderMatchStartedAt) : '-'}</Tag>
|
<Tag>订单起算:{settings?.orderMatchStartedAt ? formatTime(settings.orderMatchStartedAt) : '-'}</Tag>
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
Reference in New Issue
Block a user