perf(fulfillment): 优化本地能力选号查询与索引
This commit is contained in:
@@ -489,6 +489,18 @@
|
||||
"20261123_0122_execution_jobs_recharge_guard.py": {
|
||||
"revision": "20261123_0122",
|
||||
"sha256": "e3549ea76a9da00d1e6e01e11d25fbb6fca3cce64b26223a8f0352a6fbec4c7d"
|
||||
},
|
||||
"20261123_0123_capability_candidate_index.py": {
|
||||
"revision": "20261123_0123",
|
||||
"sha256": "4fc8ed0659f92a141ff383b5a5925e8b3e73aff7540b523198742971dc9b628b"
|
||||
},
|
||||
"20261123_0124_fulfillment_account_binding_sync.py": {
|
||||
"revision": "20261123_0124",
|
||||
"sha256": "33de2a57c88cfbea3219544cacaf8ff10d708639dde22322adb28ea7a2610d25"
|
||||
},
|
||||
"20261123_0125_douyu_collab_shop_aliases.py": {
|
||||
"revision": "20261123_0125",
|
||||
"sha256": "ff11ab9c735043d95504c1d52ddfeb8db04068a8027e0e1253ec45330f227bad"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""add covering index for fulfillment capability candidates.
|
||||
|
||||
Revision ID: 20261123_0123
|
||||
Revises: 20261123_0122
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261123_0123"
|
||||
down_revision: str | None = "20261123_0122"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
INDEX_NAME = "ix_account_commodity_candidate"
|
||||
REPLACED_INDEX_NAME = "ix_account_commodity_eligibility"
|
||||
|
||||
|
||||
def _indexes() -> set[str]:
|
||||
return {
|
||||
str(index["name"])
|
||||
for index in sa.inspect(op.get_bind()).get_indexes(
|
||||
"account_commodity_states"
|
||||
)
|
||||
if index.get("name")
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
indexes = _indexes()
|
||||
if INDEX_NAME not in indexes:
|
||||
op.create_index(
|
||||
INDEX_NAME,
|
||||
"account_commodity_states",
|
||||
[
|
||||
"platform",
|
||||
"scope",
|
||||
"commodity_id",
|
||||
"account_eligibility",
|
||||
"offer_state",
|
||||
"valid_until",
|
||||
"account_id",
|
||||
"last_exchange_at",
|
||||
"observed_at",
|
||||
],
|
||||
)
|
||||
if REPLACED_INDEX_NAME in indexes:
|
||||
op.drop_index(
|
||||
REPLACED_INDEX_NAME,
|
||||
table_name="account_commodity_states",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
indexes = _indexes()
|
||||
if REPLACED_INDEX_NAME not in indexes:
|
||||
op.create_index(
|
||||
REPLACED_INDEX_NAME,
|
||||
"account_commodity_states",
|
||||
[
|
||||
"platform",
|
||||
"scope",
|
||||
"commodity_id",
|
||||
"account_eligibility",
|
||||
"offer_state",
|
||||
"valid_until",
|
||||
"account_id",
|
||||
],
|
||||
)
|
||||
if INDEX_NAME in indexes:
|
||||
op.drop_index(INDEX_NAME, table_name="account_commodity_states")
|
||||
@@ -0,0 +1,104 @@
|
||||
"""backfill active fulfillment bindings confirmed through the account workbench.
|
||||
|
||||
Revision ID: 20261123_0124
|
||||
Revises: 20261123_0123
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261123_0124"
|
||||
down_revision: str | None = "20261123_0123"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
rows = bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT
|
||||
t.id AS task_id,
|
||||
a.id AS account_id,
|
||||
a.username,
|
||||
a.nickname,
|
||||
a.game_name,
|
||||
a.game_channel,
|
||||
a.role_change_available_at
|
||||
FROM platform_fulfillment_tasks AS t
|
||||
JOIN accounts AS a ON a.id = t.account_id
|
||||
JOIN account_leases AS l ON l.id = t.lease_id
|
||||
WHERE t.scope = 'elite'
|
||||
AND t.binding_status IN ('role_ready', 'confirming')
|
||||
AND t.execution_status NOT IN ('completed', 'cancelled')
|
||||
AND l.status = 'active'
|
||||
AND a.role_bind_status = 'bound'
|
||||
"""
|
||||
)
|
||||
).mappings().all()
|
||||
now = datetime.now(UTC).replace(tzinfo=None)
|
||||
for row in rows:
|
||||
task_id = int(row["task_id"])
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE platform_fulfillment_tasks
|
||||
SET binding_status = 'bound',
|
||||
execution_status = 'bound',
|
||||
issue_code = '',
|
||||
last_error = '',
|
||||
updated_at = :now
|
||||
WHERE id = :task_id
|
||||
"""
|
||||
),
|
||||
{"task_id": task_id, "now": now},
|
||||
)
|
||||
detail = {
|
||||
"accountId": int(row["account_id"]),
|
||||
"accountName": str(row["nickname"] or row["username"] or ""),
|
||||
"roleName": str(row["game_name"] or ""),
|
||||
"gameChannel": str(row["game_channel"] or ""),
|
||||
"roleChangeAvailableAt": (
|
||||
row["role_change_available_at"].isoformat()
|
||||
if row["role_change_available_at"]
|
||||
else None
|
||||
),
|
||||
"sourceTaskId": None,
|
||||
"backfilled": True,
|
||||
}
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
INSERT INTO platform_fulfillment_events (
|
||||
task_id,
|
||||
event_type,
|
||||
actor_type,
|
||||
actor_id,
|
||||
detail_json,
|
||||
created_at
|
||||
) VALUES (
|
||||
:task_id,
|
||||
'binding_synced_from_account',
|
||||
'system',
|
||||
'',
|
||||
:detail_json,
|
||||
:created_at
|
||||
)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"task_id": task_id,
|
||||
"detail_json": json.dumps(detail, ensure_ascii=False),
|
||||
"created_at": now,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""业务数据回填不回退,避免把已确认的账号重新标成待确认。"""
|
||||
@@ -0,0 +1,58 @@
|
||||
"""add manually maintained douyu collab shop aliases and original shop names.
|
||||
|
||||
Revision ID: 20261123_0125
|
||||
Revises: 20261123_0124
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261123_0125"
|
||||
down_revision: str | None = "20261123_0124"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def _columns(table: str) -> set[str]:
|
||||
return {
|
||||
str(column["name"])
|
||||
for column in sa.inspect(op.get_bind()).get_columns(table)
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
if "aliases" not in _columns("douyu_collab_shops"):
|
||||
op.add_column(
|
||||
"douyu_collab_shops",
|
||||
sa.Column("aliases", sa.JSON(), nullable=True),
|
||||
)
|
||||
if "shop_original_name" not in _columns("douyu_external_orders"):
|
||||
op.add_column(
|
||||
"douyu_external_orders",
|
||||
sa.Column(
|
||||
"shop_original_name",
|
||||
sa.String(length=128),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
)
|
||||
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE douyu_external_orders
|
||||
SET shop_original_name = shop
|
||||
WHERE shop_original_name = ''
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if "shop_original_name" in _columns("douyu_external_orders"):
|
||||
op.drop_column("douyu_external_orders", "shop_original_name")
|
||||
if "aliases" in _columns("douyu_collab_shops"):
|
||||
op.drop_column("douyu_collab_shops", "aliases")
|
||||
@@ -884,6 +884,8 @@ class DouyuCollabShop(Base):
|
||||
name: Mapped[str] = mapped_column(
|
||||
String(64), unique=True, nullable=False, index=True
|
||||
)
|
||||
# 各平台同步过来的完整店铺名/历史别名,统一映射到上面的规范简称。
|
||||
aliases: Mapped[list | None] = mapped_column(JSON, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
|
||||
is_active: Mapped[bool] = mapped_column(
|
||||
Boolean, default=True, server_default="1", index=True
|
||||
@@ -947,6 +949,10 @@ class DouyuExternalOrder(Base):
|
||||
shop: Mapped[str] = mapped_column(
|
||||
String(64), default="", server_default="", index=True
|
||||
)
|
||||
# 同步来源的原始完整店铺名;shop 存规范简称,筛选和展示不丢原值。
|
||||
shop_original_name: Mapped[str] = mapped_column(
|
||||
String(128), default="", server_default=""
|
||||
)
|
||||
owner_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("users.id"), nullable=True, index=True
|
||||
)
|
||||
@@ -2118,7 +2124,7 @@ class AccountCommodityState(Base):
|
||||
"account_id",
|
||||
),
|
||||
Index(
|
||||
"ix_account_commodity_eligibility",
|
||||
"ix_account_commodity_candidate",
|
||||
"platform",
|
||||
"scope",
|
||||
"commodity_id",
|
||||
@@ -2126,6 +2132,8 @@ class AccountCommodityState(Base):
|
||||
"offer_state",
|
||||
"valid_until",
|
||||
"account_id",
|
||||
"last_exchange_at",
|
||||
"observed_at",
|
||||
),
|
||||
Index(
|
||||
"ix_account_commodity_account",
|
||||
|
||||
@@ -86,6 +86,7 @@ def _shop_out(shop) -> dict:
|
||||
return {
|
||||
"id": int(shop.id),
|
||||
"name": shop.name,
|
||||
"aliases": list(shop.aliases or []),
|
||||
"sort_order": int(shop.sort_order or 0),
|
||||
"is_active": bool(shop.is_active),
|
||||
"remark": shop.remark or "",
|
||||
@@ -750,7 +751,13 @@ def create_collab_shop(
|
||||
current: User = Depends(require_permission("douyu:collab:edit")),
|
||||
):
|
||||
try:
|
||||
shop = collab.create_shop(db, current, name=req.name, remark=req.remark)
|
||||
shop = collab.create_shop(
|
||||
db,
|
||||
current,
|
||||
name=req.name,
|
||||
aliases=req.aliases,
|
||||
remark=req.remark,
|
||||
)
|
||||
except collab.CollabError as exc:
|
||||
raise _http_error(exc) from exc
|
||||
_publish_change(current, scope="shops", action="shop.create")
|
||||
|
||||
@@ -2608,11 +2608,13 @@ class HuyaExternalOrderAuditOut(BaseModel):
|
||||
|
||||
class DouyuCollabShopCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=64)
|
||||
aliases: list[str] = Field(default_factory=list)
|
||||
remark: str = Field("", max_length=255)
|
||||
|
||||
|
||||
class DouyuCollabShopUpdate(BaseModel):
|
||||
name: str | None = Field(None, min_length=1, max_length=64)
|
||||
aliases: list[str] | None = None
|
||||
sort_order: int | None = None
|
||||
is_active: bool | None = None
|
||||
remark: str | None = Field(None, max_length=255)
|
||||
@@ -2621,6 +2623,7 @@ class DouyuCollabShopUpdate(BaseModel):
|
||||
class DouyuCollabShopOut(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
aliases: list[str] = Field(default_factory=list)
|
||||
sort_order: int = 0
|
||||
is_active: bool = True
|
||||
remark: str = ""
|
||||
@@ -2705,7 +2708,7 @@ class DouyuCollabAccountLookupOut(BaseModel):
|
||||
|
||||
class DouyuCollabOrderCreate(BaseModel):
|
||||
order_no: str = Field(..., min_length=1, max_length=64)
|
||||
shop: str = Field("", max_length=64)
|
||||
shop: str = Field("", max_length=128)
|
||||
owner_id: int | None = None
|
||||
account_username: str = Field("", max_length=128)
|
||||
gift_name: str = Field("", max_length=128)
|
||||
@@ -2720,7 +2723,7 @@ class DouyuCollabOrderCreate(BaseModel):
|
||||
|
||||
class DouyuCollabOrderUpdate(BaseModel):
|
||||
order_no: str | None = Field(None, max_length=64)
|
||||
shop: str | None = Field(None, max_length=64)
|
||||
shop: str | None = Field(None, max_length=128)
|
||||
owner_id: int | None = None
|
||||
account_username: str | None = Field(None, max_length=128)
|
||||
gift_name: str | None = Field(None, max_length=128)
|
||||
@@ -2876,6 +2879,7 @@ class DouyuCollabOrderOut(BaseModel):
|
||||
id: int
|
||||
order_no: str
|
||||
shop: str = ""
|
||||
shop_original_name: str = ""
|
||||
owner_id: int | None = None
|
||||
owner_name: str = ""
|
||||
source_type: str = "manual"
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy import and_, func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
ARCHIVE_SCOPES: tuple[str, ...] = ("active", "archived", "all")
|
||||
@@ -25,14 +25,33 @@ def apply_order_visibility(
|
||||
void_status: str = "void",
|
||||
) -> Any:
|
||||
"""给协作台账查询统一追加归档和作废过滤。"""
|
||||
return query.filter(
|
||||
order_visibility_expr(
|
||||
model,
|
||||
archive_scope=archive_scope,
|
||||
include_void=include_void,
|
||||
void_status=void_status,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def order_visibility_expr(
|
||||
model: Any,
|
||||
*,
|
||||
archive_scope: str,
|
||||
include_void: bool,
|
||||
void_status: str = "void",
|
||||
):
|
||||
"""归档/作废可见性表达式,可嵌入精确订单号搜索的 OR 条件。"""
|
||||
scope = normalize_archive_scope(archive_scope)
|
||||
filters = []
|
||||
if scope == "active":
|
||||
query = query.filter(model.archived_at.is_(None))
|
||||
filters.append(model.archived_at.is_(None))
|
||||
elif scope == "archived":
|
||||
query = query.filter(model.archived_at.isnot(None))
|
||||
filters.append(model.archived_at.isnot(None))
|
||||
if not include_void:
|
||||
query = query.filter(model.status != void_status)
|
||||
return query
|
||||
filters.append(model.status != void_status)
|
||||
return and_(*filters)
|
||||
|
||||
|
||||
def count_archived(db: Session, model: Any) -> int:
|
||||
|
||||
@@ -19,7 +19,7 @@ from typing import Any
|
||||
from unicodedata import normalize as unicode_normalize
|
||||
|
||||
from loguru import logger
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy import and_, func, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.douyu import DouyuActivityClient
|
||||
@@ -56,7 +56,10 @@ from .account_sync_runner import WORK_STOREHOME_SYNC
|
||||
from .account_work_queue import enqueue_account_work
|
||||
from .audit_service import record_account_action, record_audit
|
||||
from .business_events import record_account_query
|
||||
from .collab_common import apply_order_visibility, count_archived
|
||||
from .collab_common import (
|
||||
count_archived,
|
||||
order_visibility_expr,
|
||||
)
|
||||
from .cookie_check_service import check_douyu_cookie
|
||||
from .douyu_account_probe import (
|
||||
ROLE_BOUND,
|
||||
@@ -80,6 +83,7 @@ from .douyu_goods_service import (
|
||||
)
|
||||
from .file_service import build_file_url
|
||||
from .platform_fulfillment.account_selector import (
|
||||
CapabilityAccount,
|
||||
acquire_account_lease,
|
||||
active_lease_for_account,
|
||||
capability_candidate_accounts,
|
||||
@@ -651,7 +655,7 @@ def recommend_accounts(
|
||||
),
|
||||
)
|
||||
now = _now()
|
||||
candidates_by_id: dict[int, Account] = {}
|
||||
candidates_by_id: dict[int, Account | CapabilityAccount] = {}
|
||||
if cid:
|
||||
for account in capability_candidate_accounts(
|
||||
db,
|
||||
@@ -1488,6 +1492,8 @@ def create_order(
|
||||
)
|
||||
|
||||
images = normalize_images(home_images)
|
||||
shop_original_name = _text(shop, max_length=128)
|
||||
shop_name = resolve_shop_name(db, shop_original_name)
|
||||
explicit_points = _to_int(required_points)
|
||||
name, cid, points = _resolve_gift(
|
||||
db,
|
||||
@@ -1497,7 +1503,8 @@ def create_order(
|
||||
)
|
||||
order = DouyuExternalOrder(
|
||||
order_no=order_text,
|
||||
shop=_text(shop, max_length=64),
|
||||
shop=shop_name[:64],
|
||||
shop_original_name=shop_original_name,
|
||||
owner_id=owner_user_id,
|
||||
account_username=_text(account_username, max_length=128),
|
||||
gift_name=name,
|
||||
@@ -1818,7 +1825,10 @@ def sync_platform_fulfillment_order(
|
||||
order.last_synced_at = now
|
||||
order.updated_by = current.id
|
||||
order.updated_at = now
|
||||
order.shop = _text(task.shop_name or task.shop_id, max_length=64)
|
||||
shop_original_name = _text(task.shop_name or task.shop_id, max_length=128)
|
||||
ensure_shops_registered(db, current, [shop_original_name])
|
||||
order.shop = resolve_shop_name(db, shop_original_name)[:64]
|
||||
order.shop_original_name = shop_original_name
|
||||
order.gift_name = gift_name
|
||||
order.commodity_id = commodity_id
|
||||
order.required_points = required_points
|
||||
@@ -2017,6 +2027,8 @@ def update_order(
|
||||
raise CollabError(
|
||||
"订单号已存在", status_code=409, code="order_no_exists"
|
||||
)
|
||||
elif field == "shop":
|
||||
new = _text(payload[field], max_length=128)
|
||||
else:
|
||||
new = _text(payload[field], max_length=512 if field == "remark" else 128)
|
||||
pending[field] = new
|
||||
@@ -2041,6 +2053,9 @@ def update_order(
|
||||
|
||||
for field, new in pending.items():
|
||||
setattr(order, field, new)
|
||||
if "shop" in pending:
|
||||
order.shop_original_name = str(pending["shop"] or "")
|
||||
order.shop = resolve_shop_name(db, order.shop_original_name)[:64]
|
||||
if "account_username" in payload and (
|
||||
order.account_id is None
|
||||
or not order.bind_game_role
|
||||
@@ -2976,23 +2991,89 @@ def query_activity_batch(
|
||||
return results
|
||||
|
||||
|
||||
def _normalize_shop_aliases(values: Any) -> list[str]:
|
||||
if not isinstance(values, (list, tuple, set)):
|
||||
return []
|
||||
aliases: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for raw in values:
|
||||
alias = _text(raw, max_length=128)
|
||||
if not alias or alias in seen:
|
||||
continue
|
||||
seen.add(alias)
|
||||
aliases.append(alias)
|
||||
return aliases
|
||||
|
||||
|
||||
def _shop_match_values(shop: DouyuCollabShop) -> list[str]:
|
||||
return [str(shop.name or ""), *list(shop.aliases or [])]
|
||||
|
||||
|
||||
def resolve_shop_name(db: Session, raw_name: str) -> str:
|
||||
"""按店铺管理中人工维护的别名映射规范简称;未知名称原样保留。"""
|
||||
name = _text(raw_name, max_length=128)
|
||||
if not name:
|
||||
return ""
|
||||
for shop in db.query(DouyuCollabShop).all():
|
||||
if name in _shop_match_values(shop):
|
||||
return str(shop.name)
|
||||
return name
|
||||
|
||||
|
||||
def _reproject_shop_orders(
|
||||
db: Session,
|
||||
shop: DouyuCollabShop,
|
||||
*,
|
||||
previous_name: str,
|
||||
previous_aliases: list[str],
|
||||
) -> None:
|
||||
"""店铺名称或手工别名变化后,重新计算受影响订单的展示简称。"""
|
||||
current_aliases = list(shop.aliases or [])
|
||||
match_values = {
|
||||
previous_name,
|
||||
str(shop.name or ""),
|
||||
*previous_aliases,
|
||||
*current_aliases,
|
||||
}
|
||||
match_values.discard("")
|
||||
if not match_values:
|
||||
return
|
||||
rows = (
|
||||
db.query(DouyuExternalOrder)
|
||||
.filter(
|
||||
or_(
|
||||
DouyuExternalOrder.shop.in_(match_values),
|
||||
DouyuExternalOrder.shop_original_name.in_(match_values),
|
||||
)
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for order in rows:
|
||||
original_name = order.shop_original_name or order.shop or ""
|
||||
resolved = resolve_shop_name(db, original_name)[:64]
|
||||
if order.shop == previous_name and original_name in (previous_name, shop.name):
|
||||
resolved = str(shop.name)[:64]
|
||||
order.shop = resolved
|
||||
|
||||
|
||||
def ensure_shops_registered(
|
||||
db: Session, current: User | None, names: list[str]
|
||||
) -> None:
|
||||
seen: set[str] = set()
|
||||
for raw in names:
|
||||
name = _text(raw, max_length=64)
|
||||
name = _text(raw, max_length=128)
|
||||
if not name or name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
exists = (
|
||||
db.query(DouyuCollabShop.id).filter(DouyuCollabShop.name == name).first()
|
||||
exists = any(
|
||||
name in _shop_match_values(shop)
|
||||
for shop in db.query(DouyuCollabShop).all()
|
||||
)
|
||||
if exists:
|
||||
continue
|
||||
db.add(
|
||||
DouyuCollabShop(
|
||||
name=name,
|
||||
name=name[:64],
|
||||
created_by=current.id if current else None,
|
||||
updated_by=current.id if current else None,
|
||||
)
|
||||
@@ -3016,7 +3097,12 @@ def get_shop(db: Session, shop_id: int) -> DouyuCollabShop:
|
||||
|
||||
|
||||
def create_shop(
|
||||
db: Session, current: User, *, name: str, remark: str = ""
|
||||
db: Session,
|
||||
current: User,
|
||||
*,
|
||||
name: str,
|
||||
aliases: Any = None,
|
||||
remark: str = "",
|
||||
) -> DouyuCollabShop:
|
||||
clean = _text(name, max_length=64)
|
||||
if not clean:
|
||||
@@ -3026,6 +3112,7 @@ def create_shop(
|
||||
raise CollabError("店铺已存在", status_code=409, code="shop_exists")
|
||||
shop = DouyuCollabShop(
|
||||
name=clean,
|
||||
aliases=_normalize_shop_aliases(aliases),
|
||||
remark=_text(remark, max_length=255),
|
||||
created_by=current.id,
|
||||
updated_by=current.id,
|
||||
@@ -3043,8 +3130,10 @@ def update_shop(
|
||||
payload: Mapping[str, Any],
|
||||
) -> DouyuCollabShop:
|
||||
old_name = shop.name
|
||||
old_aliases = list(shop.aliases or [])
|
||||
old = {
|
||||
"name": shop.name,
|
||||
"aliases": old_aliases,
|
||||
"sort_order": shop.sort_order,
|
||||
"is_active": shop.is_active,
|
||||
"remark": shop.remark,
|
||||
@@ -3064,6 +3153,8 @@ def update_shop(
|
||||
if duplicate:
|
||||
raise CollabError("店铺已存在", status_code=409, code="shop_exists")
|
||||
shop.name = name
|
||||
if "aliases" in payload:
|
||||
shop.aliases = _normalize_shop_aliases(payload.get("aliases"))
|
||||
if "sort_order" in payload:
|
||||
shop.sort_order = _to_int(payload.get("sort_order")) or 0
|
||||
if "is_active" in payload:
|
||||
@@ -3071,9 +3162,15 @@ def update_shop(
|
||||
if "remark" in payload:
|
||||
shop.remark = _text(payload.get("remark"), max_length=255)
|
||||
shop.updated_by = current.id
|
||||
if shop.name != old_name:
|
||||
db.query(DouyuExternalOrder).filter(DouyuExternalOrder.shop == old_name).update(
|
||||
{DouyuExternalOrder.shop: shop.name}, synchronize_session=False
|
||||
if (
|
||||
shop.name != old_name
|
||||
or list(shop.aliases or []) != old_aliases
|
||||
):
|
||||
_reproject_shop_orders(
|
||||
db,
|
||||
shop,
|
||||
previous_name=old_name,
|
||||
previous_aliases=old_aliases,
|
||||
)
|
||||
record_audit(
|
||||
db,
|
||||
@@ -3084,6 +3181,7 @@ def update_shop(
|
||||
"old": old,
|
||||
"new": {
|
||||
"name": shop.name,
|
||||
"aliases": list(shop.aliases or []),
|
||||
"sort_order": shop.sort_order,
|
||||
"is_active": shop.is_active,
|
||||
"remark": shop.remark,
|
||||
@@ -3446,6 +3544,7 @@ def serialize_order(
|
||||
"id": int(order.id),
|
||||
"order_no": order.order_no,
|
||||
"shop": order.shop or "",
|
||||
"shop_original_name": order.shop_original_name or order.shop or "",
|
||||
"owner_id": order.owner_id,
|
||||
"owner_name": users.get(int(order.owner_id), "") if order.owner_id else "",
|
||||
"source_type": order.source_type or "manual",
|
||||
@@ -3550,17 +3649,61 @@ def _apply_order_filters(
|
||||
keyword: str = "",
|
||||
ck_status: str = "",
|
||||
):
|
||||
query = apply_order_visibility(
|
||||
query,
|
||||
DouyuExternalOrder,
|
||||
archive_scope=archive_scope,
|
||||
include_void=include_void,
|
||||
void_status=STATUS_VOID,
|
||||
)
|
||||
search = _text(keyword)
|
||||
exact_search_filter = None
|
||||
if search:
|
||||
exact_search_filter = or_(
|
||||
DouyuExternalOrder.order_no == search,
|
||||
DouyuExternalOrder.source_platform_order_id == search,
|
||||
DouyuExternalOrder.source_order_id == search,
|
||||
DouyuExternalOrder.source_order_item_id == search,
|
||||
)
|
||||
pattern = f"%{search}%"
|
||||
fuzzy_search_filter = or_(
|
||||
DouyuExternalOrder.order_no.ilike(pattern),
|
||||
DouyuExternalOrder.account_username.ilike(pattern),
|
||||
DouyuExternalOrder.account_nickname.ilike(pattern),
|
||||
DouyuExternalOrder.bind_game_role.ilike(pattern),
|
||||
DouyuExternalOrder.shop.ilike(pattern),
|
||||
DouyuExternalOrder.remark.ilike(pattern),
|
||||
DouyuExternalOrder.source_order_id.ilike(pattern),
|
||||
DouyuExternalOrder.source_order_item_id.ilike(pattern),
|
||||
DouyuExternalOrder.source_platform_order_id.ilike(pattern),
|
||||
)
|
||||
query = query.filter(
|
||||
or_(
|
||||
exact_search_filter,
|
||||
and_(
|
||||
order_visibility_expr(
|
||||
DouyuExternalOrder,
|
||||
archive_scope=archive_scope,
|
||||
include_void=include_void,
|
||||
void_status=STATUS_VOID,
|
||||
),
|
||||
fuzzy_search_filter,
|
||||
),
|
||||
)
|
||||
)
|
||||
else:
|
||||
query = query.filter(
|
||||
order_visibility_expr(
|
||||
DouyuExternalOrder,
|
||||
archive_scope=archive_scope,
|
||||
include_void=include_void,
|
||||
void_status=STATUS_VOID,
|
||||
)
|
||||
)
|
||||
if _text(status):
|
||||
query = query.filter(DouyuExternalOrder.status == _text(status))
|
||||
status_filter = DouyuExternalOrder.status == _text(status)
|
||||
query = query.filter(
|
||||
or_(status_filter, exact_search_filter)
|
||||
if exact_search_filter is not None
|
||||
else status_filter
|
||||
)
|
||||
if _text(shop):
|
||||
query = query.filter(DouyuExternalOrder.shop == _text(shop))
|
||||
query = query.filter(
|
||||
DouyuExternalOrder.shop == resolve_shop_name(db, _text(shop))
|
||||
)
|
||||
if owner_id is not None:
|
||||
query = query.filter(DouyuExternalOrder.owner_id == int(owner_id))
|
||||
if _text(gift_name):
|
||||
@@ -3580,22 +3723,6 @@ def _apply_order_filters(
|
||||
Account.ck_check_status.in_(("", CK_UNVERIFIED)),
|
||||
)
|
||||
)
|
||||
search = _text(keyword)
|
||||
if search:
|
||||
pattern = f"%{search}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
DouyuExternalOrder.order_no.ilike(pattern),
|
||||
DouyuExternalOrder.account_username.ilike(pattern),
|
||||
DouyuExternalOrder.account_nickname.ilike(pattern),
|
||||
DouyuExternalOrder.bind_game_role.ilike(pattern),
|
||||
DouyuExternalOrder.shop.ilike(pattern),
|
||||
DouyuExternalOrder.remark.ilike(pattern),
|
||||
DouyuExternalOrder.source_order_id.ilike(pattern),
|
||||
DouyuExternalOrder.source_order_item_id.ilike(pattern),
|
||||
DouyuExternalOrder.source_platform_order_id.ilike(pattern),
|
||||
)
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
|
||||
@@ -43,6 +43,16 @@ if TYPE_CHECKING:
|
||||
DOUYU_PAYMENT_POLL_SECONDS = 600
|
||||
DOUYU_PAYMENT_POLL_INTERVAL = 5
|
||||
|
||||
AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES = frozenset(
|
||||
{
|
||||
"create_gold_qr",
|
||||
"donate_elite_gift",
|
||||
"create_elite_qr",
|
||||
"confirm_bind",
|
||||
"query_game_name",
|
||||
}
|
||||
)
|
||||
|
||||
# 走代理的任务类型:写操作/消耗类(兑换、锁单、支付、开通、充值、送礼)。
|
||||
# 查询/刷新/绑定/扫码等读操作始终直连——它们不怕 IP 频控,走代理只会浪费代理额度。
|
||||
DOUYU_PROXY_TASK_TYPES = {
|
||||
@@ -255,6 +265,40 @@ class DouyuBatchRunnerCore:
|
||||
"[douyu] 同步直播账号履约状态失败: task_id={}", douyu_task_id
|
||||
)
|
||||
|
||||
def _refresh_platform_exchange_eligibility(
|
||||
self,
|
||||
douyu_task_id: int,
|
||||
*,
|
||||
enabled: bool,
|
||||
) -> None:
|
||||
"""账号积分/宝典变化后,自动刷新当前履约任务的兑换投影。"""
|
||||
if not enabled:
|
||||
return
|
||||
try:
|
||||
from ..database import WorkerSessionLocal
|
||||
from .platform_fulfillment.service import (
|
||||
refresh_active_exchange_eligibility_for_account,
|
||||
)
|
||||
|
||||
refresh_db = WorkerSessionLocal()
|
||||
try:
|
||||
task = refresh_db.get(DouyuTask, int(douyu_task_id))
|
||||
if task is None or task.status != "success":
|
||||
return
|
||||
refresh_active_exchange_eligibility_for_account(
|
||||
refresh_db,
|
||||
account_id=int(task.account_id),
|
||||
scope=str(task.handbook_scope or "elite"),
|
||||
actor_id=int(task.created_by),
|
||||
)
|
||||
finally:
|
||||
refresh_db.close()
|
||||
except Exception: # noqa: BLE001 - 自动刷新不能覆盖任务执行结果
|
||||
logger.exception(
|
||||
"[douyu] 自动刷新直播履约兑换资格失败: task_id={}",
|
||||
douyu_task_id,
|
||||
)
|
||||
|
||||
def _sync_platform_fulfillment_operation(
|
||||
self,
|
||||
db: Session,
|
||||
@@ -285,8 +329,13 @@ class DouyuBatchRunnerCore:
|
||||
message: str,
|
||||
result: dict | None = None,
|
||||
) -> None:
|
||||
from .platform_fulfillment.service import requires_account_binding_sync
|
||||
|
||||
task_id = int(task.id)
|
||||
has_platform_task = task.platform_task_id is not None
|
||||
sync_platform_fulfillment = has_platform_task or requires_account_binding_sync(
|
||||
task.task_type
|
||||
)
|
||||
task.status = status
|
||||
task.message = message[:512]
|
||||
if status in {"success", "failed", "error", "stopped"}:
|
||||
@@ -352,7 +401,17 @@ class DouyuBatchRunnerCore:
|
||||
logger.exception(
|
||||
"[douyu] 写入账号任务结果事件失败: task_id={}", task.id
|
||||
)
|
||||
self._sync_platform_fulfillment(task_id, enabled=has_platform_task)
|
||||
self._sync_platform_fulfillment(
|
||||
task_id,
|
||||
enabled=sync_platform_fulfillment,
|
||||
)
|
||||
self._refresh_platform_exchange_eligibility(
|
||||
task_id,
|
||||
enabled=(
|
||||
status == "success"
|
||||
and task.task_type in AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES
|
||||
),
|
||||
)
|
||||
|
||||
def _schedule_payment_poll(
|
||||
self,
|
||||
|
||||
@@ -64,8 +64,38 @@ class AccountCandidate:
|
||||
class CapabilityCandidate:
|
||||
"""一个新鲜能力快照及其对应账号,供本地零外部请求选号。"""
|
||||
|
||||
account: Account
|
||||
state: AccountCommodityState
|
||||
account: CapabilityAccount
|
||||
state: CapabilityState
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapabilityAccount:
|
||||
"""能力选号实际需要的账号字段,不加载 CK / JSON 等大列。"""
|
||||
|
||||
id: int
|
||||
username: str
|
||||
nickname: str
|
||||
uid: str
|
||||
points: int | None
|
||||
gold_balance: int | None
|
||||
points_expire_at: datetime | None
|
||||
role_change_available_at: datetime | None
|
||||
elite_opened: bool | None
|
||||
role_bind_status: str
|
||||
ck_check_status: str
|
||||
game_name: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapabilityState:
|
||||
"""选号排序之后才需要的能力快照详情。"""
|
||||
|
||||
account_eligibility: str
|
||||
offer_state: str
|
||||
observed_at: datetime | None
|
||||
available_from: datetime | None
|
||||
valid_until: datetime | None
|
||||
blocking_reason: str
|
||||
|
||||
|
||||
def _now(now: datetime | None = None) -> datetime:
|
||||
@@ -251,7 +281,24 @@ def _capability_candidate_query(
|
||||
allow_before_open=allow_before_open,
|
||||
)
|
||||
return (
|
||||
db.query(Account, AccountCommodityState)
|
||||
db.query(
|
||||
Account.id.label("account_id"),
|
||||
Account.username.label("account_username"),
|
||||
Account.nickname.label("account_nickname"),
|
||||
Account.uid.label("account_uid"),
|
||||
Account.points.label("account_points"),
|
||||
Account.gold_balance.label("account_gold_balance"),
|
||||
Account.points_expire_at.label("account_points_expire_at"),
|
||||
Account.role_change_available_at.label(
|
||||
"account_role_change_available_at"
|
||||
),
|
||||
Account.elite_opened.label("account_elite_opened"),
|
||||
Account.role_bind_status.label("account_role_bind_status"),
|
||||
Account.ck_check_status.label("account_ck_check_status"),
|
||||
Account.game_name.label("account_game_name"),
|
||||
AccountCommodityState.offer_state.label("state_offer_state"),
|
||||
AccountCommodityState.observed_at.label("state_observed_at"),
|
||||
)
|
||||
.join(
|
||||
AccountCommodityState,
|
||||
AccountCommodityState.account_id == Account.id,
|
||||
@@ -315,10 +362,67 @@ def capability_candidate_rows(
|
||||
)
|
||||
if query is None:
|
||||
return []
|
||||
return [
|
||||
CapabilityCandidate(account=account, state=state)
|
||||
for account, state in query.all()
|
||||
]
|
||||
rows = query.all()
|
||||
if not rows:
|
||||
return []
|
||||
account_ids = [int(row.account_id) for row in rows]
|
||||
state_rows = (
|
||||
db.query(
|
||||
AccountCommodityState.account_id,
|
||||
AccountCommodityState.account_eligibility,
|
||||
AccountCommodityState.offer_state,
|
||||
AccountCommodityState.observed_at,
|
||||
AccountCommodityState.available_from,
|
||||
AccountCommodityState.valid_until,
|
||||
AccountCommodityState.blocking_reason,
|
||||
)
|
||||
.filter(
|
||||
AccountCommodityState.account_id.in_(account_ids),
|
||||
AccountCommodityState.platform == "douyu",
|
||||
AccountCommodityState.scope == scope,
|
||||
AccountCommodityState.commodity_id == commodity_id.strip(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
states = {
|
||||
int(row.account_id): CapabilityState(
|
||||
account_eligibility=str(row.account_eligibility or ""),
|
||||
offer_state=str(row.offer_state or ""),
|
||||
observed_at=row.observed_at,
|
||||
available_from=row.available_from,
|
||||
valid_until=row.valid_until,
|
||||
blocking_reason=str(row.blocking_reason or ""),
|
||||
)
|
||||
for row in state_rows
|
||||
}
|
||||
candidates: list[CapabilityCandidate] = []
|
||||
for row in rows:
|
||||
account_id = int(row.account_id)
|
||||
state = states.get(account_id)
|
||||
if state is None:
|
||||
continue
|
||||
candidates.append(
|
||||
CapabilityCandidate(
|
||||
account=CapabilityAccount(
|
||||
id=account_id,
|
||||
username=str(row.account_username or ""),
|
||||
nickname=str(row.account_nickname or ""),
|
||||
uid=str(row.account_uid or ""),
|
||||
points=row.account_points,
|
||||
gold_balance=row.account_gold_balance,
|
||||
points_expire_at=row.account_points_expire_at,
|
||||
role_change_available_at=(
|
||||
row.account_role_change_available_at
|
||||
),
|
||||
elite_opened=row.account_elite_opened,
|
||||
role_bind_status=str(row.account_role_bind_status or ""),
|
||||
ck_check_status=str(row.account_ck_check_status or ""),
|
||||
game_name=str(row.account_game_name or ""),
|
||||
),
|
||||
state=state,
|
||||
)
|
||||
)
|
||||
return candidates
|
||||
|
||||
|
||||
def capability_candidate_accounts(
|
||||
@@ -330,7 +434,7 @@ def capability_candidate_accounts(
|
||||
limit: int = 20,
|
||||
now: datetime | None = None,
|
||||
allow_before_open: bool = False,
|
||||
) -> list[Account]:
|
||||
) -> list[CapabilityAccount]:
|
||||
"""从新鲜的商品能力索引读取候选账号,不产生外部请求。"""
|
||||
return [
|
||||
candidate.account
|
||||
@@ -680,6 +784,7 @@ __all__ = [
|
||||
"EXCHANGE_COOLDOWN_DAYS",
|
||||
"VALIDATION_LEASE_MINUTES",
|
||||
"AccountCandidate",
|
||||
"CapabilityAccount",
|
||||
"acquire_account_lease",
|
||||
"active_lease_for_account",
|
||||
"capability_candidate_accounts",
|
||||
|
||||
@@ -44,6 +44,20 @@ from .runtime import (
|
||||
)
|
||||
from .views import get_task_detail
|
||||
|
||||
BINDING_SYNC_TASK_TYPES = frozenset(
|
||||
{
|
||||
"get_bind_qr",
|
||||
"query_game_name",
|
||||
"confirm_bind",
|
||||
"prepare_esports_bind",
|
||||
"query_esports_game_name",
|
||||
"confirm_esports_bind",
|
||||
"prepare_xpd_bind",
|
||||
"query_xpd_game_name",
|
||||
"confirm_xpd_bind",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def start_binding_sync(
|
||||
db: Session,
|
||||
@@ -277,7 +291,86 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int:
|
||||
]
|
||||
for task_id in task_ids:
|
||||
refresh_binding(db, task_id=task_id)
|
||||
return len(task_ids)
|
||||
douyu_task = db.get(DouyuTask, int(douyu_task_id))
|
||||
if douyu_task is None or douyu_task.task_type not in BINDING_SYNC_TASK_TYPES:
|
||||
return len(task_ids)
|
||||
return len(task_ids) + sync_active_task_from_account_binding(
|
||||
db,
|
||||
account_id=int(douyu_task.account_id),
|
||||
scope=str(douyu_task.handbook_scope or ""),
|
||||
source_task_id=int(douyu_task.id),
|
||||
)
|
||||
|
||||
|
||||
def sync_active_task_from_account_binding(
|
||||
db: Session,
|
||||
*,
|
||||
account_id: int,
|
||||
scope: str,
|
||||
source_task_id: int | None = None,
|
||||
) -> int:
|
||||
"""账号权威绑定已确认时,把当前活跃履约任务同步到 bound。
|
||||
|
||||
精英宝典工作台发出的确认任务不挂在履约任务上,因此不能只看
|
||||
``PlatformFulfillmentTask.bind_task_id``。账号上的绑定状态才是最终事实。
|
||||
只在任务已经识别出待确认角色后同步,避免把账号历史绑定误当成当前订单结果。
|
||||
"""
|
||||
if scope != "elite":
|
||||
return 0
|
||||
account = db.get(Account, int(account_id))
|
||||
if account is None or account.role_bind_status != "bound":
|
||||
return 0
|
||||
task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.account_id == int(account_id),
|
||||
PlatformFulfillmentTask.scope == "elite",
|
||||
PlatformFulfillmentTask.binding_status.in_(("role_ready", "confirming")),
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
("completed", "cancelled")
|
||||
),
|
||||
AccountLease.status == "active",
|
||||
)
|
||||
.order_by(
|
||||
PlatformFulfillmentTask.updated_at.desc(),
|
||||
PlatformFulfillmentTask.id.desc(),
|
||||
)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if task is None:
|
||||
return 0
|
||||
task.binding_status = "bound"
|
||||
task.execution_status = "bound"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
task.updated_at = _now()
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"binding_synced_from_account",
|
||||
detail={
|
||||
"accountId": int(account.id),
|
||||
"accountName": account.nickname or account.username,
|
||||
"roleName": str(account.game_name or ""),
|
||||
"gameChannel": str(account.game_channel or ""),
|
||||
"roleChangeAvailableAt": (
|
||||
account.role_change_available_at.isoformat()
|
||||
if account.role_change_available_at
|
||||
else None
|
||||
),
|
||||
"sourceTaskId": source_task_id,
|
||||
},
|
||||
)
|
||||
_apply_task_lease_policy(db, task)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
db.commit()
|
||||
return 1
|
||||
|
||||
|
||||
def requires_account_binding_sync(task_type: str) -> bool:
|
||||
return str(task_type or "") in BINDING_SYNC_TASK_TYPES
|
||||
|
||||
|
||||
def reconcile_binding_state_outbox(
|
||||
|
||||
@@ -185,7 +185,12 @@ def reset_task_binding(
|
||||
|
||||
|
||||
def refresh_exchange_eligibility(
|
||||
db: Session, *, task_id: int, current: User
|
||||
db: Session,
|
||||
*,
|
||||
task_id: int,
|
||||
current: User,
|
||||
automatic: bool = False,
|
||||
mark_failed_on_error: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
task = _load_task(db, task_id)
|
||||
if task.binding_status != "bound":
|
||||
@@ -231,20 +236,28 @@ def refresh_exchange_eligibility(
|
||||
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"
|
||||
task.last_error = str(exc)
|
||||
task.updated_at = _now()
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"eligibility_check_failed",
|
||||
actor_type="user",
|
||||
actor_id=current.id,
|
||||
detail={"error": str(exc)},
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
if mark_failed_on_error:
|
||||
task.execution_status = "manual_required"
|
||||
task.exchange_status = "check_failed"
|
||||
task.issue_code = "eligibility_check_failed"
|
||||
task.last_error = str(exc)
|
||||
task.updated_at = _now()
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"eligibility_check_failed",
|
||||
actor_type="user",
|
||||
actor_id=current.id,
|
||||
detail={"error": str(exc)},
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
else:
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"eligibility_auto_refresh_failed",
|
||||
detail={"error": str(exc), "automatic": True},
|
||||
)
|
||||
db.commit()
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
@@ -366,11 +379,12 @@ def refresh_exchange_eligibility(
|
||||
db,
|
||||
task.id,
|
||||
"exchange_eligibility_checked",
|
||||
actor_type="user",
|
||||
actor_id=current.id,
|
||||
actor_type="system" if automatic else "user",
|
||||
actor_id=None if automatic else current.id,
|
||||
detail={
|
||||
"exchangeStatus": task.exchange_status,
|
||||
"limitedCount": len(limited_ids),
|
||||
"automatic": automatic,
|
||||
},
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
@@ -378,6 +392,58 @@ def refresh_exchange_eligibility(
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
|
||||
def refresh_active_exchange_eligibility_for_account(
|
||||
db: Session,
|
||||
*,
|
||||
account_id: int,
|
||||
scope: str,
|
||||
actor_id: int | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""账号资产变化后,自动刷新当前活动履约任务的兑换投影。
|
||||
|
||||
自动刷新失败只记录时间线,不把已绑定任务打成人工;运营仍可手动重试。
|
||||
"""
|
||||
task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.account_id == int(account_id),
|
||||
PlatformFulfillmentTask.scope == str(scope or SCOPE_ELITE),
|
||||
PlatformFulfillmentTask.binding_status == "bound",
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
("completed", "cancelled")
|
||||
),
|
||||
AccountLease.status == "active",
|
||||
)
|
||||
.order_by(
|
||||
PlatformFulfillmentTask.updated_at.desc(),
|
||||
PlatformFulfillmentTask.id.desc(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if task is None:
|
||||
return None
|
||||
actor = db.get(User, int(actor_id)) if actor_id is not None else None
|
||||
if actor is None and task.operator_id is not None:
|
||||
actor = db.get(User, int(task.operator_id))
|
||||
if actor is None:
|
||||
actor = (
|
||||
db.query(User)
|
||||
.filter(User.role == "super_admin", User.is_active.is_(True))
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if actor is None:
|
||||
return None
|
||||
return refresh_exchange_eligibility(
|
||||
db,
|
||||
task_id=int(task.id),
|
||||
current=actor,
|
||||
automatic=True,
|
||||
mark_failed_on_error=False,
|
||||
)
|
||||
|
||||
|
||||
def complete_manual_exchange(
|
||||
db: Session,
|
||||
*,
|
||||
|
||||
@@ -31,8 +31,10 @@ from .binding import ( # noqa: F401
|
||||
confirm_binding_sync,
|
||||
reconcile_binding_state_outbox,
|
||||
refresh_binding,
|
||||
requires_account_binding_sync,
|
||||
start_binding,
|
||||
start_binding_sync,
|
||||
sync_active_task_from_account_binding,
|
||||
sync_task_from_binding_runner,
|
||||
)
|
||||
from .binding_status import ( # noqa: F401
|
||||
@@ -68,6 +70,7 @@ from .lifecycle import (
|
||||
complete_manual_exchange,
|
||||
mark_manual_required,
|
||||
prepare_platform_task_for_collab_takeover,
|
||||
refresh_active_exchange_eligibility_for_account,
|
||||
refresh_exchange_eligibility,
|
||||
release_task_account,
|
||||
release_task_to_manual,
|
||||
@@ -155,15 +158,18 @@ __all__ = [
|
||||
"reconcile_binding_state_outbox",
|
||||
"record_douyu_operation_result",
|
||||
"record_douyu_operation_started",
|
||||
"refresh_active_exchange_eligibility_for_account",
|
||||
"refresh_binding",
|
||||
"refresh_exchange_eligibility",
|
||||
"release_task_account",
|
||||
"release_task_to_manual",
|
||||
"requires_account_binding_sync",
|
||||
"reset_task_binding",
|
||||
"restore_cancelled_task",
|
||||
"restore_mapping",
|
||||
"set_mapping_enabled",
|
||||
"start_binding",
|
||||
"sync_active_task_from_account_binding",
|
||||
"sync_order_item_ids",
|
||||
"sync_order_snapshot",
|
||||
"sync_pending_tasks",
|
||||
|
||||
@@ -362,6 +362,9 @@ def _task_out(
|
||||
)
|
||||
collab_order = resolved.collab_orders.get(int(task.id))
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
account_binding_confirmed = bool(
|
||||
account is not None and account.role_bind_status == "bound"
|
||||
)
|
||||
effective_issue = _effective_binding_issue(task, bind_task, bind_result)
|
||||
effective_last_error = _effective_task_message(task, effective_issue)
|
||||
exchange_task_id = task.exchange_task_id
|
||||
@@ -377,7 +380,11 @@ def _task_out(
|
||||
.scalar()
|
||||
)
|
||||
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
||||
pending_role = pending_binding_role_from_result(bind_result)
|
||||
pending_role = (
|
||||
""
|
||||
if account_binding_confirmed or task.binding_status == "bound"
|
||||
else pending_binding_role_from_result(bind_result)
|
||||
)
|
||||
sale_mode = classification.normalize_sale_mode(task.sale_mode)
|
||||
availability = classification.availability_state(
|
||||
sale_mode=sale_mode,
|
||||
@@ -477,12 +484,19 @@ def _task_out(
|
||||
"status": bind_task.status,
|
||||
"message": bind_task.message,
|
||||
"qrUrl": str(bind_result.get("url") or "") if include_qr else "",
|
||||
"roleName": binding_role_from_result(bind_result),
|
||||
"roleName": (
|
||||
str(account.game_name or "")
|
||||
if account_binding_confirmed and account is not None
|
||||
else binding_role_from_result(bind_result)
|
||||
),
|
||||
"areaName": str(bind_result.get("area_name") or ""),
|
||||
"platName": str(bind_result.get("plat_name") or ""),
|
||||
"bindPhase": str(bind_result.get("bind_phase") or ""),
|
||||
"bindReadyForConfirm": bool(pending_role),
|
||||
"bindConfirmed": bool(bind_result.get("bind_confirmed")),
|
||||
"bindConfirmed": bool(
|
||||
account_binding_confirmed
|
||||
or bind_result.get("bind_confirmed")
|
||||
),
|
||||
}
|
||||
if bind_task
|
||||
else None
|
||||
@@ -620,7 +634,15 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||
else None
|
||||
)
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
pending_role = pending_binding_role_from_result(bind_result)
|
||||
account = db.get(Account, int(task.account_id)) if task.account_id else None
|
||||
account_binding_confirmed = bool(
|
||||
account is not None and account.role_bind_status == "bound"
|
||||
)
|
||||
pending_role = (
|
||||
""
|
||||
if account_binding_confirmed or task.binding_status == "bound"
|
||||
else pending_binding_role_from_result(bind_result)
|
||||
)
|
||||
effective_issue = _effective_binding_issue(task, bind_task, bind_result)
|
||||
lease = (
|
||||
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||
@@ -657,11 +679,18 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||
"qrUrl": str(bind_result.get("url") or ""),
|
||||
"qrGeneratedAt": str(bind_result.get("qr_generated_at") or ""),
|
||||
"qrExpiresAt": str(bind_result.get("qr_expires_at") or ""),
|
||||
"roleName": binding_role_from_result(bind_result),
|
||||
"roleName": (
|
||||
str(account.game_name or "")
|
||||
if account_binding_confirmed and account is not None
|
||||
else binding_role_from_result(bind_result)
|
||||
),
|
||||
"areaName": str(bind_result.get("area_name") or ""),
|
||||
"platName": str(bind_result.get("plat_name") or ""),
|
||||
"bindReadyForConfirm": (bool(pending_role) and not binding_failed),
|
||||
"bindConfirmed": bool(bind_result.get("bind_confirmed")) and binding_confirmed,
|
||||
"bindConfirmed": bool(
|
||||
binding_confirmed
|
||||
and (account_binding_confirmed or bind_result.get("bind_confirmed"))
|
||||
),
|
||||
"queueState": queue_state,
|
||||
"retryAfterMs": retry_after_ms,
|
||||
"queueLane": bind_task.queue_lane if bind_task else "",
|
||||
|
||||
Reference in New Issue
Block a user