feat(fulfillment): 增加账号商品能力索引与生命周期事件

This commit is contained in:
yml
2026-11-18 19:30:59 +08:00
parent dc95d83b32
commit 667634a8df
35 changed files with 3076 additions and 82 deletions
@@ -0,0 +1,52 @@
"""修复重复订单快照把已分配履约任务打回待分配的问题。
旧逻辑在每次消费非终态订单快照时都会执行 ``_apply_mapping``,无条件把
``execution_status`` 改成 ``ready``,但保留 ``account_id`` 和活跃租约。
自动选号只扫描 ``ready + account_id IS NULL``,因此这些任务不会被再次处理。
这里只修复带有效租约、且尚未开始绑定的异常任务,并依据兑换状态恢复提示。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261118_0090"
down_revision: str | None = "20261118_0089"
branch_labels: str | None = None
depends_on: str | None = None
def upgrade() -> None:
op.get_bind().execute(
sa.text(
"UPDATE platform_fulfillment_tasks t "
"JOIN account_leases l ON l.id = t.lease_id "
"SET t.execution_status = 'allocated', "
"t.next_allocate_at = NULL, "
"t.issue_code = CASE t.exchange_status "
"WHEN 'points_short' THEN 'points_short' "
"WHEN 'not_opened' THEN 'elite_not_opened' "
"WHEN 'limited' THEN 'commodity_limit_reached' "
"WHEN 'check_failed' THEN 'eligibility_check_failed' "
"ELSE '' END, "
"t.last_error = CASE t.exchange_status "
"WHEN 'points_short' THEN '账号积分不足,可充值后继续' "
"WHEN 'not_opened' THEN '账号尚未开通精英宝典,可开通后继续' "
"WHEN 'limited' THEN '该账号已达到此商品兑换上限' "
"WHEN 'check_failed' THEN '兑换资格查询失败,请刷新后重试' "
"ELSE '' END, "
"t.updated_at = UTC_TIMESTAMP() "
"WHERE t.execution_status = 'ready' "
"AND t.account_id IS NOT NULL "
"AND t.lease_id IS NOT NULL "
"AND t.binding_status = 'not_started' "
"AND l.purpose = 'platform_fulfillment' "
"AND l.status = 'active'"
)
)
def downgrade() -> None:
# 这是不可逆的数据修复;回滚代码版本也无需重新制造异常状态。
pass
@@ -0,0 +1,167 @@
"""账号商品兑换能力索引。
本表把“某账号对某商品当前能不能换”从 ``overview_snapshot`` JSON 中拆出来,
用于履约秒级候选查询。它只保存最后一次官方查询的派生结论;兑换事实仍写
``account_events``。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261118_0091"
down_revision: str | None = "20261118_0090"
branch_labels: str | None = None
depends_on: str | None = None
TABLE = "account_commodity_states"
def _table_exists(name: str) -> bool:
return bool(
op.get_bind()
.execute(
sa.text(
"SELECT COUNT(*) FROM information_schema.tables "
"WHERE table_schema = DATABASE() AND table_name = :name"
),
{"name": name},
)
.scalar()
)
def _index_exists(name: str) -> bool:
return bool(
op.get_bind()
.execute(
sa.text(
"SELECT COUNT(*) FROM information_schema.statistics "
"WHERE table_schema = DATABASE() "
"AND table_name = :table AND index_name = :name"
),
{"table": TABLE, "name": name},
)
.scalar()
)
def upgrade() -> None:
if not _table_exists(TABLE):
op.create_table(
TABLE,
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
sa.Column("account_id", sa.Integer(), nullable=False),
sa.Column(
"platform",
sa.String(length=16),
nullable=False,
server_default="douyu",
),
sa.Column(
"scope",
sa.String(length=16),
nullable=False,
server_default="elite",
),
sa.Column("commodity_id", sa.String(length=64), nullable=False),
sa.Column(
"commodity_name",
sa.String(length=256),
nullable=False,
server_default="",
),
sa.Column(
"availability",
sa.String(length=16),
nullable=False,
server_default="unknown",
),
sa.Column(
"blocking_reason",
sa.String(length=255),
nullable=False,
server_default="",
),
sa.Column(
"raw_status",
sa.String(length=16),
nullable=False,
server_default="",
),
sa.Column("observed_at", sa.DateTime(), nullable=True),
sa.Column("valid_until", sa.DateTime(), nullable=True),
sa.Column("next_check_at", sa.DateTime(), nullable=True),
sa.Column("last_exchange_at", sa.DateTime(), nullable=True),
sa.Column(
"exchange_count_365d",
sa.Integer(),
nullable=False,
server_default="0",
),
sa.Column(
"source", sa.String(length=24), nullable=False, server_default=""
),
sa.Column(
"error_code",
sa.String(length=64),
nullable=False,
server_default="",
),
sa.Column(
"created_at",
sa.DateTime(),
nullable=False,
server_default=sa.text("CURRENT_TIMESTAMP"),
),
sa.Column(
"updated_at",
sa.DateTime(),
nullable=False,
server_default=sa.text("CURRENT_TIMESTAMP"),
),
sa.PrimaryKeyConstraint("id"),
sa.ForeignKeyConstraint(
["account_id"],
["accounts.id"],
name="fk_account_commodity_account",
ondelete="CASCADE",
),
sa.UniqueConstraint(
"account_id",
"platform",
"scope",
"commodity_id",
name="uq_account_commodity_state",
),
)
if not _index_exists("ix_account_commodity_match"):
op.create_index(
"ix_account_commodity_match",
TABLE,
[
"platform",
"scope",
"commodity_id",
"availability",
"valid_until",
"account_id",
],
)
if not _index_exists("ix_account_commodity_account"):
op.create_index(
"ix_account_commodity_account",
TABLE,
["account_id", "platform", "scope"],
)
def downgrade() -> None:
if _index_exists("ix_account_commodity_account"):
op.drop_index("ix_account_commodity_account", table_name=TABLE)
if _index_exists("ix_account_commodity_match"):
op.drop_index("ix_account_commodity_match", table_name=TABLE)
if _table_exists(TABLE):
op.drop_table(TABLE)
@@ -0,0 +1,38 @@
"""回填官方兑换事件的商品检索键。
早期 ``record_official_exchange`` 只把 ``commodity_id`` 放进 JSON detail,
没有写 ``subject_key``。履约的 365 天同商品规则按 ``subject_key`` 查询,
因此这些官方历史记录实际没有参与匹配。这里从 detail 幂等回填。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261118_0092"
down_revision: str | None = "20261118_0091"
branch_labels: str | None = None
depends_on: str | None = None
def upgrade() -> None:
op.get_bind().execute(
sa.text(
"UPDATE account_events "
"SET subject_key = LEFT("
"JSON_UNQUOTE(JSON_EXTRACT(detail, '$.commodity_id')), 96"
"), subject_type = 'commodity' "
"WHERE event_type = 'exchange' "
"AND source = 'official_sync' "
"AND subject_key = '' "
"AND detail IS NOT NULL "
"AND JSON_UNQUOTE(JSON_EXTRACT(detail, '$.commodity_id')) IS NOT NULL "
"AND JSON_UNQUOTE(JSON_EXTRACT(detail, '$.commodity_id')) <> ''"
)
)
def downgrade() -> None:
# 回填的是可重建的检索投影,不回滚,避免影响后续新写入事件。
pass
@@ -0,0 +1,72 @@
"""账号商品能力增加限时兑换窗口。
斗鱼 ``storehome`` 同时返回账号级 ``status`` 和商品级限时规则:
``timeLimited``、``startTime`` / ``endTime``、``specTimes``。这三类信息
必须分明,不能把未开始、已结束和账号限兑都显示成同一种“不可兑换”。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261118_0093"
down_revision: str | None = "20261118_0092"
branch_labels: str | None = None
depends_on: str | None = None
TABLE = "account_commodity_states"
def _column_exists(name: str) -> bool:
return bool(
op.get_bind()
.execute(
sa.text(
"SELECT COUNT(*) FROM information_schema.columns "
"WHERE table_schema = DATABASE() "
"AND table_name = :table AND column_name = :name"
),
{"table": TABLE, "name": name},
)
.scalar()
)
def upgrade() -> None:
if not _column_exists("time_limited"):
op.add_column(
TABLE,
sa.Column(
"time_limited",
sa.Boolean(),
nullable=False,
server_default="0",
),
)
if not _column_exists("available_from"):
op.add_column(
TABLE,
sa.Column("available_from", sa.DateTime(), nullable=True),
)
if not _column_exists("available_until"):
op.add_column(
TABLE,
sa.Column("available_until", sa.DateTime(), nullable=True),
)
if not _column_exists("schedule_json"):
op.add_column(
TABLE,
sa.Column("schedule_json", sa.JSON(), nullable=True),
)
def downgrade() -> None:
if _column_exists("schedule_json"):
op.drop_column(TABLE, "schedule_json")
if _column_exists("available_until"):
op.drop_column(TABLE, "available_until")
if _column_exists("available_from"):
op.drop_column(TABLE, "available_from")
if _column_exists("time_limited"):
op.drop_column(TABLE, "time_limited")
+103
View File
@@ -1637,6 +1637,109 @@ class AccountEvent(Base):
)
class AccountCommodityState(Base):
"""账号对具体斗鱼商品的当前兑换能力。
``accounts`` 保存账号级状态(CK、积分、宝典、换绑冷却),本表保存
“这个账号现在能不能换这个商品”。它是查询快照的派生索引,不是新的账号主表:
- ``availability`` 是最近一次官方商品列表得出的结论;
- ``observed_at`` / ``valid_until`` 明确这条结论的有效期;
- ``last_exchange_at`` / ``exchange_count_365d`` 是兑换历史的高频反规范化;
- 真正发生过的兑换仍然只追加到 ``account_events``。
匹配读取本表,真正占用账号前再做一次实时确认。查不到时保留上一有效结论,
但过期的 ``available`` 不允许继续参与自动匹配。
"""
__tablename__ = "account_commodity_states"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
account_id: Mapped[int] = mapped_column(
ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False
)
platform: Mapped[str] = mapped_column(
String(16), nullable=False, default="douyu", server_default="douyu"
)
scope: Mapped[str] = mapped_column(
String(16), nullable=False, default="elite", server_default="elite"
)
commodity_id: Mapped[str] = mapped_column(String(64), nullable=False)
commodity_name: Mapped[str] = mapped_column(
String(256), nullable=False, default="", server_default=""
)
# available / limited / no_stock / not_open / not_offered / unknown
availability: Mapped[str] = mapped_column(
String(16), nullable=False, default="unknown", server_default="unknown"
)
blocking_reason: Mapped[str] = mapped_column(
String(255), nullable=False, default="", server_default=""
)
raw_status: Mapped[str] = mapped_column(
String(16), nullable=False, default="", server_default=""
)
time_limited: Mapped[bool] = mapped_column(
Boolean, nullable=False, default=False, server_default="0"
)
available_from: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
available_until: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
schedule_json: Mapped[list | None] = mapped_column(JSON, nullable=True)
observed_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
valid_until: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
next_check_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
last_exchange_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
exchange_count_365d: Mapped[int] = mapped_column(
Integer, nullable=False, default=0, server_default="0"
)
source: Mapped[str] = mapped_column(
String(24), nullable=False, default="", server_default=""
)
error_code: Mapped[str] = mapped_column(
String(64), nullable=False, default="", server_default=""
)
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
updated_at: Mapped[datetime] = mapped_column(
UTCDateTime, default=_utcnow, onupdate=_utcnow
)
__table_args__ = (
UniqueConstraint(
"account_id",
"platform",
"scope",
"commodity_id",
name="uq_account_commodity_state",
),
Index(
"ix_account_commodity_match",
"platform",
"scope",
"commodity_id",
"availability",
"valid_until",
"account_id",
),
Index(
"ix_account_commodity_account",
"account_id",
"platform",
"scope",
),
)
class AccountLease(Base):
"""账号租约:谁在**此刻**可以使用这个账号。
+118 -10
View File
@@ -1,5 +1,6 @@
import csv
import io
from datetime import UTC, datetime
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query, Response
@@ -10,6 +11,7 @@ from ..database import get_db
from ..deps import get_current_user, require_permission
from ..models import (
Account,
AccountCommodityState,
AccountEvent,
AuditLog,
DouyuTask,
@@ -32,13 +34,16 @@ from ..schemas import (
BatchAssign,
)
from ..services.account_binding import bind_payload
from ..services.account_capability_service import account_capability_counts
from ..services.account_events_service import (
CATEGORY_OPS,
EVENT_ASSIGNED,
EVENT_AUTOMATION_CHANGED,
EVENT_CK_INVALID,
EVENT_ELITE_OPENED,
EVENT_ESPORTS_OPENED,
EVENT_EXCHANGE,
EVENT_IMPORTED,
EVENT_RECHARGE,
EVENT_REMARK_CHANGED,
EVENT_TAG_CHANGED,
@@ -967,6 +972,7 @@ def import_accounts(
if accounts:
db.add_all(accounts)
db.flush()
db.add(
AuditLog(
user_id=current.id,
@@ -975,6 +981,22 @@ def import_accounts(
target=f"导入{len(accounts)}个",
)
)
emit_bulk(
db,
[
{
"account_id": account.id,
"event_type": EVENT_IMPORTED,
"title": "账号已导入",
"category": CATEGORY_OPS,
"source": "audit",
"actor_type": "user",
"actor_id": current.id,
"source_ref": f"account_imported:{account.id}",
}
for account in accounts
],
)
db.commit()
duplicated_note = f",重复跳过 {duplicated} 个" if duplicated else ""
@@ -1254,16 +1276,23 @@ def set_account_automation(
acc = db.query(Account).filter(Account.id == account_id).first()
if not acc:
raise HTTPException(status_code=404, detail="账号不存在")
previous = bool(acc.auto_managed)
acc.auto_managed = bool(req.auto_managed)
db.add(
AuditLog(
user_id=current.id,
username=current.username,
action="account:automation",
target=acc.username,
account_id=acc.id,
detail="参与自动化" if req.auto_managed else "不参与自动化",
)
record_account_action(
db,
current,
account=acc,
action="account:automation",
event_type=EVENT_AUTOMATION_CHANGED,
title=(
"自动化:不参与 → 参与"
if req.auto_managed
else "自动化:参与 → 不参与"
),
detail={
"from": previous,
"to": bool(req.auto_managed),
},
)
db.commit()
return {
@@ -1509,6 +1538,81 @@ def batch_delete_accounts_selection(
return {"message": f"已删除 {deleted} 个账号", "deleted": deleted, "success": True}
@router.get("/{account_id}/commodities")
def account_commodities(
account_id: int,
scope: str = Query("", max_length=16),
availability: str = Query("", max_length=16),
limit: int = Query(500, ge=1, le=1000),
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""账号 × 商品当前兑换能力及最后确认时间。"""
if (
not _visible_accounts_query(db, current)
.filter(Account.id == account_id)
.first()
):
raise HTTPException(status_code=404, detail="账号不存在或无权查看")
now = datetime.now(UTC)
query = db.query(AccountCommodityState).filter(
AccountCommodityState.account_id == account_id,
AccountCommodityState.platform == "douyu",
)
scope_value = scope.strip()
availability_value = availability.strip()
if scope_value:
query = query.filter(AccountCommodityState.scope == scope_value)
if availability_value:
query = query.filter(
AccountCommodityState.availability == availability_value
)
rows = (
query.order_by(
case(
(AccountCommodityState.availability == "available", 0),
(AccountCommodityState.availability == "limited", 1),
else_=2,
),
AccountCommodityState.valid_until.desc(),
AccountCommodityState.commodity_id.asc(),
)
.limit(limit)
.all()
)
return {
"items": [
{
"commodity_id": row.commodity_id,
"commodity_name": row.commodity_name,
"scope": row.scope,
"availability": row.availability,
"blocking_reason": row.blocking_reason,
"raw_status": row.raw_status,
"time_limited": bool(row.time_limited),
"available_from": row.available_from,
"available_until": row.available_until,
"schedule": row.schedule_json or [],
"observed_at": row.observed_at,
"valid_until": row.valid_until,
"next_check_at": row.next_check_at,
"last_exchange_at": row.last_exchange_at,
"exchange_count_365d": row.exchange_count_365d,
"fresh": bool(row.valid_until and row.valid_until > now),
"source": row.source,
"error_code": row.error_code,
}
for row in rows
],
"summary": account_capability_counts(
db,
account_id=account_id,
now=now,
),
}
@router.get("/{account_id}/exchange-records")
def account_exchange_records(
account_id: int,
@@ -1660,6 +1764,10 @@ def account_overview(
"points_expire_at": acc.points_expire_at,
"overview_snapshot": acc.overview_snapshot,
"overview_queried_at": acc.overview_queried_at,
"commodity_capability": account_capability_counts(
db,
account_id=int(acc.id),
),
"high_value": high_value_payload(acc),
"elite_opened": acc.elite_opened,
"elite_expire_time": acc.elite_expire_time,
@@ -1694,7 +1802,7 @@ def account_events(
page_size: int = 50,
event_type: str = "",
category: str = Query(
"", description="按粗分类筛选:lifecycle / auth / business / ops"
"", description="按粗分类筛选:lifecycle / auth / business / activity / ops"
),
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
@@ -0,0 +1,568 @@
"""账号商品能力索引。
``accounts`` 回答“账号整体能不能用”,本模块回答“账号对具体商品现在能不能换”。
能力索引只保存查询投影;兑换等不可变事实仍写 ``account_events``。
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import case, func
from sqlalchemy.orm import Session
from ..models import Account, AccountCommodityState, AccountEvent
AVAILABILITY_AVAILABLE = "available"
AVAILABILITY_LIMITED = "limited"
AVAILABILITY_NO_STOCK = "no_stock"
AVAILABILITY_NOT_OPEN = "not_open"
AVAILABILITY_NOT_OFFERED = "not_offered"
AVAILABILITY_EXPIRED = "expired"
AVAILABILITY_UNKNOWN = "unknown"
DEFAULT_CAPABILITY_TTL_SECONDS = 15 * 60
def _env_positive_int(name: str, default: int) -> int:
try:
value = int(os.getenv(name, str(default)))
except ValueError:
return default
return value if value > 0 else default
def capability_ttl_seconds() -> int:
return _env_positive_int(
"ACCOUNT_COMMODITY_STATE_TTL_SECONDS",
DEFAULT_CAPABILITY_TTL_SECONDS,
)
def _to_int(value: Any) -> int | None:
if value is None or value == "":
return None
try:
return int(float(value))
except (TypeError, ValueError):
return None
def _to_datetime(value: Any) -> datetime | None:
timestamp = _to_int(value)
if timestamp is None or timestamp <= 0:
return None
if timestamp > 10_000_000_000:
timestamp //= 1000
return datetime.fromtimestamp(timestamp, tz=UTC)
@dataclass(frozen=True)
class GoodsTimeWindow:
time_limited: bool
start: datetime | None
end: datetime | None
state: str
next_boundary: datetime | None
schedule: list[dict[str, Any]]
def goods_time_window(
item: dict[str, Any],
*,
now: datetime | None = None,
) -> GoodsTimeWindow:
"""解析商品限时窗口。
``status`` 是账号维度的限兑;时间窗口是商品维度的开放区间。两者必须同时
判断。``specTimes`` 优先于外层 start/end,用于一天多场或分阶段开放。
"""
moment = now or datetime.now(UTC)
intervals: list[tuple[datetime, datetime]] = []
schedule: list[dict[str, Any]] = []
raw_spec_times = item.get("specTimes")
if isinstance(raw_spec_times, list):
for raw in raw_spec_times:
if not isinstance(raw, dict):
continue
schedule.append(dict(raw))
start = _to_datetime(raw.get("startTime"))
end = _to_datetime(raw.get("endTime"))
if start is not None and end is not None and end >= start:
intervals.append((start, end))
if not intervals:
start = _to_datetime(item.get("startTime"))
end = _to_datetime(item.get("endTime"))
if start is not None and end is not None and end >= start:
intervals.append((start, end))
time_limited = bool(_to_int(item.get("timeLimited")))
if not intervals:
return GoodsTimeWindow(
time_limited=time_limited,
start=None,
end=None,
state="",
next_boundary=None,
schedule=schedule,
)
intervals.sort(key=lambda value: value[0])
for start, end in intervals:
if start <= moment <= end:
return GoodsTimeWindow(
time_limited=time_limited,
start=start,
end=end,
state="active",
next_boundary=end,
schedule=schedule,
)
for start, end in intervals:
if start > moment:
return GoodsTimeWindow(
time_limited=time_limited,
start=start,
end=end,
state="before",
next_boundary=start,
schedule=schedule,
)
start, end = intervals[-1]
return GoodsTimeWindow(
time_limited=time_limited,
start=start,
end=end,
state="after",
next_boundary=None,
schedule=schedule,
)
def classify_goods_item(
item: dict[str, Any],
*,
now: datetime | None = None,
) -> tuple[str, str, str]:
"""把官方 storehome 商品项归一成能力状态。
返回 ``(availability, blocking_reason, raw_status)``。只有官方明确给出的
账号级 ``status`` 才允许写成 available / limited;缺字段一律 unknown。
"""
moment = now or datetime.now(UTC)
window = goods_time_window(item, now=moment)
raw_status = str(item.get("status") if item.get("status") is not None else "")
status = _to_int(item.get("status"))
store_status = _to_int(
item.get("storeStatus")
if item.get("storeStatus") is not None
else item.get("store_status")
)
open_status = _to_int(
item.get("openStatus")
if item.get("openStatus") is not None
else item.get("open_status")
)
count = _to_int(item.get("count"))
if window.state == "before":
return (
AVAILABILITY_NOT_OPEN,
f"限时兑换未开始,开始于 {window.start.isoformat() if window.start else '未知时间'}",
raw_status,
)
if window.state == "after":
return AVAILABILITY_EXPIRED, "限时兑换已结束", raw_status
if status == 1:
return AVAILABILITY_LIMITED, "该账号已达此商品兑换上限", raw_status
if store_status == 0:
return AVAILABILITY_NO_STOCK, "官方商城当前无库存", raw_status
if count is not None and count <= 0:
return AVAILABILITY_NO_STOCK, "官方商城当前无库存", raw_status
if open_status == 0:
return AVAILABILITY_NOT_OPEN, "活动尚未开放兑换", raw_status
if status == 0:
return AVAILABILITY_AVAILABLE, "", raw_status
return AVAILABILITY_UNKNOWN, "官方商品列表未返回可判定的账号状态", raw_status
def _exchange_stats(
db: Session,
*,
account_id: int,
now: datetime,
) -> dict[str, tuple[datetime | None, int]]:
since = now - timedelta(days=365)
recent_rows = (
db.query(
AccountEvent.subject_key,
func.max(AccountEvent.occurred_at),
func.count(AccountEvent.id),
)
.filter(
AccountEvent.account_id == account_id,
AccountEvent.event_type == "exchange",
AccountEvent.subject_key != "",
AccountEvent.occurred_at >= since,
)
.group_by(AccountEvent.subject_key)
.all()
)
latest_rows = (
db.query(
AccountEvent.subject_key,
func.max(AccountEvent.occurred_at),
)
.filter(
AccountEvent.account_id == account_id,
AccountEvent.event_type == "exchange",
AccountEvent.subject_key != "",
)
.group_by(AccountEvent.subject_key)
.all()
)
latest = {
str(key or ""): value
for key, value in latest_rows
if str(key or "")
}
stats: dict[str, tuple[datetime | None, int]] = {}
for key, recent_at, recent_count in recent_rows:
commodity_id = str(key or "")
if not commodity_id:
continue
stats[commodity_id] = (
latest.get(commodity_id) or recent_at,
int(recent_count or 0),
)
for commodity_id, value in latest.items():
stats.setdefault(commodity_id, (value, 0))
return stats
def _commodity_id(item: dict[str, Any]) -> str:
return str(
item.get("commodityId")
or item.get("commodity_id")
or item.get("id")
or ""
).strip()
def _commodity_name(item: dict[str, Any]) -> str:
return str(
item.get("name")
or item.get("commodityName")
or item.get("commodity_name")
or ""
).strip()
def sync_account_goods_states(
db: Session,
account: Account,
goods_items: list[dict[str, Any]],
*,
scope: str = "elite",
observed_at: datetime | None = None,
source: str = "overview",
replace_missing: bool = True,
) -> int:
"""用一次完整官方商品列表刷新账号商品能力。
只在整份商品列表查询成功时调用。单项/整份失败时不要调用本函数,避免把
“没查到”误写成“不可兑换”。
"""
if not goods_items or account.id is None:
return 0
moment = observed_at or datetime.now(UTC)
valid_until = moment + timedelta(seconds=capability_ttl_seconds())
existing_rows = (
db.query(AccountCommodityState)
.filter(
AccountCommodityState.account_id == account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
)
.all()
)
by_commodity = {row.commodity_id: row for row in existing_rows}
exchange_stats = _exchange_stats(db, account_id=int(account.id), now=moment)
seen: set[str] = set()
changed = 0
for item in goods_items:
if not isinstance(item, dict):
continue
commodity_id = _commodity_id(item)
if not commodity_id:
continue
seen.add(commodity_id)
state = by_commodity.get(commodity_id)
if state is None:
state = AccountCommodityState(
account_id=int(account.id),
platform="douyu",
scope=scope,
commodity_id=commodity_id,
created_at=moment,
)
db.add(state)
by_commodity[commodity_id] = state
availability, reason, raw_status = classify_goods_item(item, now=moment)
window = goods_time_window(item, now=moment)
last_exchange_at, exchange_count = exchange_stats.get(
commodity_id,
(None, 0),
)
state.commodity_name = _commodity_name(item)[:256]
state.availability = availability
state.blocking_reason = reason[:255]
state.raw_status = raw_status[:16]
state.time_limited = window.time_limited
state.available_from = window.start
state.available_until = window.end
state.schedule_json = window.schedule or None
state.observed_at = moment
state.valid_until = valid_until
state.next_check_at = (
min(valid_until, window.next_boundary)
if window.next_boundary is not None
else valid_until
)
state.last_exchange_at = last_exchange_at
state.exchange_count_365d = int(exchange_count)
state.source = source[:24]
state.error_code = ""
state.updated_at = moment
changed += 1
if replace_missing:
for commodity_id, state in by_commodity.items():
if commodity_id in seen:
continue
if (
state.availability == AVAILABILITY_NOT_OFFERED
and state.blocking_reason == "官方商品列表本次未返回该商品"
):
continue
state.availability = AVAILABILITY_NOT_OFFERED
state.blocking_reason = "官方商品列表本次未返回该商品"
state.observed_at = moment
state.valid_until = None
state.next_check_at = valid_until
state.source = source[:24]
state.updated_at = moment
changed += 1
db.flush()
return changed
def record_account_commodity_state(
db: Session,
account: Account,
*,
commodity_id: str,
availability: str,
blocking_reason: str = "",
raw_status: str = "",
observed_at: datetime | None = None,
source: str = "live_check",
scope: str = "elite",
valid_for_seconds: int | None = None,
error_code: str = "",
) -> AccountCommodityState:
"""写入单个商品的实时检查结论,供下一轮匹配直接使用。"""
moment = observed_at or datetime.now(UTC)
ttl = (
capability_ttl_seconds()
if valid_for_seconds is None
else max(1, int(valid_for_seconds))
)
state = (
db.query(AccountCommodityState)
.filter(
AccountCommodityState.account_id == account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
)
.first()
)
if state is None:
state = AccountCommodityState(
account_id=int(account.id),
platform="douyu",
scope=scope,
commodity_id=commodity_id,
created_at=moment,
)
db.add(state)
exchange_stats = _exchange_stats(
db,
account_id=int(account.id),
now=moment,
)
last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (None, 0))
state.availability = availability
state.blocking_reason = blocking_reason[:255]
state.raw_status = raw_status[:16]
state.observed_at = moment
state.valid_until = moment + timedelta(seconds=ttl)
state.next_check_at = state.valid_until
state.last_exchange_at = last_exchange_at
state.exchange_count_365d = int(exchange_count)
state.source = source[:24]
state.error_code = error_code[:64]
state.updated_at = moment
db.flush()
return state
def mark_commodity_exchanged(
db: Session,
*,
account_id: int,
commodity_id: str,
occurred_at: datetime | None = None,
scope: str = "elite",
commodity_name: str = "",
) -> None:
"""实际兑换后立即更新匹配投影,避免下一单再次选中。"""
if not commodity_id:
return
moment = occurred_at or datetime.now(UTC)
state = (
db.query(AccountCommodityState)
.filter(
AccountCommodityState.account_id == account_id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
)
.first()
)
if state is None:
state = AccountCommodityState(
account_id=account_id,
platform="douyu",
scope=scope,
commodity_id=commodity_id,
created_at=moment,
)
db.add(state)
exchange_stats = _exchange_stats(db, account_id=account_id, now=moment)
last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (moment, 1))
if commodity_name:
state.commodity_name = commodity_name[:256]
state.availability = AVAILABILITY_LIMITED
state.blocking_reason = "该账号已兑换过此商品,365 天内不可重复分配"
state.observed_at = moment
state.valid_until = None
state.next_check_at = moment + timedelta(days=365)
state.last_exchange_at = last_exchange_at
state.exchange_count_365d = max(1, int(exchange_count))
state.source = "exchange"
state.error_code = ""
state.updated_at = moment
db.flush()
def invalidate_account_commodity_states(
db: Session,
*,
account_id: int,
reason: str,
observed_at: datetime | None = None,
) -> int:
"""CK 失效等全局风险发生时,立即作废所有可匹配能力。"""
moment = observed_at or datetime.now(UTC)
changed = (
db.query(AccountCommodityState)
.filter(
AccountCommodityState.account_id == account_id,
AccountCommodityState.availability == AVAILABILITY_AVAILABLE,
)
.update(
{
AccountCommodityState.availability: AVAILABILITY_UNKNOWN,
AccountCommodityState.blocking_reason: reason[:255],
AccountCommodityState.observed_at: moment,
AccountCommodityState.valid_until: None,
AccountCommodityState.next_check_at: moment,
AccountCommodityState.updated_at: moment,
},
synchronize_session=False,
)
)
return int(changed or 0)
def account_capability_counts(
db: Session,
*,
account_id: int,
now: datetime | None = None,
) -> dict[str, int]:
moment = now or datetime.now(UTC)
rows = (
db.query(
AccountCommodityState.availability,
func.count(AccountCommodityState.id),
func.sum(
case(
(
AccountCommodityState.availability
== AVAILABILITY_AVAILABLE,
1,
),
else_=0,
)
),
)
.filter(AccountCommodityState.account_id == account_id)
.group_by(AccountCommodityState.availability)
.all()
)
result = {str(status): int(count or 0) for status, count, _ in rows}
fresh_available = (
db.query(func.count(AccountCommodityState.id))
.filter(
AccountCommodityState.account_id == account_id,
AccountCommodityState.availability == AVAILABILITY_AVAILABLE,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > moment,
)
.scalar()
or 0
)
result["fresh_available"] = int(fresh_available)
result["total"] = sum(
value for key, value in result.items() if key not in {"fresh_available", "total"}
)
return result
__all__ = [
"AVAILABILITY_AVAILABLE",
"AVAILABILITY_EXPIRED",
"AVAILABILITY_LIMITED",
"AVAILABILITY_NOT_OFFERED",
"AVAILABILITY_NOT_OPEN",
"AVAILABILITY_NO_STOCK",
"AVAILABILITY_UNKNOWN",
"account_capability_counts",
"capability_ttl_seconds",
"classify_goods_item",
"goods_time_window",
"invalidate_account_commodity_states",
"mark_commodity_exchanged",
"record_account_commodity_state",
"sync_account_goods_states",
]
@@ -69,6 +69,14 @@ EVENT_ASSIGNED = "assigned" # 分配客服
EVENT_TAG_CHANGED = "tag_changed" # 标签变更
EVENT_REMARK_CHANGED = "remark_changed" # 备注变更
EVENT_STATUS_CHANGED = "status_changed" # 生命周期状态变迁(停用/归档/失效…)
EVENT_AUTOMATION_CHANGED = "automation_changed" # 自动化开关
EVENT_TASK_STARTED = "task_started" # 斗鱼账号任务创建
EVENT_TASK_SUCCEEDED = "task_succeeded" # 斗鱼账号任务成功
EVENT_TASK_FAILED = "task_failed" # 斗鱼账号任务失败
EVENT_TASK_STOPPED = "task_stopped" # 斗鱼账号任务停止/中断
EVENT_QUERY_COMPLETED = "query_completed" # 同步查询完成(含部分失败)
EVENT_LEASE_ACQUIRED = "lease_acquired" # 分配履约账号使用权
EVENT_LEASE_RELEASED = "lease_released" # 释放履约账号使用权
# 有符号金额的事件类型(用于页面「累计充值/累计消耗」):
# 充值为正、兑换为负,其余不计入金额统计。
@@ -80,6 +88,7 @@ CATEGORY_LIFECYCLE = "lifecycle" # 生命周期状态变迁
CATEGORY_AUTH = "auth" # 登录与 CK
CATEGORY_BUSINESS = "business" # 充值 / 兑换 / 积分 / 开通
CATEGORY_OPS = "ops" # 人工操作(分配 / 标签 / 停用)
CATEGORY_ACTIVITY = "activity" # 查询 / 绑定 / 账号任务等活动
def _is_duplicate_entry(exc: BaseException) -> bool:
+18
View File
@@ -290,6 +290,24 @@ def on_ck_verdict(
# `error`(查不到)**不**作废:查不到不等于账号出问题了。
if verdict == "invalid":
invalidate_high_value(account)
if account.id is not None:
from .account_capability_service import (
invalidate_account_commodity_states,
)
try:
invalidate_account_commodity_states(
db,
account_id=int(account.id),
reason="CK 已失效,账号商品能力待重新确认",
observed_at=now,
)
except Exception as exc: # noqa: BLE001 - 生命周期主流程不能被派生索引拖垮
logger.warning(
"作废账号商品能力失败 account_id={}: {}",
account.id,
exc,
)
data = detail or {}
account.ck_check_result = {
"fish_ball": data.get("fish_ball"),
@@ -6,6 +6,12 @@
from __future__ import annotations
from .jobs.account_capability_refresh import (
JOB_KEY as ACCOUNT_CAPABILITY_REFRESH_KEY,
)
from .jobs.account_capability_refresh import (
run_account_capability_refresh,
)
from .jobs.account_overview_refresh import (
JOB_KEY as ACCOUNT_OVERVIEW_REFRESH_KEY,
)
@@ -45,6 +51,7 @@ from .scheduler import (
)
__all__ = [
"ACCOUNT_CAPABILITY_REFRESH_KEY",
"ACCOUNT_OVERVIEW_REFRESH_KEY",
"CK_HEALTH_KEY",
"CK_RELOGIN_KEY",
@@ -58,6 +65,7 @@ __all__ = [
"register_job",
"registered_jobs",
"reset_registry",
"run_account_capability_refresh",
"run_account_overview_refresh",
"run_ck_health",
"run_ck_relogin",
@@ -74,6 +82,18 @@ __all__ = [
def register_default_jobs() -> None:
"""登记内置作业(幂等)。"""
register_job(
JobSpec(
key=ACCOUNT_CAPABILITY_REFRESH_KEY,
title="履约商品能力补充刷新",
# 只刷新有 pending 履约需求且能力快照已过期的账号。
interval_seconds=3600,
run_interval_seconds=5 * 60,
batch_size=100,
concurrency=3,
run=run_account_capability_refresh,
)
)
register_job(
JobSpec(
key=POINTS_EXPIRE_KEY,
@@ -0,0 +1,118 @@
"""按直播履约需求刷新账号商品能力。
全量资料补全仍由 ``account_overview_refresh`` 负责;本作业只处理“有 pending
任务、但对应商品能力快照已经过期”的账号,避免为了秒匹配把两万多个账号
无条件轮询一遍。
"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from sqlalchemy import exists, or_, select
from sqlalchemy.orm import Session
from ....models import (
Account,
AccountCommodityState,
AccountLease,
AutomationJob,
PlatformFulfillmentTask,
)
from ...account_lifecycle import MANUAL_STATES
from ...douyu_service import cookie_operable_filter
from .account_overview_refresh import run_refresh_for_accounts
JOB_KEY = "account_capability_refresh"
def _base_query(db: Session, now: datetime):
pending_commodities = (
select(PlatformFulfillmentTask.commodity_id)
.where(
PlatformFulfillmentTask.execution_status == "ready",
PlatformFulfillmentTask.account_id.is_(None),
PlatformFulfillmentTask.commodity_id != "",
)
.distinct()
)
stale_demand_state = exists(
select(AccountCommodityState.id).where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == "elite",
AccountCommodityState.commodity_id.in_(pending_commodities),
or_(
AccountCommodityState.valid_until.is_(None),
AccountCommodityState.valid_until <= now,
AccountCommodityState.next_check_at.is_(None),
AccountCommodityState.next_check_at <= now,
),
)
)
active_lease = exists(
select(AccountLease.id).where(
AccountLease.active_account_id == Account.id,
)
)
return db.query(Account).filter(
cookie_operable_filter(),
Account.auto_managed.is_(True),
Account.status.notin_(MANUAL_STATES),
Account.ck_check_status == "valid",
stale_demand_state,
~active_lease,
)
def build_select_query(
db: Session,
job: AutomationJob,
now: datetime | None = None,
):
moment = now or datetime.now(UTC)
batch = max(1, int(job.batch_size or 100))
return (
_base_query(db, moment)
.order_by(
Account.overview_queried_at.is_(None).desc(),
Account.overview_queried_at.asc(),
Account.id.asc(),
)
.limit(batch)
)
def count_remaining(
db: Session,
*,
now: datetime | None = None,
) -> int:
return _base_query(db, now or datetime.now(UTC)).count()
def run_account_capability_refresh(
db: Session,
job: AutomationJob,
) -> dict[str, Any]:
now = datetime.now(UTC)
accounts = build_select_query(db, job, now).all()
return run_refresh_for_accounts(
db,
job,
accounts,
now=now,
remaining_count=count_remaining(db, now=now),
source="capability_demand_refresh",
log_label="capability",
empty_message="当前履约商品没有到期待刷新的账号能力",
)
__all__ = [
"JOB_KEY",
"build_select_query",
"count_remaining",
"run_account_capability_refresh",
]
@@ -159,10 +159,18 @@ def _system_user_id(db: Session) -> int:
return int(user.id)
def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, Any]:
"""本轮:选一批 → 建任务 → 就地跑完 → 看失败率决定要不要熔断。"""
now = datetime.now(UTC)
accounts = build_select_query(db, job, now).all()
def run_refresh_for_accounts(
db: Session,
job: AutomationJob,
accounts: list[Account],
*,
now: datetime,
remaining_count: int | None = None,
source: str = "scheduled_refresh",
log_label: str = "overview",
empty_message: str = "全库暂无待补全或到期的账号",
) -> dict[str, Any]:
"""对指定账号执行资料刷新;能力刷新作业也复用这条写入链。"""
if not accounts:
return {
"scanned": 0,
@@ -170,7 +178,7 @@ def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, A
"invalid": 0,
"succeeded": 0,
"failed": 0,
"message": "全库暂无待补全或到期的账号",
"message": empty_message,
}
account_ids = [a.id for a in accounts]
@@ -181,7 +189,7 @@ def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, A
"elite",
_system_user_id(db),
# 标上来源,便于在任务列表里区分「定时巡检」与「人工点查询」
{"source": "scheduled_refresh"},
{"source": source},
)
if count == 0:
return {
@@ -220,19 +228,18 @@ def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, A
db.commit()
paused = True
logger.warning(
f"[overview] 失败率 {error_ratio:.0%} 过高,已自动关闭作业"
f"[{log_label}] 失败率 {error_ratio:.0%} 过高,已自动关闭作业"
f"(batch={batch_id},failed={failed}/{len(rows)})—— 请确认是否被风控"
)
message = (
f"本轮查 {len(rows)} 个:成功 {succeeded} / 失败 {failed}"
f"(剩 {count_remaining(db, job, now)} 个待查)"
)
message = f"本轮查 {len(rows)} 个:成功 {succeeded} / 失败 {failed}"
if remaining_count is not None:
message += f"(剩 {remaining_count} 个待查)"
if paused:
# 把**可能的原因**写进消息里:运维看作业历史时才知道该去查什么,
# 否则只看到"失败率高"会一头雾水。
message += ";失败率过高,已自动关闭作业(大面积失败通常是**被风控**或接口抖动,请先确认再重开)"
logger.info(f"[overview] {message}")
logger.info(f"[{log_label}] {message}")
return {
"scanned": len(rows),
"valid": succeeded,
@@ -243,3 +250,16 @@ def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, A
"paused": paused,
"message": message,
}
def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, Any]:
"""本轮:选一批 → 建任务 → 就地跑完 → 看失败率决定要不要熔断。"""
now = datetime.now(UTC)
accounts = build_select_query(db, job, now).all()
return run_refresh_for_accounts(
db,
job,
accounts,
now=now,
remaining_count=count_remaining(db, job, now),
)
+142 -3
View File
@@ -33,17 +33,24 @@ from __future__ import annotations
from datetime import datetime
from typing import Any
from loguru import logger
from sqlalchemy.orm import Session
from ..models import Account
from .account_events_service import (
CATEGORY_ACTIVITY,
CATEGORY_BUSINESS,
EVENT_BIND_OK,
EVENT_EXCHANGE,
EVENT_GOLD_SPENT,
EVENT_POINTS_CREDIT,
EVENT_POINTS_EXPIRE,
EVENT_QUERY_COMPLETED,
EVENT_RECHARGE,
EVENT_TASK_FAILED,
EVENT_TASK_STARTED,
EVENT_TASK_STOPPED,
EVENT_TASK_SUCCEEDED,
OFFICIAL_SYNC_SOURCE,
emit,
to_naive_utc,
@@ -64,6 +71,116 @@ def task_ref(task_id: int, kind: str = "") -> str:
return f"{base}:{kind}" if kind else base
def record_douyu_task_started(
db: Session,
account: Account,
*,
task_id: int,
task_type: str,
task_label: str,
scope: str,
actor_id: int | None = None,
) -> bool:
"""记录账号任务已创建;每次任务只写一条。"""
return emit(
db,
account_id=account.id,
event_type=EVENT_TASK_STARTED,
title=f"{task_label}:任务已创建",
category=CATEGORY_ACTIVITY,
detail={
"task_id": task_id,
"task_type": task_type,
"scope": scope,
"status": "planned",
},
source="douyu_task",
subject_type="task",
subject_key=str(task_id),
actor_type="user" if actor_id else "system",
actor_id=actor_id,
source_ref=f"douyu_task_started:{task_id}",
)
def record_douyu_task_result(
db: Session,
account: Account,
*,
task_id: int,
task_type: str,
task_label: str,
scope: str,
status: str,
message: str = "",
occurred_at: datetime | None = None,
) -> bool:
"""记录账号任务终态;成功不等于业务事实,因此单独作为活动事件。"""
event_type = {
"success": EVENT_TASK_SUCCEEDED,
"failed": EVENT_TASK_FAILED,
"error": EVENT_TASK_FAILED,
"stopped": EVENT_TASK_STOPPED,
}.get(status)
if event_type is None:
return False
status_label = {
EVENT_TASK_SUCCEEDED: "成功",
EVENT_TASK_FAILED: "失败",
EVENT_TASK_STOPPED: "已停止",
}[event_type]
return emit(
db,
account_id=account.id,
event_type=event_type,
title=f"{task_label}:{status_label}",
category=CATEGORY_ACTIVITY,
occurred_at=occurred_at,
detail={
"task_id": task_id,
"task_type": task_type,
"scope": scope,
"status": status,
"message": (message or "")[:1000],
},
source="douyu_task",
subject_type="task",
subject_key=str(task_id),
source_ref=f"douyu_task_result:{task_id}",
)
def record_account_query(
db: Session,
account: Account,
*,
query_type: str,
title: str,
ok: bool,
detail: dict[str, Any] | None = None,
actor_id: int | None = None,
) -> bool:
"""记录同步查询结果;允许同一查询反复发生,不做跨次幂等。"""
suffix = "" if ok else "(部分失败)"
return emit(
db,
account_id=account.id,
event_type=EVENT_QUERY_COMPLETED,
title=f"{title}{suffix}",
category=CATEGORY_ACTIVITY,
detail={
"query_type": query_type,
"ok": ok,
**(detail or {}),
},
source="douyu_query",
subject_type="query",
subject_key=query_type,
actor_type="user" if actor_id else "system",
actor_id=actor_id,
)
def record_recharge(
db: Session,
account: Account,
@@ -137,7 +254,7 @@ def record_exchange(
`score` 为负写入 `amount`(消耗),`points_after` 是兑换后的积分余额。
"""
return emit(
written = emit(
db,
account_id=account.id,
event_type=EVENT_EXCHANGE,
@@ -161,6 +278,26 @@ def record_exchange(
subject_key=commodity_id or name or "",
source_ref=task_ref(task_id),
)
if commodity_id:
from .account_capability_service import mark_commodity_exchanged
try:
mark_commodity_exchanged(
db,
account_id=int(account.id),
commodity_id=commodity_id,
occurred_at=occurred_at,
scope=scope,
commodity_name=name,
)
except Exception as exc: # noqa: BLE001 - 派生索引不能破坏兑换主流程
logger.warning(
"更新账号商品能力失败 account_id={} commodity_id={}: {}",
account.id,
commodity_id,
exc,
)
return written
def record_gold_spent(
@@ -366,7 +503,7 @@ def record_official_exchange(
"""
if not commodity_id:
return False
return emit(
written = emit(
db,
account_id=account.id,
event_type=EVENT_EXCHANGE,
@@ -386,11 +523,13 @@ def record_official_exchange(
"scope": scope,
},
source=OFFICIAL_SYNC_SOURCE,
subject_type="goods",
subject_type="commodity",
subject_key=commodity_id,
source_ref=(
f"official_exchange:{scope}:{account.id}:{commodity_id}:{_stamp(occurred_at)}"
),
)
return written
def _stamp(value: datetime | None) -> str:
+44 -3
View File
@@ -34,6 +34,7 @@ from ..models import (
User,
)
from .audit_service import record_audit
from .business_events import record_account_query
from .collab_common import apply_order_visibility, count_archived
from .douyu_activity_query import (
activity_client,
@@ -1304,6 +1305,22 @@ def query_activity(
commit=False,
)
record_account_query(
db,
account,
query_type="collab_activity",
title="查询鱼翅与积分" if not include_records else "查询积分与兑换记录",
ok=not bool(errors),
detail={
"order_no": order.order_no,
"include_records": include_records,
"verdict": verdict,
"records": len(records),
"errors": errors[:10],
},
actor_id=current.id,
)
if commit:
db.commit()
db.refresh(order)
@@ -1640,10 +1657,34 @@ def refresh_activity_goods(
if account is None:
raise CollabError("没有带 CK 的斗鱼账号,无法刷新活动商品", code="no_account")
active_client = client or _client_for_account(account)
goods = query_activity_goods(
active_client, manual_id=str(config.manual_id or ""), rid=str(config.rid or "")
)
try:
goods = query_activity_goods(
active_client,
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
)
except Exception as exc:
record_account_query(
db,
account,
query_type="goods_refresh",
title="刷新活动商品",
ok=False,
detail={"error": str(exc)[:1000]},
actor_id=current.id,
)
db.commit()
raise
upsert_goods_snapshot(db, goods, commit=False)
record_account_query(
db,
account,
query_type="goods_refresh",
title="刷新活动商品",
ok=True,
detail={"count": len(goods)},
actor_id=current.id,
)
record_audit(
db,
current,
+22
View File
@@ -26,6 +26,7 @@ from ..models import (
from .douyu_goods_service import upsert_goods_snapshot
from .douyu_service import (
DOUYU_CONFIG_FIELDS,
SUPPORTED_DOUYU_TASK_TYPES,
douyu_config_value,
douyu_task_payload,
ensure_douyu_config,
@@ -212,6 +213,27 @@ class DouyuBatchRunnerCore:
if result is not None:
task.result = result
task.finished_at = datetime.now(UTC)
if task.account_id and status in {"success", "failed", "error", "stopped"}:
from .business_events import record_douyu_task_result
account = (
db.query(Account).filter(Account.id == task.account_id).first()
)
if account is not None:
record_douyu_task_result(
db,
account,
task_id=int(task.id),
task_type=str(task.task_type or ""),
task_label=SUPPORTED_DOUYU_TASK_TYPES.get(
str(task.task_type or ""),
str(task.task_type or "斗鱼任务"),
),
scope=str(task.handbook_scope or ""),
status=status,
message=message,
occurred_at=task.finished_at,
)
db.commit()
self._push_task_event(task)
self._sync_platform_fulfillment(db, task)
+27 -10
View File
@@ -5,8 +5,8 @@
一个**只读**聚合任务:鱼翅 / 积分(含到期时间)/ 精英宝典 / 电竞手册 /
小店 / 官方兑换记录 / **限兑商品(重点看高价值套装是否已拥有)**。
**不改任何账号状态、不发业务事件** —— 纯查询不是「事实」,
按既有设计例行查询不进时间线,否则查几次就把时间线刷满了。
查询结果会投影成账号当前状态和商品能力,但不会制造兑换等业务事实。
任务本身由执行器统一写入 `activity` 时间线;轮询过程不逐次刷事件。
## 为什么「是否已拥有」能直接查官方
@@ -34,6 +34,7 @@ from core.douyu import DouyuActivityClient
from ..models import Account, DouyuTask
from .account_binding import binding_snapshot, set_bind_status
from .account_capability_service import sync_account_goods_states
from .business_events import record_official_exchange
from .douyu_activity_query import (
query_activity_goods,
@@ -50,8 +51,9 @@ from .high_value_service import (
extract_high_value_goods,
)
#: 官方兑换记录默认取多少条(完整记录可能很多,一次性拉回来没必要)
EXCHANGE_RECORD_LIMIT = 20
#: 官方兑换记录单次抓取上限。能力匹配需要更完整的一年记录,详情页只展示前 20 条。
EXCHANGE_RECORD_FETCH_LIMIT = 100
EXCHANGE_RECORD_DISPLAY_LIMIT = 20
#: 单项错误的摘要长度(避免把整个 traceback 塞进 task.result)
_ERROR_MAX = 200
@@ -144,7 +146,7 @@ def _ts(value: Any) -> Any:
class OverviewMixin:
"""一键查询域:只读聚合,不写状态、不发事件。"""
"""一键查询域:读取官方数据并投影到账号当前状态。"""
if TYPE_CHECKING:
@@ -212,7 +214,7 @@ class OverviewMixin:
return query_exchange_records(
client,
manual_id=manual_id,
limit=EXCHANGE_RECORD_LIMIT,
limit=EXCHANGE_RECORD_FETCH_LIMIT,
)
def _fetch_esports_records(
@@ -225,7 +227,7 @@ class OverviewMixin:
return query_exchange_records(
client,
manual_id=esports_manual_id,
limit=EXCHANGE_RECORD_LIMIT,
limit=EXCHANGE_RECORD_FETCH_LIMIT,
)
def _fetch_xpd_records(
@@ -440,7 +442,7 @@ class OverviewMixin:
except Exception as exc: # noqa: BLE001 外部接口边界需要宽泛兜底
errors[key] = _err(exc)
continue
overview["exchange_records"][scope] = rows[:EXCHANGE_RECORD_LIMIT]
overview["exchange_records"][scope] = rows[:EXCHANGE_RECORD_DISPLAY_LIMIT]
all_records.extend((scope, r) for r in rows)
overview[f"exchange_record_count_{scope}"] = len(rows)
@@ -450,10 +452,25 @@ class OverviewMixin:
db, account, all_records
)
overview["exchange_records"] = {
scope: rows[:EXCHANGE_RECORD_LIMIT]
scope: rows[:EXCHANGE_RECORD_DISPLAY_LIMIT]
for scope, rows in _group_by_scope(all_records).items()
}
# ---- 账号 × 商品能力索引 ----
# 只有完整商城列表查询成功时才更新,避免把网络失败写成“不可兑换”。
if goods_query_ok:
try:
overview["commodity_states_synced"] = sync_account_goods_states(
db,
account,
pending_goods,
scope="elite",
observed_at=queried_at,
source="overview",
)
except Exception as exc: # noqa: BLE001
errors["commodity_states"] = _err(exc)
# ---- 🎯 高价值套装判定(依赖兑换记录,必须放在它之后)----
if not manual_id:
errors["high_value_goods"] = "未配置精英宝典 manualID"
@@ -478,7 +495,7 @@ class OverviewMixin:
errors["high_value_goods"] = _err(exc)
# 查询会回写账号上的余额/积分缓存(各 _refresh_* 内部已写),
# 但**不改生命周期状态**,也不发事件。
# 但**不改生命周期状态,也不制造业务事实事件**;任务活动由执行器统一记录。
account.updated_at = datetime.now(UTC)
owned = [
+60 -12
View File
@@ -12,6 +12,7 @@ from core.douyu.activity_client import DouyuActivityClient
from core.douyu.cookie_utils import cookie_value
from ..models import Account, DouyuConfig, DouyuTask, LoginTask
from .account_events_service import CATEGORY_ACTIVITY, EVENT_TASK_STARTED, emit_bulk
SUPPORTED_DOUYU_TASK_TYPES = {
"get_bind_qr": "获取绑定二维码",
@@ -291,19 +292,47 @@ def create_douyu_planned_tasks(
batch_id = uuid.uuid4().hex[:12]
payload = payload or {}
task_rows: list[tuple[DouyuTask, Account]] = []
for account in accounts:
db.add(
DouyuTask(
batch_id=batch_id,
account_id=account.id,
account_assigned_to=account.assigned_to,
task_type=task_type,
handbook_scope=handbook_scope,
status="planned",
message="任务已创建,等待执行",
result={"payload": payload} if payload else None,
created_by=created_by,
)
task = DouyuTask(
batch_id=batch_id,
account_id=account.id,
account_assigned_to=account.assigned_to,
task_type=task_type,
handbook_scope=handbook_scope,
status="planned",
message="任务已创建,等待执行",
result={"payload": payload} if payload else None,
created_by=created_by,
)
db.add(task)
task_rows.append((task, account))
db.flush()
if task_rows:
label = SUPPORTED_DOUYU_TASK_TYPES[task_type]
emit_bulk(
db,
[
{
"account_id": account.id,
"event_type": EVENT_TASK_STARTED,
"title": f"{label}:任务已创建",
"category": CATEGORY_ACTIVITY,
"detail": {
"task_id": task.id,
"task_type": task_type,
"scope": handbook_scope,
"status": "planned",
},
"source": "douyu_task",
"subject_type": "task",
"subject_key": str(task.id),
"actor_type": "user",
"actor_id": created_by,
"source_ref": f"douyu_task_started:{task.id}",
}
for task, account in task_rows
],
)
db.commit()
return batch_id, len(accounts)
@@ -328,10 +357,29 @@ def cleanup_orphan_douyu_tasks(
if not tasks:
return 0
now = datetime.now(UTC)
from .business_events import record_douyu_task_result
for task in tasks:
task.status = "stopped"
task.message = message
task.finished_at = now
if task.account_id:
account = db.query(Account).filter(Account.id == task.account_id).first()
if account is not None:
record_douyu_task_result(
db,
account,
task_id=int(task.id),
task_type=str(task.task_type or ""),
task_label=SUPPORTED_DOUYU_TASK_TYPES.get(
str(task.task_type or ""),
str(task.task_type or "斗鱼任务"),
),
scope=str(task.handbook_scope or ""),
status="stopped",
message=message,
occurred_at=now,
)
db.commit()
return len(tasks)
@@ -13,7 +13,14 @@ from sqlalchemy import case, or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ...models import Account, AccountEvent, AccountLease, User
from ...models import Account, AccountCommodityState, AccountEvent, AccountLease, User
from ..account_capability_service import AVAILABILITY_AVAILABLE
from ..account_events_service import (
CATEGORY_OPS,
EVENT_LEASE_ACQUIRED,
EVENT_LEASE_RELEASED,
emit,
)
from ..account_lifecycle import MANUAL_STATES
VALIDATION_LEASE_MINUTES = 5
@@ -136,6 +143,10 @@ def live_candidate_accounts(
Account.cookie != "",
Account.auto_managed.is_(True),
Account.status.notin_(MANUAL_STATES),
or_(
Account.role_change_available_at.is_(None),
Account.role_change_available_at <= _now(),
),
or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)),
~active_lease,
)
@@ -172,6 +183,80 @@ def live_candidate_accounts(
)
def capability_candidate_accounts(
db: Session,
*,
commodity_id: str,
required_points: int = 0,
scope: str = "elite",
limit: int = 20,
now: datetime | None = None,
) -> list[Account]:
"""从新鲜的商品能力索引读取候选账号,不产生外部请求。"""
commodity = commodity_id.strip()
if not commodity:
return []
moment = _now(now)
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
owner_ids = _pool_owner_ids()
active_lease = (
select(AccountLease.id)
.where(AccountLease.active_account_id == Account.id)
.exists()
)
return (
db.query(Account)
.join(
AccountCommodityState,
AccountCommodityState.account_id == Account.id,
)
.filter(
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity,
AccountCommodityState.availability == AVAILABILITY_AVAILABLE,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > moment,
or_(
AccountCommodityState.available_from.is_(None),
AccountCommodityState.available_from <= moment,
),
or_(
AccountCommodityState.available_until.is_(None),
AccountCommodityState.available_until >= moment,
),
or_(
AccountCommodityState.last_exchange_at.is_(None),
AccountCommodityState.last_exchange_at < since,
),
Account.cookie.isnot(None),
Account.cookie != "",
Account.auto_managed.is_(True),
Account.status.notin_(MANUAL_STATES),
or_(
Account.role_change_available_at.is_(None),
Account.role_change_available_at <= moment,
),
or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)),
~active_lease,
)
.order_by(
case((Account.ck_check_status == "valid", 0), else_=1),
case((Account.status == "active", 0), else_=1),
case((Account.elite_opened.is_(True), 0), else_=1),
case(
(Account.points >= max(0, int(required_points)), 0),
else_=1,
),
Account.points.asc(),
AccountCommodityState.observed_at.desc(),
Account.id.asc(),
)
.limit(max(1, min(int(limit), 100)))
.all()
)
def has_recent_exchange(
db: Session,
*,
@@ -231,6 +316,26 @@ def lease_account(
if lease in db:
db.expunge(lease)
return None
emit(
db,
account_id=int(candidate.account_id),
event_type=EVENT_LEASE_ACQUIRED,
title=f"履约占用:任务 #{task_id}",
category=CATEGORY_OPS,
detail={
"lease_id": lease.id,
"task_id": task_id,
"holder_user_id": holder_user_id,
"commodity_id": commodity_id,
"purpose": "platform_fulfillment",
},
source="lease",
subject_type="task",
subject_key=str(task_id),
actor_type="user",
actor_id=holder_user_id,
source_ref=f"account_lease_acquired:{lease.id}",
)
db.commit()
return lease
@@ -265,6 +370,23 @@ def release_lease(
lease.status = "released"
lease.released_at = _now(now)
lease.release_reason = str(reason or "")[:64]
emit(
db,
account_id=int(lease.account_id),
event_type=EVENT_LEASE_RELEASED,
title=f"释放履约占用:{reason}",
category=CATEGORY_OPS,
detail={
"lease_id": lease.id,
"task_id": lease.batch_id,
"reason": str(reason or "")[:64],
},
source="lease",
subject_type="lease",
subject_key=str(lease.id),
actor_type="system",
source_ref=f"account_lease_released:{lease.id}",
)
db.commit()
return True
@@ -292,6 +414,24 @@ def expire_platform_fulfillment_leases(
lease.status = "expired"
lease.released_at = moment
lease.release_reason = "ttl_expired"
emit(
db,
account_id=int(lease.account_id),
event_type=EVENT_LEASE_RELEASED,
title="履约租约已过期",
category=CATEGORY_OPS,
occurred_at=moment,
detail={
"lease_id": lease.id,
"task_id": lease.batch_id,
"reason": "ttl_expired",
},
source="lease",
subject_type="lease",
subject_key=str(lease.id),
actor_type="system",
source_ref=f"account_lease_released:{lease.id}",
)
if leases:
db.commit()
return len(leases)
@@ -302,6 +442,7 @@ __all__ = [
"EXCHANGE_COOLDOWN_DAYS",
"VALIDATION_LEASE_MINUTES",
"AccountCandidate",
"capability_candidate_accounts",
"eligible_accounts",
"expire_platform_fulfillment_leases",
"has_recent_exchange",
@@ -116,7 +116,7 @@ def run_auto_allocation_once(
)
candidates = (
query.order_by(
PlatformFulfillmentTask.next_allocate_at.asc(),
PlatformFulfillmentTask.paid_at.asc(),
PlatformFulfillmentTask.id.asc(),
)
.limit(batch_size)
@@ -10,6 +10,7 @@ from threading import Lock
from typing import Any
from fastapi import HTTPException
from loguru import logger
from sqlalchemy import or_
from sqlalchemy.orm import Session
@@ -28,6 +29,12 @@ from ..account_binding import (
binding_role_from_result,
pending_binding_role_from_result,
)
from ..account_capability_service import (
AVAILABILITY_AVAILABLE,
AVAILABILITY_LIMITED,
record_account_commodity_state,
)
from ..business_events import record_account_query, record_douyu_task_started
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
from ..douyu_activity_query import activity_client, query_exchange_eligibility
from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches
@@ -39,6 +46,7 @@ from ..external_order_source import (
)
from .account_selector import (
AccountCandidate,
capability_candidate_accounts,
has_recent_exchange,
lease_account,
live_candidate_accounts,
@@ -63,6 +71,11 @@ BINDING_QR_TTL_SECONDS = int(os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "600")
AUTO_SYNC_INTERVAL_SECONDS = 900.0
DEFAULT_LIVE_CANDIDATE_LIMIT = 20
def _matching_mode() -> str:
mode = os.getenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid").strip().lower()
return mode if mode in {"legacy", "hybrid", "capability"} else "hybrid"
_SYNC_LOCK = Lock()
_AUTO_SYNC_LOCK = Lock()
_AUTO_SYNC_LAST_ATTEMPT = float("-inf")
@@ -237,6 +250,7 @@ def _upsert_order_snapshot(
task.source_snapshot_json = _jsonable(snapshot)
return task, created, False
previous_execution_status = task.execution_status
terminal = (
terminal_order
or _snapshot_value(
@@ -331,10 +345,22 @@ def _upsert_order_snapshot(
task.last_error = "订单已关闭或直播履约配置已停用"
task.next_allocate_at = None
else:
_apply_mapping(task, mapping)
if task.execution_status == "ready" and task.account_id is None:
task.next_allocate_at = _now()
elif task.account_id is not None:
# 订单快照会被重复投递。只有未分配任务从「待映射」进入「待分配」时
# 才允许改生命周期状态;已分配任务不能被快照更新打回 pending。
update_execution_status = task.account_id is None and (
previous_execution_status == "pending_mapping" or mapping is None
)
_apply_mapping(
task,
mapping,
update_execution_status=update_execution_status,
)
if task.account_id is not None:
task.next_allocate_at = None
elif task.execution_status == "ready":
if previous_execution_status != "ready" or task.next_allocate_at is None:
task.next_allocate_at = _now()
else:
task.next_allocate_at = None
after = (
@@ -662,18 +688,24 @@ def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask:
def _apply_mapping(
task: PlatformFulfillmentTask,
mapping: PlatformCommodityMapping | None,
*,
update_execution_status: bool = True,
) -> None:
if mapping is None:
if mapping is not None:
task.commodity_mapping_id = mapping.id
task.commodity_id = mapping.commodity_id
task.required_points = mapping.required_points
else:
task.commodity_mapping_id = None
task.commodity_id = ""
task.required_points = None
if not update_execution_status:
return
if mapping is None:
task.execution_status = "pending_mapping"
task.issue_code = "mapping_missing"
task.last_error = "内部 SKU 尚未配置斗鱼商品映射"
return
task.commodity_mapping_id = mapping.id
task.commodity_id = mapping.commodity_id
task.required_points = mapping.required_points
task.execution_status = "ready"
task.issue_code = ""
task.last_error = ""
@@ -780,7 +812,10 @@ def _sync_pending_tasks(
task.scope = SCOPE_ELITE
task.source_snapshot_json = _jsonable(row)
task.updated_at = _now()
if task.execution_status in {"pending_mapping", "ready"}:
if (
task.account_id is None
and task.execution_status in {"pending_mapping", "ready"}
):
_apply_mapping(task, mapping)
if task.execution_status == "ready" and task.account_id is None:
task.next_allocate_at = _now()
@@ -1262,6 +1297,7 @@ def upsert_mapping(
pending = db.query(PlatformFulfillmentTask).filter(
PlatformFulfillmentTask.internal_sku_key == sku_key,
PlatformFulfillmentTask.account_id.is_(None),
PlatformFulfillmentTask.execution_status.in_(
["pending_mapping", "ready", "manual_required"]
),
@@ -1324,19 +1360,39 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
except ValueError:
candidate_limit = DEFAULT_LIVE_CANDIDATE_LIMIT
candidate_limit = max(1, min(candidate_limit, 100))
# 缓存用于优先排序,最终是否可用仍由下面的逐个实时检测决定。
candidates = live_candidate_accounts(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
mode = _matching_mode()
capability_candidates = (
capability_candidate_accounts(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
scope=task.scope or SCOPE_ELITE,
)
if mode in {"hybrid", "capability"}
else []
)
capability_first = bool(capability_candidates)
candidates = capability_candidates
if not candidates and mode != "capability":
# hybrid 模式下能力索引为空或全部过期时,保留旧逻辑兜底。
candidates = live_candidate_accounts(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
)
diagnostics: list[dict[str, Any]] = []
qualified: list[tuple[Account, DouyuLiveAccountState]] = []
selected: AccountCandidate | None = None
selected_state: DouyuLiveAccountState | None = None
lease = None
for account in candidates:
def inspect_candidate(
account: Account,
*,
source: str,
) -> tuple[Account, DouyuLiveAccountState] | None:
live_state = refresh_douyu_account_state(
db,
account,
@@ -1344,13 +1400,40 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
rid=rid,
act_alias=act_alias,
)
reasons = live_state.blocking_reasons(commodity_id=task.commodity_id)
if has_recent_exchange(
limited = task.commodity_id in live_state.limited_ids
recent_exchange = has_recent_exchange(
db,
account_id=int(account.id),
commodity_id=task.commodity_id,
):
)
reasons = live_state.blocking_reasons(commodity_id=task.commodity_id)
if recent_exchange:
reasons.append("365 天内已有该商品兑换事件")
if live_state.ck_verdict == "valid" and not live_state.error:
try:
record_account_commodity_state(
db,
account,
commodity_id=task.commodity_id,
availability=(
AVAILABILITY_LIMITED if limited else AVAILABILITY_AVAILABLE
),
blocking_reason=(
"该账号已达此商品兑换上限" if limited else ""
),
raw_status="1" if limited else "0",
observed_at=live_state.checked_at,
source="live_check",
scope=task.scope or SCOPE_ELITE,
)
except Exception as exc: # noqa: BLE001 - 派生索引不能阻止本次选号
logger.warning(
"写入选号商品能力失败 account_id={} commodity_id={}: {}",
account.id,
task.commodity_id,
exc,
)
if reasons:
diagnostics.append(
{
@@ -1360,10 +1443,45 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
"eliteOpened": live_state.elite_opened,
"points": live_state.points,
"reasons": reasons,
"source": source,
}
)
continue
qualified.append((account, live_state))
return None
return account, live_state
def inspect_batch(
batch: list[Account],
*,
source: str,
) -> None:
# 能力索引已按成本排序,首个确认通过即可;旧兜底最多比较 3 个。
for account in batch:
inspected = inspect_candidate(account, source=source)
if inspected is None:
continue
qualified.append(inspected)
if source == "capability" or len(qualified) >= 3:
return
if capability_candidates:
inspect_batch(capability_candidates, source="capability")
elif mode != "capability":
inspect_batch(candidates, source="live")
if not qualified and capability_first and mode == "hybrid":
checked_ids = {int(account.id) for account in capability_candidates}
fallback_candidates = [
account
for account in live_candidate_accounts(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
)
if int(account.id) not in checked_ids
]
candidates = [*candidates, *fallback_candidates]
inspect_batch(fallback_candidates, source="live_fallback")
# 积分和宝典开通不淘汰账号,只影响后续处理成本。优先选已经可直接兑换的账号,
# 其次是只需充值、只需开通、两者都需要的账号。
@@ -1404,6 +1522,7 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
"eliteOpened": live_state.elite_opened,
"points": live_state.points,
"reasons": ["账号刚被其他任务占用"],
"source": "capability" if capability_first else "live",
}
)
if selected is None or selected_state is None or lease is None:
@@ -1411,7 +1530,11 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
task.next_allocate_at = _now() + timedelta(seconds=45)
task.issue_code = "no_eligible_account"
if not candidates:
task.last_error = "没有带 CK、允许自动管理且未停用的斗鱼账号"
task.last_error = (
"商品能力池暂无可用账号"
if mode == "capability"
else "没有带 CK、允许自动管理且未停用的斗鱼账号"
)
else:
summary = ";".join(
f"{item['accountName']}: {', '.join(item['reasons'][:3])}"
@@ -1428,6 +1551,8 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
"account_allocation_failed",
detail={
"candidateCount": len(candidates),
"matchingMode": mode,
"capabilityCandidates": len(capability_candidates),
"diagnostics": diagnostics,
},
)
@@ -1644,6 +1769,17 @@ async def start_binding(
)
db.add(bind_task)
db.flush()
account = db.query(Account).filter(Account.id == task.account_id).first()
if account is not None:
record_douyu_task_started(
db,
account,
task_id=int(bind_task.id),
task_type="get_bind_qr",
task_label="获取绑定二维码",
scope="elite",
actor_id=current.id,
)
task.bind_task_id = bind_task.id
task.binding_status = "preparing"
task.execution_status = "waiting_bind"
@@ -1855,6 +1991,17 @@ async def confirm_binding(
)
db.add(confirm_task)
db.flush()
account = db.query(Account).filter(Account.id == task.account_id).first()
if account is not None:
record_douyu_task_started(
db,
account,
task_id=int(confirm_task.id),
task_type="confirm_bind",
task_label="确认绑定",
scope="elite",
actor_id=current.id,
)
task.bind_task_id = confirm_task.id
task.binding_status = "confirming"
task.execution_status = "binding_confirming"
@@ -1903,6 +2050,15 @@ def refresh_exchange_eligibility(
account.elite_opened = bool(eligibility.elite_user_info.get("manual_type"))
account.points = eligibility.points
except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败
record_account_query(
db,
account,
query_type="exchange_eligibility",
title="刷新兑换资格",
ok=False,
detail={"error": str(exc)[:1000], "commodity_id": task.commodity_id},
actor_id=current.id,
)
task.execution_status = "manual_required"
task.exchange_status = "check_failed"
task.issue_code = "eligibility_check_failed"
@@ -1936,6 +2092,40 @@ def refresh_exchange_eligibility(
task.exchange_status = "eligible"
task.issue_code = ""
task.last_error = ""
record_account_commodity_state(
db,
account,
commodity_id=task.commodity_id,
availability=(
AVAILABILITY_LIMITED
if task.commodity_id in eligibility.limited_ids
else AVAILABILITY_AVAILABLE
),
blocking_reason=(
"该账号已达此商品兑换上限"
if task.commodity_id in eligibility.limited_ids
else ""
),
raw_status="1" if task.commodity_id in eligibility.limited_ids else "0",
observed_at=_now(),
source="eligibility_check",
scope=task.scope or SCOPE_ELITE,
)
record_account_query(
db,
account,
query_type="exchange_eligibility",
title="刷新兑换资格",
ok=True,
detail={
"commodity_id": task.commodity_id,
"exchange_status": task.exchange_status,
"limited": task.commodity_id in eligibility.limited_ids,
"points": account.points,
"elite_opened": account.elite_opened,
},
actor_id=current.id,
)
# 积分不足、未开通和限兑都不是流程终点:角色已经绑定,账号继续保留,
# 后续充值/开通/解除限兑后刷新资格即可。
task.execution_status = "bound"