feat(fulfillment): 支持共享账号操作并完善时间线
This commit is contained in:
@@ -395,6 +395,9 @@ class TestEventsCategoryFilter(_Base):
|
|||||||
assert item["category"] == svc.CATEGORY_BUSINESS
|
assert item["category"] == svc.CATEGORY_BUSINESS
|
||||||
assert item["subject_key"] == "sku-1"
|
assert item["subject_key"] == "sku-1"
|
||||||
assert item["actor_id"] == self.admin.id
|
assert item["actor_id"] == self.admin.id
|
||||||
|
assert item["actor_name"] == "act-admin"
|
||||||
|
assert item["actor_role"] == "super_admin"
|
||||||
|
assert item["actor_role_label"] == "超级管理员"
|
||||||
|
|
||||||
|
|
||||||
class TestBatchDeleteRecordsIds(_Base):
|
class TestBatchDeleteRecordsIds(_Base):
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ class TestConstructors(_Base):
|
|||||||
amount=100,
|
amount=100,
|
||||||
channel="wechat_qr",
|
channel="wechat_qr",
|
||||||
douyu_uid="u1",
|
douyu_uid="u1",
|
||||||
|
actor_id=self.user.id,
|
||||||
)
|
)
|
||||||
is True
|
is True
|
||||||
)
|
)
|
||||||
@@ -73,6 +74,8 @@ class TestConstructors(_Base):
|
|||||||
assert event.source_ref == "douyu_task:101"
|
assert event.source_ref == "douyu_task:101"
|
||||||
assert event.detail["channel"] == "wechat_qr"
|
assert event.detail["channel"] == "wechat_qr"
|
||||||
assert event.detail["confirmed"] is True
|
assert event.detail["confirmed"] is True
|
||||||
|
assert event.actor_type == "user"
|
||||||
|
assert event.actor_id == self.user.id
|
||||||
|
|
||||||
def test_recharge_without_amount_still_records(self):
|
def test_recharge_without_amount_still_records(self):
|
||||||
"""金额拿不到时宁可记一条金额为空的事件,也不要凭空编一个数字。"""
|
"""金额拿不到时宁可记一条金额为空的事件,也不要凭空编一个数字。"""
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
"""验证 DouyuTask 的 account_assigned_to 字段与任务查询优化。"""
|
"""验证 DouyuTask 的 account_assigned_to 字段与任务查询优化。"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from tests.support.db import init_test_schema, make_test_session
|
from tests.support.db import init_test_schema, make_test_session
|
||||||
from web.backend.models import Account, DouyuTask, User
|
from web.backend.models import Account, DouyuTask, PlatformFulfillmentTask, User
|
||||||
from web.backend.routers.douyu import _visible_tasks_query
|
from web.backend.routers.douyu import (
|
||||||
|
_require_task_account_access,
|
||||||
|
_visible_tasks_query,
|
||||||
|
)
|
||||||
from web.backend.services.douyu_service import create_douyu_planned_tasks
|
from web.backend.services.douyu_service import create_douyu_planned_tasks
|
||||||
|
|
||||||
|
|
||||||
@@ -67,13 +72,12 @@ def test_douyu_task_assigned_to_flow():
|
|||||||
assert task_map[acc_1.id].account_assigned_to == user_a.id
|
assert task_map[acc_1.id].account_assigned_to == user_a.id
|
||||||
assert task_map[acc_2.id].account_assigned_to == user_b.id
|
assert task_map[acc_2.id].account_assigned_to == user_b.id
|
||||||
|
|
||||||
# 2. 验证 _visible_tasks_query 能够精准过滤所属客服
|
# 2. 客服能看到自己创建的任务;被分配账号的客服也能看到。
|
||||||
query_a = _visible_tasks_query(db, user_a).filter(
|
query_a = _visible_tasks_query(db, user_a).filter(
|
||||||
DouyuTask.batch_id == batch_id
|
DouyuTask.batch_id == batch_id
|
||||||
)
|
)
|
||||||
visible_a = query_a.all()
|
visible_a = query_a.all()
|
||||||
assert len(visible_a) == 1
|
assert {row.account_id for row in visible_a} == {acc_1.id, acc_2.id}
|
||||||
assert visible_a[0].account_id == acc_1.id
|
|
||||||
|
|
||||||
query_b = _visible_tasks_query(db, user_b).filter(
|
query_b = _visible_tasks_query(db, user_b).filter(
|
||||||
DouyuTask.batch_id == batch_id
|
DouyuTask.batch_id == batch_id
|
||||||
@@ -99,3 +103,92 @@ def test_douyu_task_assigned_to_flow():
|
|||||||
finally:
|
finally:
|
||||||
db.rollback()
|
db.rollback()
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_platform_task_context_allows_shared_account_operation():
|
||||||
|
init_test_schema()
|
||||||
|
db: Session = make_test_session()
|
||||||
|
try:
|
||||||
|
owner = User(
|
||||||
|
username="ctx-owner",
|
||||||
|
password_hash="h",
|
||||||
|
role="support",
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
operator = User(
|
||||||
|
username="ctx-operator",
|
||||||
|
password_hash="h",
|
||||||
|
role="support",
|
||||||
|
custom_permissions=[
|
||||||
|
"douyu:task",
|
||||||
|
"account:view_assigned",
|
||||||
|
"platform_fulfillment:use",
|
||||||
|
],
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
db.add_all([owner, operator])
|
||||||
|
db.flush()
|
||||||
|
account = Account(
|
||||||
|
username="ctx-shared-account",
|
||||||
|
password="p",
|
||||||
|
email="ctx@test.com",
|
||||||
|
email_password="p",
|
||||||
|
cookie="acf_uid=1; acf_auth=x",
|
||||||
|
assigned_to=owner.id,
|
||||||
|
)
|
||||||
|
db.add(account)
|
||||||
|
db.flush()
|
||||||
|
task = PlatformFulfillmentTask(
|
||||||
|
source_order_id="ctx-order",
|
||||||
|
source_order_item_id="ctx-item",
|
||||||
|
platform_order_id="ctx-platform-order",
|
||||||
|
account_id=account.id,
|
||||||
|
execution_status="allocated",
|
||||||
|
)
|
||||||
|
db.add(task)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException) as exc_info:
|
||||||
|
_require_task_account_access(db, operator, [account.id])
|
||||||
|
assert exc_info.value.status_code == 403
|
||||||
|
|
||||||
|
_require_task_account_access(
|
||||||
|
db,
|
||||||
|
operator,
|
||||||
|
[account.id],
|
||||||
|
platform_task_id=task.id,
|
||||||
|
)
|
||||||
|
batch_id, count = create_douyu_planned_tasks(
|
||||||
|
db,
|
||||||
|
[account.id],
|
||||||
|
"query_elite_status",
|
||||||
|
"elite",
|
||||||
|
operator.id,
|
||||||
|
platform_task_id=task.id,
|
||||||
|
)
|
||||||
|
assert count == 1
|
||||||
|
assert (
|
||||||
|
db.query(DouyuTask).filter(DouyuTask.batch_id == batch_id).one().platform_task_id
|
||||||
|
== task.id
|
||||||
|
)
|
||||||
|
|
||||||
|
other = Account(
|
||||||
|
username="ctx-other-account",
|
||||||
|
password="p",
|
||||||
|
email="ctx-other@test.com",
|
||||||
|
email_password="p",
|
||||||
|
cookie="acf_uid=2; acf_auth=x",
|
||||||
|
assigned_to=owner.id,
|
||||||
|
)
|
||||||
|
db.add(other)
|
||||||
|
db.commit()
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
_require_task_account_access(
|
||||||
|
db,
|
||||||
|
operator,
|
||||||
|
[other.id],
|
||||||
|
platform_task_id=task.id,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
db.rollback()
|
||||||
|
db.close()
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
|||||||
PROJECT_ROOT = TESTS_DIR.parent
|
PROJECT_ROOT = TESTS_DIR.parent
|
||||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||||
|
|
||||||
HEAD_REVISION = "20261118_0095"
|
HEAD_REVISION = "20261118_0096"
|
||||||
|
|
||||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||||
EXTRA_INDEXES = (
|
EXTRA_INDEXES = (
|
||||||
|
|||||||
@@ -743,6 +743,62 @@ class TestFulfillmentCollabSync(_Base):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TestDouyuOperationTimeline(_Base):
|
||||||
|
def test_operation_start_and_result_are_written_once(self):
|
||||||
|
task = self.task()
|
||||||
|
account = self.account("operation-timeline-account")
|
||||||
|
task.account_id = account.id
|
||||||
|
self.session.commit()
|
||||||
|
douyu_task = DouyuTask(
|
||||||
|
batch_id="platform-operation",
|
||||||
|
account_id=account.id,
|
||||||
|
account_assigned_to=account.assigned_to,
|
||||||
|
task_type="create_gold_qr",
|
||||||
|
handbook_scope="elite",
|
||||||
|
status="planned",
|
||||||
|
created_by=self.admin_id,
|
||||||
|
platform_task_id=task.id,
|
||||||
|
)
|
||||||
|
self.session.add(douyu_task)
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
service.record_douyu_operation_started(
|
||||||
|
self.session,
|
||||||
|
task,
|
||||||
|
current=self.admin,
|
||||||
|
batch_id=douyu_task.batch_id,
|
||||||
|
task_type=douyu_task.task_type,
|
||||||
|
douyu_task_ids=[douyu_task.id],
|
||||||
|
payload={"amount": 18},
|
||||||
|
)
|
||||||
|
service.record_douyu_operation_result(
|
||||||
|
self.session,
|
||||||
|
douyu_task,
|
||||||
|
status="success",
|
||||||
|
message="充值鱼翅成功",
|
||||||
|
)
|
||||||
|
service.record_douyu_operation_result(
|
||||||
|
self.session,
|
||||||
|
douyu_task,
|
||||||
|
status="success",
|
||||||
|
message="充值鱼翅成功",
|
||||||
|
)
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
detail = service.get_task_detail(self.session, task.id)
|
||||||
|
operation_events = [
|
||||||
|
event
|
||||||
|
for event in detail["events"]
|
||||||
|
if event["eventType"].startswith("douyu_operation_")
|
||||||
|
]
|
||||||
|
assert [event["eventType"] for event in operation_events] == [
|
||||||
|
"douyu_operation_succeeded",
|
||||||
|
"douyu_operation_started",
|
||||||
|
]
|
||||||
|
assert operation_events[0]["detail"]["douyuTaskId"] == douyu_task.id
|
||||||
|
assert operation_events[1]["detail"]["batchId"] == douyu_task.batch_id
|
||||||
|
|
||||||
|
|
||||||
class TestSnapshotSync(_Base):
|
class TestSnapshotSync(_Base):
|
||||||
def snapshot(self, **overrides):
|
def snapshot(self, **overrides):
|
||||||
payload = {
|
payload = {
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""关联斗鱼任务与直播履约任务上下文。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "20261118_0096"
|
||||||
|
down_revision: str | None = "20261118_0095"
|
||||||
|
branch_labels: str | None = None
|
||||||
|
depends_on: str | None = None
|
||||||
|
|
||||||
|
TABLE = "douyu_tasks"
|
||||||
|
COLUMN = "platform_task_id"
|
||||||
|
INDEX = "ix_douyu_tasks_platform_task_id"
|
||||||
|
|
||||||
|
|
||||||
|
def _column_exists() -> 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 = :column"
|
||||||
|
),
|
||||||
|
{"table": TABLE, "column": COLUMN},
|
||||||
|
)
|
||||||
|
.scalar()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _index_exists() -> 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 = :index"
|
||||||
|
),
|
||||||
|
{"table": TABLE, "index": INDEX},
|
||||||
|
)
|
||||||
|
.scalar()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
if not _column_exists():
|
||||||
|
op.add_column(TABLE, sa.Column(COLUMN, sa.BigInteger(), nullable=True))
|
||||||
|
if not _index_exists():
|
||||||
|
op.create_index(INDEX, TABLE, [COLUMN])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
if _index_exists():
|
||||||
|
op.drop_index(INDEX, table_name=TABLE)
|
||||||
|
if _column_exists():
|
||||||
|
op.drop_column(TABLE, COLUMN)
|
||||||
@@ -357,6 +357,11 @@ class DouyuTask(Base):
|
|||||||
created_by: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
created_by: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||||
finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||||
|
platform_task_id: Mapped[int | None] = mapped_column(
|
||||||
|
BigInteger,
|
||||||
|
nullable=True,
|
||||||
|
index=True,
|
||||||
|
)
|
||||||
# 账号归属客服冗余字段,配合复合索引消除任务列表全表 filesort。
|
# 账号归属客服冗余字段,配合复合索引消除任务列表全表 filesort。
|
||||||
account_assigned_to: Mapped[int | None] = mapped_column(
|
account_assigned_to: Mapped[int | None] = mapped_column(
|
||||||
ForeignKey("users.id"), nullable=True
|
ForeignKey("users.id"), nullable=True
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ from ..models import (
|
|||||||
LoginTask,
|
LoginTask,
|
||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
from ..permissions import user_has_permission
|
from ..permissions import ROLE_LABELS, user_has_permission
|
||||||
from ..schemas import (
|
from ..schemas import (
|
||||||
AccountAssign,
|
AccountAssign,
|
||||||
AccountAutomationUpdate,
|
AccountAutomationUpdate,
|
||||||
@@ -1856,8 +1856,34 @@ def account_events(
|
|||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
items = [dict(row) for row in rows]
|
||||||
|
actor_ids = {
|
||||||
|
int(item["actor_id"])
|
||||||
|
for item in items
|
||||||
|
if item.get("actor_type") == "user"
|
||||||
|
and item.get("actor_id") is not None
|
||||||
|
}
|
||||||
|
actors = {
|
||||||
|
int(user.id): user
|
||||||
|
for user in db.query(User).filter(User.id.in_(actor_ids)).all()
|
||||||
|
} if actor_ids else {}
|
||||||
|
for item in items:
|
||||||
|
actor = (
|
||||||
|
actors.get(int(item["actor_id"]))
|
||||||
|
if item.get("actor_type") == "user"
|
||||||
|
and item.get("actor_id") is not None
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
item["actor_name"] = (
|
||||||
|
actor.deleted_username or actor.username
|
||||||
|
) if actor is not None else ""
|
||||||
|
item["actor_role"] = actor.role if actor is not None else ""
|
||||||
|
item["actor_role_label"] = (
|
||||||
|
ROLE_LABELS.get(actor.role, actor.role) if actor is not None else ""
|
||||||
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"items": [dict(row) for row in rows],
|
"items": items,
|
||||||
"total": int(total),
|
"total": int(total),
|
||||||
"page": page,
|
"page": page,
|
||||||
"page_size": page_size,
|
"page_size": page_size,
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ from ..models import (
|
|||||||
DouyuWorkbench,
|
DouyuWorkbench,
|
||||||
DouyuWorkbenchAccount,
|
DouyuWorkbenchAccount,
|
||||||
DouyuXpdGoodsSnapshot,
|
DouyuXpdGoodsSnapshot,
|
||||||
|
PlatformFulfillmentTask,
|
||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
from ..permissions import user_has_permission
|
from ..permissions import user_has_permission
|
||||||
@@ -70,6 +71,7 @@ from ..services.douyu_service import (
|
|||||||
douyu_task_payload,
|
douyu_task_payload,
|
||||||
ensure_douyu_config,
|
ensure_douyu_config,
|
||||||
)
|
)
|
||||||
|
from ..services.platform_fulfillment import service as platform_fulfillment_service
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/douyu", tags=["斗鱼活动"])
|
router = APIRouter(prefix="/api/douyu", tags=["斗鱼活动"])
|
||||||
|
|
||||||
@@ -159,6 +161,13 @@ async def supplier_recharge_callback(request: Request, db: Session = Depends(get
|
|||||||
)
|
)
|
||||||
task.result = result
|
task.result = result
|
||||||
callback_success = status not in {3, 4}
|
callback_success = status not in {3, 4}
|
||||||
|
if task.platform_task_id and status in {2, 3, 4}:
|
||||||
|
platform_fulfillment_service.record_douyu_operation_result(
|
||||||
|
db,
|
||||||
|
task,
|
||||||
|
status="success" if status == 2 else "failed",
|
||||||
|
message=task.message,
|
||||||
|
)
|
||||||
# 回调说成功了就补一条充值事件。幂等键与 runner 那条**完全一致**
|
# 回调说成功了就补一条充值事件。幂等键与 runner 那条**完全一致**
|
||||||
# (business_events.task_ref),所以「runner 也观测到了」时不会重复记账;
|
# (business_events.task_ref),所以「runner 也观测到了」时不会重复记账;
|
||||||
# 而「runner 已判超时/失败、回调才到」这个黑洞则能被补上。
|
# 而「runner 已判超时/失败、回调才到」这个黑洞则能被补上。
|
||||||
@@ -237,12 +246,21 @@ def _visible_tasks_query(db: Session, current: User):
|
|||||||
return query
|
return query
|
||||||
if user_has_permission(current, "account:view_assigned"):
|
if user_has_permission(current, "account:view_assigned"):
|
||||||
# 彻底消除全表 filesort:直接通过 douyu_tasks 上的 account_assigned_to 复合索引倒序定位
|
# 彻底消除全表 filesort:直接通过 douyu_tasks 上的 account_assigned_to 复合索引倒序定位
|
||||||
return query.filter(DouyuTask.account_assigned_to == current.id)
|
return query.filter(
|
||||||
|
or_(
|
||||||
|
DouyuTask.account_assigned_to == current.id,
|
||||||
|
DouyuTask.created_by == current.id,
|
||||||
|
)
|
||||||
|
)
|
||||||
raise HTTPException(status_code=403, detail="无权查看斗鱼任务")
|
raise HTTPException(status_code=403, detail="无权查看斗鱼任务")
|
||||||
|
|
||||||
|
|
||||||
def _require_task_account_access(
|
def _require_task_account_access(
|
||||||
db: Session, current: User, account_ids: list[int]
|
db: Session,
|
||||||
|
current: User,
|
||||||
|
account_ids: list[int],
|
||||||
|
*,
|
||||||
|
platform_task_id: int | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""确保任务只会提交到当前用户可操作的账号。"""
|
"""确保任务只会提交到当前用户可操作的账号。"""
|
||||||
requested_ids = set(account_ids)
|
requested_ids = set(account_ids)
|
||||||
@@ -252,8 +270,27 @@ def _require_task_account_access(
|
|||||||
raise HTTPException(status_code=403, detail="无权操作斗鱼账号")
|
raise HTTPException(status_code=403, detail="无权操作斗鱼账号")
|
||||||
query = query.filter(Account.assigned_to == current.id)
|
query = query.filter(Account.assigned_to == current.id)
|
||||||
allowed_ids = {account_id for (account_id,) in query.all()}
|
allowed_ids = {account_id for (account_id,) in query.all()}
|
||||||
if allowed_ids != requested_ids:
|
if allowed_ids == requested_ids:
|
||||||
raise HTTPException(status_code=403, detail="包含无权操作的斗鱼账号")
|
return
|
||||||
|
if (
|
||||||
|
platform_task_id
|
||||||
|
and len(requested_ids) == 1
|
||||||
|
and user_has_permission(current, "platform_fulfillment:use")
|
||||||
|
):
|
||||||
|
task = (
|
||||||
|
db.query(PlatformFulfillmentTask)
|
||||||
|
.filter(
|
||||||
|
PlatformFulfillmentTask.id == int(platform_task_id),
|
||||||
|
PlatformFulfillmentTask.account_id.in_(requested_ids),
|
||||||
|
PlatformFulfillmentTask.execution_status.notin_(
|
||||||
|
["completed", "cancelled"]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if task is not None:
|
||||||
|
return
|
||||||
|
raise HTTPException(status_code=403, detail="包含无权操作的斗鱼账号")
|
||||||
|
|
||||||
|
|
||||||
def _require_batch_owner(db: Session, current: User, batch_id: str) -> None:
|
def _require_batch_owner(db: Session, current: User, batch_id: str) -> None:
|
||||||
@@ -731,7 +768,12 @@ async def create_task_batch(
|
|||||||
"""创建斗鱼任务记录并启动后台执行器。"""
|
"""创建斗鱼任务记录并启动后台执行器。"""
|
||||||
if not req.account_ids:
|
if not req.account_ids:
|
||||||
raise HTTPException(status_code=400, detail="请选择斗鱼账号")
|
raise HTTPException(status_code=400, detail="请选择斗鱼账号")
|
||||||
_require_task_account_access(db, current, req.account_ids)
|
_require_task_account_access(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
req.account_ids,
|
||||||
|
platform_task_id=req.platform_task_id,
|
||||||
|
)
|
||||||
|
|
||||||
cleanup_orphan_douyu_tasks(
|
cleanup_orphan_douyu_tasks(
|
||||||
db,
|
db,
|
||||||
@@ -748,6 +790,7 @@ async def create_task_batch(
|
|||||||
req.handbook_scope,
|
req.handbook_scope,
|
||||||
current.id,
|
current.id,
|
||||||
req.payload,
|
req.payload,
|
||||||
|
platform_task_id=req.platform_task_id,
|
||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
@@ -755,6 +798,31 @@ async def create_task_batch(
|
|||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=400, detail="没有可执行的斗鱼账号,请先登录获取 Cookie"
|
status_code=400, detail="没有可执行的斗鱼账号,请先登录获取 Cookie"
|
||||||
)
|
)
|
||||||
|
if req.platform_task_id:
|
||||||
|
platform_task = (
|
||||||
|
db.query(PlatformFulfillmentTask)
|
||||||
|
.filter(PlatformFulfillmentTask.id == int(req.platform_task_id))
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
douyu_task_ids = [
|
||||||
|
int(task_id)
|
||||||
|
for (task_id,) in (
|
||||||
|
db.query(DouyuTask.id)
|
||||||
|
.filter(DouyuTask.batch_id == batch_id)
|
||||||
|
.order_by(DouyuTask.id.asc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
]
|
||||||
|
if platform_task is not None:
|
||||||
|
platform_fulfillment_service.record_douyu_operation_started(
|
||||||
|
db,
|
||||||
|
platform_task,
|
||||||
|
current=current,
|
||||||
|
batch_id=batch_id,
|
||||||
|
task_type=req.task_type,
|
||||||
|
douyu_task_ids=douyu_task_ids,
|
||||||
|
payload=req.payload,
|
||||||
|
)
|
||||||
|
|
||||||
if req.task_type == "create_gold_qr":
|
if req.task_type == "create_gold_qr":
|
||||||
config = ensure_douyu_config(db)
|
config = ensure_douyu_config(db)
|
||||||
@@ -783,6 +851,7 @@ async def create_task_batch(
|
|||||||
"batch_id": batch_id,
|
"batch_id": batch_id,
|
||||||
"task_type": req.task_type,
|
"task_type": req.task_type,
|
||||||
"count": count,
|
"count": count,
|
||||||
|
"platform_task_id": req.platform_task_id,
|
||||||
"account_count": len(req.account_ids),
|
"account_count": len(req.account_ids),
|
||||||
"handbook_scope": req.handbook_scope,
|
"handbook_scope": req.handbook_scope,
|
||||||
"recharge_channel": recharge_channel,
|
"recharge_channel": recharge_channel,
|
||||||
|
|||||||
@@ -1612,6 +1612,7 @@ class DouyuTaskBatchRequest(BaseModel):
|
|||||||
handbook_scope: str = Field(..., pattern="^(elite|esports|peace)$")
|
handbook_scope: str = Field(..., pattern="^(elite|esports|peace)$")
|
||||||
concurrency: int = Field(3, ge=1, le=10)
|
concurrency: int = Field(3, ge=1, le=10)
|
||||||
payload: dict[str, Any] = Field(default_factory=dict)
|
payload: dict[str, Any] = Field(default_factory=dict)
|
||||||
|
platform_task_id: int | None = Field(None, gt=0)
|
||||||
|
|
||||||
|
|
||||||
class DouyuWorkbenchAccountsUpdate(BaseModel):
|
class DouyuWorkbenchAccountsUpdate(BaseModel):
|
||||||
|
|||||||
@@ -114,6 +114,7 @@ def record_douyu_task_result(
|
|||||||
status: str,
|
status: str,
|
||||||
message: str = "",
|
message: str = "",
|
||||||
occurred_at: datetime | None = None,
|
occurred_at: datetime | None = None,
|
||||||
|
actor_id: int | None = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""记录账号任务终态;成功不等于业务事实,因此单独作为活动事件。"""
|
"""记录账号任务终态;成功不等于业务事实,因此单独作为活动事件。"""
|
||||||
event_type = {
|
event_type = {
|
||||||
@@ -146,6 +147,8 @@ def record_douyu_task_result(
|
|||||||
source="douyu_task",
|
source="douyu_task",
|
||||||
subject_type="task",
|
subject_type="task",
|
||||||
subject_key=str(task_id),
|
subject_key=str(task_id),
|
||||||
|
actor_type="user" if actor_id else "system",
|
||||||
|
actor_id=actor_id,
|
||||||
source_ref=f"douyu_task_result:{task_id}",
|
source_ref=f"douyu_task_result:{task_id}",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -194,6 +197,7 @@ def record_recharge(
|
|||||||
douyu_uid: str = "",
|
douyu_uid: str = "",
|
||||||
balance_after: int | None = None,
|
balance_after: int | None = None,
|
||||||
confirmed: bool = True,
|
confirmed: bool = True,
|
||||||
|
actor_id: int | None = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""充值鱼翅到账。
|
"""充值鱼翅到账。
|
||||||
|
|
||||||
@@ -226,6 +230,8 @@ def record_recharge(
|
|||||||
source="douyu_task",
|
source="douyu_task",
|
||||||
subject_type="recharge",
|
subject_type="recharge",
|
||||||
subject_key=order_id or supplier_order_id or "",
|
subject_key=order_id or supplier_order_id or "",
|
||||||
|
actor_type="user" if actor_id else "system",
|
||||||
|
actor_id=actor_id,
|
||||||
source_ref=task_ref(task_id),
|
source_ref=task_ref(task_id),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -245,6 +251,7 @@ def record_exchange(
|
|||||||
game_channel: str = "",
|
game_channel: str = "",
|
||||||
points_after: int | None = None,
|
points_after: int | None = None,
|
||||||
scope: str = "elite",
|
scope: str = "elite",
|
||||||
|
actor_id: int | None = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""商品/皮肤兑换成功 —— **只在真的消耗了积分并兑换成功时调用**。
|
"""商品/皮肤兑换成功 —— **只在真的消耗了积分并兑换成功时调用**。
|
||||||
|
|
||||||
@@ -276,6 +283,8 @@ def record_exchange(
|
|||||||
source="douyu_task",
|
source="douyu_task",
|
||||||
subject_type="commodity",
|
subject_type="commodity",
|
||||||
subject_key=commodity_id or name or "",
|
subject_key=commodity_id or name or "",
|
||||||
|
actor_type="user" if actor_id else "system",
|
||||||
|
actor_id=actor_id,
|
||||||
source_ref=task_ref(task_id),
|
source_ref=task_ref(task_id),
|
||||||
)
|
)
|
||||||
if commodity_id:
|
if commodity_id:
|
||||||
@@ -311,6 +320,7 @@ def record_gold_spent(
|
|||||||
source_label: str = "",
|
source_label: str = "",
|
||||||
balance_after: int | None = None,
|
balance_after: int | None = None,
|
||||||
confirmed: bool = True,
|
confirmed: bool = True,
|
||||||
|
actor_id: int | None = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""鱼翅消耗(送礼等)。
|
"""鱼翅消耗(送礼等)。
|
||||||
|
|
||||||
@@ -338,6 +348,8 @@ def record_gold_spent(
|
|||||||
detail={"reason": reason, "source": source_label, "confirmed": confirmed},
|
detail={"reason": reason, "source": source_label, "confirmed": confirmed},
|
||||||
source="douyu_task",
|
source="douyu_task",
|
||||||
subject_type="gold",
|
subject_type="gold",
|
||||||
|
actor_type="user" if actor_id else "system",
|
||||||
|
actor_id=actor_id,
|
||||||
# 副事件:同一个任务还会发「积分到账」,所以带后缀避免撞幂等键
|
# 副事件:同一个任务还会发「积分到账」,所以带后缀避免撞幂等键
|
||||||
source_ref=task_ref(task_id, "gold"),
|
source_ref=task_ref(task_id, "gold"),
|
||||||
)
|
)
|
||||||
@@ -387,6 +399,7 @@ def record_points_credit(
|
|||||||
expire_at: Any = None,
|
expire_at: Any = None,
|
||||||
confirmed: bool = True,
|
confirmed: bool = True,
|
||||||
source_label: str = "精英令",
|
source_label: str = "精英令",
|
||||||
|
actor_id: int | None = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""积分到账(送礼/任务发放)。
|
"""积分到账(送礼/任务发放)。
|
||||||
|
|
||||||
@@ -417,6 +430,8 @@ def record_points_credit(
|
|||||||
},
|
},
|
||||||
source="douyu_task",
|
source="douyu_task",
|
||||||
subject_type="points",
|
subject_type="points",
|
||||||
|
actor_type="user" if actor_id else "system",
|
||||||
|
actor_id=actor_id,
|
||||||
source_ref=task_ref(task_id),
|
source_ref=task_ref(task_id),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -432,6 +447,7 @@ def record_bind(
|
|||||||
act_alias: str = "",
|
act_alias: str = "",
|
||||||
rebind: bool = False,
|
rebind: bool = False,
|
||||||
weak: bool = False,
|
weak: bool = False,
|
||||||
|
actor_id: int | None = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""角色绑定 / 换绑**真的发生了**。
|
"""角色绑定 / 换绑**真的发生了**。
|
||||||
|
|
||||||
@@ -468,6 +484,8 @@ def record_bind(
|
|||||||
source="douyu_task",
|
source="douyu_task",
|
||||||
subject_type=f"{scope}_role",
|
subject_type=f"{scope}_role",
|
||||||
subject_key=role_name or "",
|
subject_key=role_name or "",
|
||||||
|
actor_type="user" if actor_id else "system",
|
||||||
|
actor_id=actor_id,
|
||||||
source_ref=task_ref(task_id),
|
source_ref=task_ref(task_id),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1027,6 +1027,7 @@ class BindMixin:
|
|||||||
act_alias=use_confirm_alias,
|
act_alias=use_confirm_alias,
|
||||||
rebind=_bind_is_rebind(before_snapshot),
|
rebind=_bind_is_rebind(before_snapshot),
|
||||||
weak=True,
|
weak=True,
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
self._mark_task(
|
self._mark_task(
|
||||||
db,
|
db,
|
||||||
@@ -1062,6 +1063,7 @@ class BindMixin:
|
|||||||
role_name=final_role_name,
|
role_name=final_role_name,
|
||||||
act_alias=use_confirm_alias,
|
act_alias=use_confirm_alias,
|
||||||
rebind=_bind_is_rebind(after_snapshot),
|
rebind=_bind_is_rebind(after_snapshot),
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
self._mark_task(
|
self._mark_task(
|
||||||
db,
|
db,
|
||||||
@@ -1218,6 +1220,7 @@ class BindMixin:
|
|||||||
scope="esports",
|
scope="esports",
|
||||||
role_name=role_text,
|
role_name=role_text,
|
||||||
act_alias=act_alias,
|
act_alias=act_alias,
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
self._mark_task(
|
self._mark_task(
|
||||||
db,
|
db,
|
||||||
|
|||||||
@@ -200,6 +200,30 @@ class DouyuBatchRunnerCore:
|
|||||||
"[douyu] 同步直播账号履约状态失败: task_id={}", task.id
|
"[douyu] 同步直播账号履约状态失败: task_id={}", task.id
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _sync_platform_fulfillment_operation(
|
||||||
|
self,
|
||||||
|
db: Session,
|
||||||
|
task: DouyuTask,
|
||||||
|
*,
|
||||||
|
status: str,
|
||||||
|
message: str,
|
||||||
|
) -> None:
|
||||||
|
if not task.platform_task_id:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
from .platform_fulfillment.service import record_douyu_operation_result
|
||||||
|
|
||||||
|
record_douyu_operation_result(
|
||||||
|
db,
|
||||||
|
task,
|
||||||
|
status=status,
|
||||||
|
message=message,
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001 - 履约时间线不能覆盖任务执行结果
|
||||||
|
logger.exception(
|
||||||
|
"[douyu] 写入履约操作时间线失败: task_id={}", task.id
|
||||||
|
)
|
||||||
|
|
||||||
def _mark_task(
|
def _mark_task(
|
||||||
self,
|
self,
|
||||||
db: Session,
|
db: Session,
|
||||||
@@ -233,7 +257,14 @@ class DouyuBatchRunnerCore:
|
|||||||
status=status,
|
status=status,
|
||||||
message=message,
|
message=message,
|
||||||
occurred_at=task.finished_at,
|
occurred_at=task.finished_at,
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
|
self._sync_platform_fulfillment_operation(
|
||||||
|
db,
|
||||||
|
task,
|
||||||
|
status=status,
|
||||||
|
message=message,
|
||||||
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
self._push_task_event(task)
|
self._push_task_event(task)
|
||||||
self._sync_platform_fulfillment(db, task)
|
self._sync_platform_fulfillment(db, task)
|
||||||
|
|||||||
@@ -202,6 +202,7 @@ class DonateMixin:
|
|||||||
points_after=account.esports_points,
|
points_after=account.esports_points,
|
||||||
confirmed=confirmed,
|
confirmed=confirmed,
|
||||||
source_label=gift_name,
|
source_label=gift_name,
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
record_gold_spent(
|
record_gold_spent(
|
||||||
db,
|
db,
|
||||||
@@ -211,6 +212,7 @@ class DonateMixin:
|
|||||||
reason=f"赠送{gift_name} x{gift_count}",
|
reason=f"赠送{gift_name} x{gift_count}",
|
||||||
source_label=f"赠送{gift_name}",
|
source_label=f"赠送{gift_name}",
|
||||||
balance_after=account.gold_balance,
|
balance_after=account.gold_balance,
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
self._mark_task(db, task, "success", message, result)
|
self._mark_task(db, task, "success", message, result)
|
||||||
|
|
||||||
@@ -338,6 +340,7 @@ class DonateMixin:
|
|||||||
expire_at=expire_at,
|
expire_at=expire_at,
|
||||||
confirmed=confirmed,
|
confirmed=confirmed,
|
||||||
source_label="精英令",
|
source_label="精英令",
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
# 鱼翅出项:以前只记「积分到账」,花掉的鱼翅没有任何记录 ——
|
# 鱼翅出项:以前只记「积分到账」,花掉的鱼翅没有任何记录 ——
|
||||||
# 充值有账、消耗没账,对不上。金额取实测余额差。
|
# 充值有账、消耗没账,对不上。金额取实测余额差。
|
||||||
@@ -349,6 +352,7 @@ class DonateMixin:
|
|||||||
reason=f"赠送精英令 x{gift_count}",
|
reason=f"赠送精英令 x{gift_count}",
|
||||||
source_label="赠送精英令",
|
source_label="赠送精英令",
|
||||||
balance_after=account.gold_balance,
|
balance_after=account.gold_balance,
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
self._mark_task(db, task, "success", message, result)
|
self._mark_task(db, task, "success", message, result)
|
||||||
|
|
||||||
|
|||||||
@@ -294,6 +294,7 @@ class GoldMixin:
|
|||||||
channel=channel,
|
channel=channel,
|
||||||
balance_after=account.gold_balance,
|
balance_after=account.gold_balance,
|
||||||
confirmed=True,
|
confirmed=True,
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
self._mark_task(
|
self._mark_task(
|
||||||
db,
|
db,
|
||||||
@@ -453,6 +454,7 @@ class GoldMixin:
|
|||||||
channel="supplier_api",
|
channel="supplier_api",
|
||||||
douyu_uid=str(result.get("douyu_uid") or ""),
|
douyu_uid=str(result.get("douyu_uid") or ""),
|
||||||
balance_after=account.gold_balance,
|
balance_after=account.gold_balance,
|
||||||
|
actor_id=int(task.created_by),
|
||||||
# 供应商终态成功 ≠ 斗鱼余额已变,如实标注
|
# 供应商终态成功 ≠ 斗鱼余额已变,如实标注
|
||||||
confirmed=False,
|
confirmed=False,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -283,6 +283,7 @@ class GoodsMixin:
|
|||||||
game_channel=account.game_channel or "",
|
game_channel=account.game_channel or "",
|
||||||
points_after=account.points,
|
points_after=account.points,
|
||||||
scope="elite",
|
scope="elite",
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
self._mark_task(
|
self._mark_task(
|
||||||
db,
|
db,
|
||||||
@@ -589,6 +590,7 @@ class GoodsMixin:
|
|||||||
game_channel=account.game_channel or "",
|
game_channel=account.game_channel or "",
|
||||||
points_after=(points_refresh or {}).get("points"),
|
points_after=(points_refresh or {}).get("points"),
|
||||||
scope="elite",
|
scope="elite",
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
self._refresh_high_value_after_exchange(
|
self._refresh_high_value_after_exchange(
|
||||||
client,
|
client,
|
||||||
@@ -709,6 +711,7 @@ class GoodsMixin:
|
|||||||
game_channel=account.esports_game_channel or "",
|
game_channel=account.esports_game_channel or "",
|
||||||
points_after=account.esports_points,
|
points_after=account.esports_points,
|
||||||
scope="esports",
|
scope="esports",
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
self._mark_task(db, task, "success", message, result)
|
self._mark_task(db, task, "success", message, result)
|
||||||
|
|
||||||
|
|||||||
@@ -406,6 +406,8 @@ class ManualMixin:
|
|||||||
"spent": spent,
|
"spent": spent,
|
||||||
},
|
},
|
||||||
source="manual",
|
source="manual",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=int(task.created_by),
|
||||||
source_ref=(
|
source_ref=(
|
||||||
f"elite_opened:{account.id}:{int(account.updated_at.timestamp())}"
|
f"elite_opened:{account.id}:{int(account.updated_at.timestamp())}"
|
||||||
),
|
),
|
||||||
@@ -509,6 +511,8 @@ class ManualMixin:
|
|||||||
amount=-spent if spent else None,
|
amount=-spent if spent else None,
|
||||||
detail={"points": account.esports_points, "spent": spent},
|
detail={"points": account.esports_points, "spent": spent},
|
||||||
source="manual",
|
source="manual",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=int(task.created_by),
|
||||||
source_ref=(
|
source_ref=(
|
||||||
f"esports_opened:{account.id}:{int(account.updated_at.timestamp())}"
|
f"esports_opened:{account.id}:{int(account.updated_at.timestamp())}"
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -599,6 +599,7 @@ class XpdMixin:
|
|||||||
game_channel=channel,
|
game_channel=channel,
|
||||||
points_after=result.get("new_balance"),
|
points_after=result.get("new_balance"),
|
||||||
scope="peace",
|
scope="peace",
|
||||||
|
actor_id=int(task.created_by),
|
||||||
)
|
)
|
||||||
self._mark_task(
|
self._mark_task(
|
||||||
db,
|
db,
|
||||||
|
|||||||
@@ -273,6 +273,7 @@ def create_douyu_planned_tasks(
|
|||||||
handbook_scope: str,
|
handbook_scope: str,
|
||||||
created_by: int,
|
created_by: int,
|
||||||
payload: dict | None = None,
|
payload: dict | None = None,
|
||||||
|
platform_task_id: int | None = None,
|
||||||
) -> tuple[str, int]:
|
) -> tuple[str, int]:
|
||||||
"""创建斗鱼任务记录,等待后台执行器消费。"""
|
"""创建斗鱼任务记录,等待后台执行器消费。"""
|
||||||
if task_type not in SUPPORTED_DOUYU_TASK_TYPES:
|
if task_type not in SUPPORTED_DOUYU_TASK_TYPES:
|
||||||
@@ -304,6 +305,7 @@ def create_douyu_planned_tasks(
|
|||||||
message="任务已创建,等待执行",
|
message="任务已创建,等待执行",
|
||||||
result={"payload": payload} if payload else None,
|
result={"payload": payload} if payload else None,
|
||||||
created_by=created_by,
|
created_by=created_by,
|
||||||
|
platform_task_id=platform_task_id,
|
||||||
)
|
)
|
||||||
db.add(task)
|
db.add(task)
|
||||||
task_rows.append((task, account))
|
task_rows.append((task, account))
|
||||||
@@ -380,6 +382,15 @@ def cleanup_orphan_douyu_tasks(
|
|||||||
message=message,
|
message=message,
|
||||||
occurred_at=now,
|
occurred_at=now,
|
||||||
)
|
)
|
||||||
|
if task.platform_task_id:
|
||||||
|
from .platform_fulfillment.service import record_douyu_operation_result
|
||||||
|
|
||||||
|
record_douyu_operation_result(
|
||||||
|
db,
|
||||||
|
task,
|
||||||
|
status="stopped",
|
||||||
|
message=message,
|
||||||
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
return len(tasks)
|
return len(tasks)
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,11 @@ from ..business_events import record_account_query, record_douyu_task_started
|
|||||||
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
|
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
|
||||||
from ..douyu_activity_query import activity_client, query_exchange_eligibility
|
from ..douyu_activity_query import activity_client, query_exchange_eligibility
|
||||||
from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches
|
from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches
|
||||||
from ..douyu_service import douyu_config_value, ensure_douyu_config
|
from ..douyu_service import (
|
||||||
|
SUPPORTED_DOUYU_TASK_TYPES,
|
||||||
|
douyu_config_value,
|
||||||
|
ensure_douyu_config,
|
||||||
|
)
|
||||||
from ..external_order_source import (
|
from ..external_order_source import (
|
||||||
OrderLookupUnavailable,
|
OrderLookupUnavailable,
|
||||||
list_pending_manual_fulfillments,
|
list_pending_manual_fulfillments,
|
||||||
@@ -648,6 +652,80 @@ def _append_event(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def record_douyu_operation_started(
|
||||||
|
db: Session,
|
||||||
|
task: PlatformFulfillmentTask,
|
||||||
|
*,
|
||||||
|
current: User,
|
||||||
|
batch_id: str,
|
||||||
|
task_type: str,
|
||||||
|
douyu_task_ids: list[int],
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""记录履约上下文发起的斗鱼操作,账号任务结果由执行器补写。"""
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
task.id,
|
||||||
|
"douyu_operation_started",
|
||||||
|
actor_type="user",
|
||||||
|
actor_id=current.id,
|
||||||
|
detail={
|
||||||
|
"batchId": batch_id,
|
||||||
|
"douyuTaskIds": douyu_task_ids,
|
||||||
|
"taskType": task_type,
|
||||||
|
"taskLabel": SUPPORTED_DOUYU_TASK_TYPES.get(task_type, task_type),
|
||||||
|
"accountId": task.account_id,
|
||||||
|
"payload": payload or {},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def record_douyu_operation_result(
|
||||||
|
db: Session,
|
||||||
|
douyu_task: DouyuTask,
|
||||||
|
*,
|
||||||
|
status: str,
|
||||||
|
message: str,
|
||||||
|
) -> None:
|
||||||
|
"""把履约上下文的斗鱼任务终态投影到履约时间线。"""
|
||||||
|
if not douyu_task.platform_task_id:
|
||||||
|
return
|
||||||
|
event_type = {
|
||||||
|
"success": "douyu_operation_succeeded",
|
||||||
|
"stopped": "douyu_operation_stopped",
|
||||||
|
}.get(status, "douyu_operation_failed")
|
||||||
|
exists = (
|
||||||
|
db.query(PlatformFulfillmentEvent.id)
|
||||||
|
.filter(
|
||||||
|
PlatformFulfillmentEvent.task_id == int(douyu_task.platform_task_id),
|
||||||
|
PlatformFulfillmentEvent.event_type == event_type,
|
||||||
|
PlatformFulfillmentEvent.detail_json["douyuTaskId"].as_integer()
|
||||||
|
== int(douyu_task.id),
|
||||||
|
)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if exists is not None:
|
||||||
|
return
|
||||||
|
_append_event(
|
||||||
|
db,
|
||||||
|
int(douyu_task.platform_task_id),
|
||||||
|
event_type,
|
||||||
|
detail={
|
||||||
|
"batchId": douyu_task.batch_id,
|
||||||
|
"douyuTaskId": int(douyu_task.id),
|
||||||
|
"taskType": douyu_task.task_type,
|
||||||
|
"taskLabel": SUPPORTED_DOUYU_TASK_TYPES.get(
|
||||||
|
douyu_task.task_type,
|
||||||
|
douyu_task.task_type,
|
||||||
|
),
|
||||||
|
"accountId": douyu_task.account_id,
|
||||||
|
"status": status,
|
||||||
|
"message": (message or "")[:1000],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _emit_order_site_binding_state(
|
def _emit_order_site_binding_state(
|
||||||
db: Session,
|
db: Session,
|
||||||
task_id: int,
|
task_id: int,
|
||||||
@@ -2500,6 +2578,8 @@ __all__ = [
|
|||||||
"list_tasks",
|
"list_tasks",
|
||||||
"mark_manual_required",
|
"mark_manual_required",
|
||||||
"reconcile_binding_state_outbox",
|
"reconcile_binding_state_outbox",
|
||||||
|
"record_douyu_operation_result",
|
||||||
|
"record_douyu_operation_started",
|
||||||
"refresh_binding",
|
"refresh_binding",
|
||||||
"refresh_exchange_eligibility",
|
"refresh_exchange_eligibility",
|
||||||
"release_task_account",
|
"release_task_account",
|
||||||
|
|||||||
@@ -187,6 +187,9 @@ export interface AccountEventItem {
|
|||||||
source: string;
|
source: string;
|
||||||
actor_type?: string;
|
actor_type?: string;
|
||||||
actor_id?: number | null;
|
actor_id?: number | null;
|
||||||
|
actor_name?: string;
|
||||||
|
actor_role?: string;
|
||||||
|
actor_role_label?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AccountEventPage {
|
export interface AccountEventPage {
|
||||||
@@ -749,6 +752,7 @@ export interface DouyuTaskBatchRequest {
|
|||||||
handbook_scope: "elite" | "esports" | "peace";
|
handbook_scope: "elite" | "esports" | "peace";
|
||||||
concurrency?: number;
|
concurrency?: number;
|
||||||
payload?: Record<string, unknown>;
|
payload?: Record<string, unknown>;
|
||||||
|
platform_task_id?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DouyuTaskBatchResult {
|
export interface DouyuTaskBatchResult {
|
||||||
|
|||||||
@@ -56,6 +56,12 @@ const CATEGORY_OPTIONS = [
|
|||||||
{ value: 'ops', label: '人工操作' },
|
{ value: 'ops', label: '人工操作' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const ACTOR_TYPE_LABELS: Record<string, string> = {
|
||||||
|
user: '用户',
|
||||||
|
system: '系统',
|
||||||
|
public: '客户',
|
||||||
|
};
|
||||||
|
|
||||||
/** 生命周期状态 → 展示色(与账号列表页保持一致,取值域见后端 account_lifecycle)。 */
|
/** 生命周期状态 → 展示色(与账号列表页保持一致,取值域见后端 account_lifecycle)。 */
|
||||||
const STATUS_TONES: Record<string, string> = {
|
const STATUS_TONES: Record<string, string> = {
|
||||||
imported: 'default',
|
imported: 'default',
|
||||||
@@ -106,6 +112,16 @@ function eventTag(type: string) {
|
|||||||
return <Tag color={style.color}>{style.label}</Tag>;
|
return <Tag color={style.color}>{style.label}</Tag>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function actorLabel(item: AccountEventItem) {
|
||||||
|
if (item.actor_type === 'user') {
|
||||||
|
const name = item.actor_name || (item.actor_id ? `用户 #${item.actor_id}` : '用户');
|
||||||
|
const role = item.actor_role_label ? `(${item.actor_role_label})` : '';
|
||||||
|
const id = item.actor_id ? ` · ID ${item.actor_id}` : '';
|
||||||
|
return `${name}${role}${id}`;
|
||||||
|
}
|
||||||
|
return ACTOR_TYPE_LABELS[item.actor_type || 'system'] || item.actor_type || '系统';
|
||||||
|
}
|
||||||
|
|
||||||
const COMMODITY_STATE: Record<string, { label: string; color: string }> = {
|
const COMMODITY_STATE: Record<string, { label: string; color: string }> = {
|
||||||
available: { label: '可兑换', color: 'green' },
|
available: { label: '可兑换', color: 'green' },
|
||||||
limited: { label: '已达上限', color: 'orange' },
|
limited: { label: '已达上限', color: 'orange' },
|
||||||
@@ -296,6 +312,12 @@ export default function AccountDetailPage() {
|
|||||||
width: 100,
|
width: 100,
|
||||||
render: (val: string) => eventTag(val),
|
render: (val: string) => eventTag(val),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: '操作人',
|
||||||
|
key: 'actor',
|
||||||
|
width: 190,
|
||||||
|
render: (_value, record) => <Text>{actorLabel(record)}</Text>,
|
||||||
|
},
|
||||||
{ title: '说明', dataIndex: 'title', ellipsis: true },
|
{ title: '说明', dataIndex: 'title', ellipsis: true },
|
||||||
{
|
{
|
||||||
title: '金额 / 变动',
|
title: '金额 / 变动',
|
||||||
|
|||||||
@@ -97,6 +97,10 @@ const EVENT_LABELS: Record<string, string> = {
|
|||||||
manual_exchange_completed: '人工兑换完成',
|
manual_exchange_completed: '人工兑换完成',
|
||||||
marked_manual_required: '转人工处理',
|
marked_manual_required: '转人工处理',
|
||||||
released_to_manual: '释放账号并转人工',
|
released_to_manual: '释放账号并转人工',
|
||||||
|
douyu_operation_started: '斗鱼操作已提交',
|
||||||
|
douyu_operation_succeeded: '斗鱼操作成功',
|
||||||
|
douyu_operation_failed: '斗鱼操作失败',
|
||||||
|
douyu_operation_stopped: '斗鱼操作已停止',
|
||||||
task_cancelled: '任务已取消',
|
task_cancelled: '任务已取消',
|
||||||
task_restored: '恢复已取消任务',
|
task_restored: '恢复已取消任务',
|
||||||
};
|
};
|
||||||
@@ -187,7 +191,17 @@ function eventLabel(value: string) {
|
|||||||
function eventColor(value: string) {
|
function eventColor(value: string) {
|
||||||
if (value.includes('failed') || value.includes('cancelled')) return 'red';
|
if (value.includes('failed') || value.includes('cancelled')) return 'red';
|
||||||
if (value.includes('manual_required') || value.includes('released_to_manual')) return 'orange';
|
if (value.includes('manual_required') || value.includes('released_to_manual')) return 'orange';
|
||||||
if (value.includes('completed') || value.includes('allocated') || value.includes('restored')) return 'green';
|
if (
|
||||||
|
value.includes('completed') ||
|
||||||
|
value.includes('allocated') ||
|
||||||
|
value.includes('restored') ||
|
||||||
|
value.includes('succeeded')
|
||||||
|
) {
|
||||||
|
return 'green';
|
||||||
|
}
|
||||||
|
if (value.includes('douyu_operation_failed') || value.includes('douyu_operation_stopped')) {
|
||||||
|
return value.includes('stopped') ? 'orange' : 'red';
|
||||||
|
}
|
||||||
return 'blue';
|
return 'blue';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -236,6 +250,16 @@ function eventDescription(event: { eventType: string; detail: Record<string, unk
|
|||||||
const status = String(detail.restoredExecutionStatus || '');
|
const status = String(detail.restoredExecutionStatus || '');
|
||||||
return `恢复原因:${String(detail.reason || '误取消恢复')};恢复后状态:${statusLabel(status)}`;
|
return `恢复原因:${String(detail.reason || '误取消恢复')};恢复后状态:${statusLabel(status)}`;
|
||||||
}
|
}
|
||||||
|
if (event.eventType === 'douyu_operation_started') {
|
||||||
|
return `${String(detail.taskLabel || detail.taskType || '斗鱼操作')};批次 ${String(detail.batchId || '-')}`;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
event.eventType === 'douyu_operation_succeeded' ||
|
||||||
|
event.eventType === 'douyu_operation_failed' ||
|
||||||
|
event.eventType === 'douyu_operation_stopped'
|
||||||
|
) {
|
||||||
|
return `${String(detail.taskLabel || detail.taskType || '斗鱼操作')}:${String(detail.message || detail.status || '-')}`;
|
||||||
|
}
|
||||||
if (event.eventType === 'binding_started') return '已生成客户绑定二维码';
|
if (event.eventType === 'binding_started') return '已生成客户绑定二维码';
|
||||||
if (event.eventType === 'binding_confirm_started') return '已提交游戏角色绑定确认';
|
if (event.eventType === 'binding_confirm_started') return '已提交游戏角色绑定确认';
|
||||||
if (event.eventType === 'binding_failed') {
|
if (event.eventType === 'binding_failed') {
|
||||||
@@ -595,6 +619,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
handbook_scope: 'elite',
|
handbook_scope: 'elite',
|
||||||
concurrency: 1,
|
concurrency: 1,
|
||||||
payload,
|
payload,
|
||||||
|
platform_task_id: selected.id,
|
||||||
});
|
});
|
||||||
setDouyuActionType(taskType);
|
setDouyuActionType(taskType);
|
||||||
setDouyuActionBatchId(result.batch_id);
|
setDouyuActionBatchId(result.batch_id);
|
||||||
|
|||||||
Reference in New Issue
Block a user