feat(fulfillment): 展示可分配账号库存
This commit is contained in:
@@ -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),
|
||||
|
||||
@@ -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,
|
||||
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",
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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<string, PlatformFulfillmentCommodityAvailability>;
|
||||
uniqueAllocatable: number;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface PlatformFulfillmentSettings {
|
||||
leaseDurationMinutes: 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 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<PlatformFulfillmentTask[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [accountAvailability, setAccountAvailability] = useState<PlatformFulfillmentAccountAvailability | null>(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 ? (
|
||||
<Space direction="vertical" size={2}>
|
||||
<Text>{task.account.nickname || task.account.username}</Text>
|
||||
<Text type="secondary">
|
||||
积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'}
|
||||
</Text>
|
||||
<Text type="secondary">
|
||||
租约 {task.lease ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'}
|
||||
</Text>
|
||||
{task.sharedLeaseTaskIds?.length ? (
|
||||
<Tag color="cyan">同角色共享 #{task.sharedLeaseTaskIds.join(', #')}</Tag>
|
||||
render: (_, task) => {
|
||||
if (task.account) {
|
||||
return (
|
||||
<Space direction="vertical" size={2}>
|
||||
<Text>{task.account.nickname || task.account.username}</Text>
|
||||
<Text type="secondary">
|
||||
积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'}
|
||||
</Text>
|
||||
<Text type="secondary">
|
||||
租约 {task.lease ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'}
|
||||
</Text>
|
||||
{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}
|
||||
</Space>
|
||||
) : (
|
||||
<Text type="secondary">未分配</Text>
|
||||
),
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '用户角色绑定',
|
||||
@@ -1978,6 +2036,21 @@ export default function PlatformFulfillmentPage() {
|
||||
</Space>
|
||||
) : 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 (
|
||||
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
||||
<Card size="small">
|
||||
@@ -1989,6 +2062,23 @@ export default function PlatformFulfillmentPage() {
|
||||
<Text type="secondary">系统自动检测账号并选号;只有缺货、CK 异常或资格失败时转人工处理。客户扫码绑定后,运营可直接开通宝典、充值或兑换皮肤。</Text>
|
||||
</div>
|
||||
<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>订单起算:{settings?.orderMatchStartedAt ? formatTime(settings.orderMatchStartedAt) : '-'}</Tag>
|
||||
<Button
|
||||
|
||||
Reference in New Issue
Block a user