fix(platform): 持久化并完善斗鱼兑换结果图片
This commit is contained in:
@@ -94,6 +94,10 @@
|
|||||||
7. 运营在斗鱼侧人工完成兑换。
|
7. 运营在斗鱼侧人工完成兑换。
|
||||||
8. 回到工作台点击“完成”,系统释放账号租约并记录操作时间线。
|
8. 回到工作台点击“完成”,系统释放账号租约并记录操作时间线。
|
||||||
|
|
||||||
|
通过“兑换当前订单皮肤”执行成功时,系统会生成兑换结果图片并保存到文件存储。
|
||||||
|
履约详情会长期展示该凭证,支持查看大图、复制和下载;斗鱼任务日志被清理后,
|
||||||
|
履约任务上的图片引用仍保留。
|
||||||
|
|
||||||
## 账号租约
|
## 账号租约
|
||||||
|
|
||||||
账号租约默认无限制,适合当前“分配后由运营人工处理”的流程。管理员可在
|
账号租约默认无限制,适合当前“分配后由运营人工处理”的流程。管理员可在
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
"""斗鱼兑换结果图片持久化到文件存储并绑定履约任务。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from web.backend.models import (
|
||||||
|
Account,
|
||||||
|
DouyuTask,
|
||||||
|
FileAsset,
|
||||||
|
PlatformFulfillmentTask,
|
||||||
|
User,
|
||||||
|
)
|
||||||
|
from web.backend.services.douyu_exchange_result_image import (
|
||||||
|
ExchangeResultImageError,
|
||||||
|
save_exchange_result_image,
|
||||||
|
)
|
||||||
|
from web.backend.services.file_storage import reset_object_storage_cache
|
||||||
|
from web.backend.services.platform_fulfillment import service as fulfillment_service
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def local_storage(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||||
|
monkeypatch.setenv("OSS_MODE", "local")
|
||||||
|
monkeypatch.setenv("OSS_LOCAL_ROOT", str(tmp_path))
|
||||||
|
monkeypatch.setenv("OSS_MAX_UPLOAD_SIZE_MB", "10")
|
||||||
|
reset_object_storage_cache()
|
||||||
|
yield tmp_path
|
||||||
|
reset_object_storage_cache()
|
||||||
|
|
||||||
|
|
||||||
|
def _png_bytes() -> bytes:
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
Image.new("RGB", (320, 470), (20, 60, 120)).save(buffer, "PNG")
|
||||||
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _records(db) -> tuple[User, Account, PlatformFulfillmentTask, DouyuTask]:
|
||||||
|
user = User(username="exchange-image-user", password_hash="h", role="support")
|
||||||
|
db.add(user)
|
||||||
|
db.flush()
|
||||||
|
account = Account(
|
||||||
|
username="exchange-image-account",
|
||||||
|
password="p",
|
||||||
|
email="exchange-image@example.com",
|
||||||
|
email_password="ep",
|
||||||
|
status="active",
|
||||||
|
assigned_to=user.id,
|
||||||
|
)
|
||||||
|
db.add(account)
|
||||||
|
db.flush()
|
||||||
|
platform_task = PlatformFulfillmentTask(
|
||||||
|
source_order_id="exchange-order",
|
||||||
|
source_order_item_id="exchange-item",
|
||||||
|
internal_sku_key="套装-花羊椰椰",
|
||||||
|
sku_name="套装-花羊椰椰",
|
||||||
|
target_platform="douyu",
|
||||||
|
account_id=account.id,
|
||||||
|
binding_status="bound",
|
||||||
|
execution_status="bound",
|
||||||
|
exchange_status="eligible",
|
||||||
|
)
|
||||||
|
db.add(platform_task)
|
||||||
|
db.flush()
|
||||||
|
douyu_task = DouyuTask(
|
||||||
|
batch_id="exchange-image-batch",
|
||||||
|
account_id=account.id,
|
||||||
|
account_assigned_to=user.id,
|
||||||
|
task_type="exchange_goods",
|
||||||
|
handbook_scope="elite",
|
||||||
|
status="success",
|
||||||
|
message="兑换成功",
|
||||||
|
result={"goods": {"commodityName": "套装-花羊椰椰"}},
|
||||||
|
created_by=user.id,
|
||||||
|
platform_task_id=platform_task.id,
|
||||||
|
)
|
||||||
|
db.add(douyu_task)
|
||||||
|
db.commit()
|
||||||
|
return user, account, platform_task, douyu_task
|
||||||
|
|
||||||
|
|
||||||
|
def test_saves_image_and_binds_it_to_both_tasks(db, local_storage: Path):
|
||||||
|
user, _account, platform_task, douyu_task = _records(db)
|
||||||
|
|
||||||
|
saved = save_exchange_result_image(
|
||||||
|
db,
|
||||||
|
douyu_task,
|
||||||
|
data=_png_bytes(),
|
||||||
|
filename="兑换结果.png",
|
||||||
|
uploader_id=user.id,
|
||||||
|
platform_task=platform_task,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert saved["objectKey"].startswith("exchange-result/")
|
||||||
|
assert saved["url"].startswith("/api/files/object?key=")
|
||||||
|
db.refresh(douyu_task)
|
||||||
|
db.refresh(platform_task)
|
||||||
|
assert douyu_task.result["exchange_result_image"]["object_key"] == saved["objectKey"]
|
||||||
|
assert platform_task.exchange_task_id == douyu_task.id
|
||||||
|
assert platform_task.exchange_result_image_key == saved["objectKey"]
|
||||||
|
assert platform_task.exchange_result_image_saved_at is not None
|
||||||
|
asset = db.query(FileAsset).one()
|
||||||
|
assert asset.object_key == saved["objectKey"]
|
||||||
|
assert asset.scene == "exchange-result"
|
||||||
|
assert asset.uploader_id == str(user.id)
|
||||||
|
stored = [path for path in local_storage.rglob("*") if path.is_file()]
|
||||||
|
assert len(stored) == 3
|
||||||
|
|
||||||
|
payload = fulfillment_service._task_out(db, platform_task)
|
||||||
|
assert payload["exchangeResultImage"]["objectKey"] == saved["objectKey"]
|
||||||
|
assert payload["exchangeResultImage"]["url"] == saved["url"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_saving_is_idempotent(db, local_storage: Path):
|
||||||
|
user, _account, platform_task, douyu_task = _records(db)
|
||||||
|
first = save_exchange_result_image(
|
||||||
|
db,
|
||||||
|
douyu_task,
|
||||||
|
data=_png_bytes(),
|
||||||
|
uploader_id=user.id,
|
||||||
|
platform_task=platform_task,
|
||||||
|
)
|
||||||
|
|
||||||
|
second = save_exchange_result_image(
|
||||||
|
db,
|
||||||
|
douyu_task,
|
||||||
|
data=_png_bytes(),
|
||||||
|
uploader_id=user.id,
|
||||||
|
platform_task=platform_task,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert second == first
|
||||||
|
assert db.query(FileAsset).count() == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_exchange_operation_links_the_douyu_task(db):
|
||||||
|
user, _account, platform_task, douyu_task = _records(db)
|
||||||
|
|
||||||
|
fulfillment_service.record_douyu_operation_started(
|
||||||
|
db,
|
||||||
|
platform_task,
|
||||||
|
current=user,
|
||||||
|
batch_id=douyu_task.batch_id,
|
||||||
|
task_type="exchange_goods",
|
||||||
|
douyu_task_ids=[douyu_task.id],
|
||||||
|
)
|
||||||
|
|
||||||
|
db.refresh(platform_task)
|
||||||
|
assert platform_task.exchange_task_id == douyu_task.id
|
||||||
|
assert fulfillment_service._task_out(db, platform_task)["exchangeTaskId"] == douyu_task.id
|
||||||
|
|
||||||
|
|
||||||
|
def test_detail_recovers_legacy_exchange_task_by_platform_task_id(db):
|
||||||
|
_user, _account, platform_task, douyu_task = _records(db)
|
||||||
|
platform_task.exchange_task_id = None
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
payload = fulfillment_service._task_out(
|
||||||
|
db,
|
||||||
|
platform_task,
|
||||||
|
include_exchange_task=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert payload["exchangeTaskId"] == douyu_task.id
|
||||||
|
|
||||||
|
|
||||||
|
def test_rejects_non_exchange_or_unfinished_task(db, local_storage: Path):
|
||||||
|
user, _account, platform_task, douyu_task = _records(db)
|
||||||
|
douyu_task.task_type = "query_elite_status"
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
with pytest.raises(ExchangeResultImageError, match="不是兑换任务"):
|
||||||
|
save_exchange_result_image(
|
||||||
|
db,
|
||||||
|
douyu_task,
|
||||||
|
data=_png_bytes(),
|
||||||
|
uploader_id=user.id,
|
||||||
|
platform_task=platform_task,
|
||||||
|
)
|
||||||
+139
-38
@@ -41,7 +41,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 = "20261121_0104"
|
HEAD_REVISION = "20261121_0105"
|
||||||
|
|
||||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||||
EXTRA_INDEXES = (
|
EXTRA_INDEXES = (
|
||||||
@@ -314,6 +314,63 @@ class TestMigrationSmoke:
|
|||||||
with admin_engine.begin() as conn:
|
with admin_engine.begin() as conn:
|
||||||
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
|
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
|
||||||
|
|
||||||
|
def test_0105_adds_exchange_result_image_columns_and_roundtrips(self):
|
||||||
|
creds = get_mysql_credentials()
|
||||||
|
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
|
||||||
|
mig_url = (
|
||||||
|
f"mysql+pymysql://{quote_plus(creds['user'])}:"
|
||||||
|
f"{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/"
|
||||||
|
f"{mig_db}?charset=utf8mb4"
|
||||||
|
)
|
||||||
|
admin_engine = get_test_engine()
|
||||||
|
mig_engine = create_engine(mig_url)
|
||||||
|
original_url = database_module.DATABASE_URL
|
||||||
|
with admin_engine.begin() as conn:
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
f"CREATE DATABASE `{mig_db}` "
|
||||||
|
"CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
database_module.DATABASE_URL = mig_url
|
||||||
|
cfg = _migration_config()
|
||||||
|
cfg.set_main_option("sqlalchemy.url", mig_url)
|
||||||
|
command.upgrade(cfg, "20261121_0104")
|
||||||
|
before = {
|
||||||
|
row["name"]
|
||||||
|
for row in inspect(mig_engine).get_columns(
|
||||||
|
"platform_fulfillment_tasks"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
assert "exchange_result_image_key" not in before
|
||||||
|
assert "exchange_result_image_saved_at" not in before
|
||||||
|
|
||||||
|
command.upgrade(cfg, "head")
|
||||||
|
after = {
|
||||||
|
row["name"]
|
||||||
|
for row in inspect(mig_engine).get_columns(
|
||||||
|
"platform_fulfillment_tasks"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
assert "exchange_result_image_key" in after
|
||||||
|
assert "exchange_result_image_saved_at" in after
|
||||||
|
|
||||||
|
command.downgrade(cfg, "20261121_0104")
|
||||||
|
downgraded = {
|
||||||
|
row["name"]
|
||||||
|
for row in inspect(mig_engine).get_columns(
|
||||||
|
"platform_fulfillment_tasks"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
assert "exchange_result_image_key" not in downgraded
|
||||||
|
assert "exchange_result_image_saved_at" not in downgraded
|
||||||
|
finally:
|
||||||
|
database_module.DATABASE_URL = original_url
|
||||||
|
mig_engine.dispose()
|
||||||
|
with admin_engine.begin() as conn:
|
||||||
|
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
|
||||||
|
|
||||||
def test_0077_converts_super_admin_membership_to_overlay(self):
|
def test_0077_converts_super_admin_membership_to_overlay(self):
|
||||||
creds = get_mysql_credentials()
|
creds = get_mysql_credentials()
|
||||||
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
|
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
|
||||||
@@ -723,46 +780,90 @@ class TestMigrationSmoke:
|
|||||||
)
|
)
|
||||||
session.add(lease)
|
session.add(lease)
|
||||||
session.commit()
|
session.commit()
|
||||||
broken = PlatformFulfillmentTask(
|
broken_id = 9001
|
||||||
source_system="order_site",
|
unassigned_id = 9002
|
||||||
source_order_id="MIG-0090",
|
account_id = account.id
|
||||||
source_order_item_id="MIG-0090-1",
|
lease_id = lease.id
|
||||||
account_id=account.id,
|
|
||||||
lease_id=lease.id,
|
# 该用例固定在 0089 架构上验证历史迁移;不能用当前 ORM 插入,
|
||||||
execution_status="ready",
|
# 否则后续新增列会被 SQLAlchemy 一并写进旧表。
|
||||||
binding_status="not_started",
|
with mig_engine.begin() as conn:
|
||||||
exchange_status="points_short",
|
for task_id, item_id, extra in (
|
||||||
issue_code="",
|
(
|
||||||
last_error="",
|
broken_id,
|
||||||
)
|
"MIG-0090-1",
|
||||||
unassigned = PlatformFulfillmentTask(
|
{
|
||||||
source_system="order_site",
|
"account_id": account_id,
|
||||||
source_order_id="MIG-0090",
|
"lease_id": lease_id,
|
||||||
source_order_item_id="MIG-0090-2",
|
"exchange_status": "points_short",
|
||||||
execution_status="ready",
|
"issue_code": "",
|
||||||
binding_status="not_started",
|
"last_error": "",
|
||||||
exchange_status="not_started",
|
},
|
||||||
issue_code="no_eligible_account",
|
),
|
||||||
last_error="当前没有可用账号",
|
(
|
||||||
)
|
unassigned_id,
|
||||||
session.add_all([broken, unassigned])
|
"MIG-0090-2",
|
||||||
session.commit()
|
{
|
||||||
broken_id = broken.id
|
"account_id": None,
|
||||||
unassigned_id = unassigned.id
|
"lease_id": None,
|
||||||
|
"exchange_status": "not_started",
|
||||||
|
"issue_code": "no_eligible_account",
|
||||||
|
"last_error": "当前没有可用账号",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
):
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
INSERT INTO platform_fulfillment_tasks (
|
||||||
|
id, source_system, source_order_id,
|
||||||
|
source_order_item_id, account_id, lease_id,
|
||||||
|
execution_status, binding_status, exchange_status,
|
||||||
|
issue_code, last_error, created_at, updated_at
|
||||||
|
) VALUES (
|
||||||
|
:id, 'order_site', 'MIG-0090',
|
||||||
|
:source_order_item_id, :account_id, :lease_id,
|
||||||
|
'ready', 'not_started', :exchange_status,
|
||||||
|
:issue_code, :last_error,
|
||||||
|
UTC_TIMESTAMP(), UTC_TIMESTAMP()
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"id": task_id,
|
||||||
|
"source_order_item_id": item_id,
|
||||||
|
**extra,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
command.upgrade(cfg, "20261118_0090")
|
command.upgrade(cfg, "20261118_0090")
|
||||||
|
|
||||||
with Session(mig_engine) as session:
|
with mig_engine.connect() as conn:
|
||||||
repaired = session.get(PlatformFulfillmentTask, broken_id)
|
rows = {
|
||||||
untouched = session.get(PlatformFulfillmentTask, unassigned_id)
|
int(row["id"]): row
|
||||||
assert repaired is not None
|
for row in conn.execute(
|
||||||
assert repaired.execution_status == "allocated"
|
text(
|
||||||
assert repaired.issue_code == "points_short"
|
"""
|
||||||
assert repaired.last_error == "账号积分不足,可充值后继续"
|
SELECT id, execution_status, issue_code, last_error,
|
||||||
assert repaired.next_allocate_at is None
|
next_allocate_at
|
||||||
assert untouched is not None
|
FROM platform_fulfillment_tasks
|
||||||
assert untouched.execution_status == "ready"
|
WHERE id IN (:broken_id, :unassigned_id)
|
||||||
assert untouched.issue_code == "no_eligible_account"
|
"""
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"broken_id": broken_id,
|
||||||
|
"unassigned_id": unassigned_id,
|
||||||
|
},
|
||||||
|
).mappings()
|
||||||
|
}
|
||||||
|
repaired = rows[broken_id]
|
||||||
|
untouched = rows[unassigned_id]
|
||||||
|
assert repaired["execution_status"] == "allocated"
|
||||||
|
assert repaired["issue_code"] == "points_short"
|
||||||
|
assert repaired["last_error"] == "账号积分不足,可充值后继续"
|
||||||
|
assert repaired["next_allocate_at"] is None
|
||||||
|
assert untouched["execution_status"] == "ready"
|
||||||
|
assert untouched["issue_code"] == "no_eligible_account"
|
||||||
finally:
|
finally:
|
||||||
database_module.DATABASE_URL = original_url
|
database_module.DATABASE_URL = original_url
|
||||||
mig_engine.dispose()
|
mig_engine.dispose()
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""履约任务保存兑换结果图片。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "20261121_0105"
|
||||||
|
down_revision = "20261121_0104"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def _column_exists(column: str) -> bool:
|
||||||
|
return bool(
|
||||||
|
op.get_bind()
|
||||||
|
.execute(
|
||||||
|
sa.text(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM information_schema.columns
|
||||||
|
WHERE table_schema = DATABASE()
|
||||||
|
AND table_name = 'platform_fulfillment_tasks'
|
||||||
|
AND column_name = :column
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{"column": column},
|
||||||
|
)
|
||||||
|
.scalar()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
if not _column_exists("exchange_result_image_key"):
|
||||||
|
op.add_column(
|
||||||
|
"platform_fulfillment_tasks",
|
||||||
|
sa.Column(
|
||||||
|
"exchange_result_image_key",
|
||||||
|
sa.String(length=512),
|
||||||
|
nullable=False,
|
||||||
|
server_default="",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if not _column_exists("exchange_result_image_saved_at"):
|
||||||
|
op.add_column(
|
||||||
|
"platform_fulfillment_tasks",
|
||||||
|
sa.Column(
|
||||||
|
"exchange_result_image_saved_at",
|
||||||
|
sa.DateTime(),
|
||||||
|
nullable=True,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
if _column_exists("exchange_result_image_saved_at"):
|
||||||
|
op.drop_column("platform_fulfillment_tasks", "exchange_result_image_saved_at")
|
||||||
|
if _column_exists("exchange_result_image_key"):
|
||||||
|
op.drop_column("platform_fulfillment_tasks", "exchange_result_image_key")
|
||||||
@@ -2043,6 +2043,12 @@ class PlatformFulfillmentTask(Base):
|
|||||||
exchange_task_id: Mapped[int | None] = mapped_column(
|
exchange_task_id: Mapped[int | None] = mapped_column(
|
||||||
ForeignKey("douyu_tasks.id", ondelete="SET NULL"), nullable=True
|
ForeignKey("douyu_tasks.id", ondelete="SET NULL"), nullable=True
|
||||||
)
|
)
|
||||||
|
exchange_result_image_key: Mapped[str] = mapped_column(
|
||||||
|
String(512), nullable=False, default="", server_default=""
|
||||||
|
)
|
||||||
|
exchange_result_image_saved_at: Mapped[datetime | None] = mapped_column(
|
||||||
|
UTCDateTime, nullable=True
|
||||||
|
)
|
||||||
binding_status: Mapped[str] = mapped_column(
|
binding_status: Mapped[str] = mapped_column(
|
||||||
String(24), nullable=False, default="not_started", server_default="not_started"
|
String(24), nullable=False, default="not_started", server_default="not_started"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -10,9 +10,11 @@ from weakref import WeakKeyDictionary
|
|||||||
from fastapi import (
|
from fastapi import (
|
||||||
APIRouter,
|
APIRouter,
|
||||||
Depends,
|
Depends,
|
||||||
|
File,
|
||||||
HTTPException,
|
HTTPException,
|
||||||
Query,
|
Query,
|
||||||
Request,
|
Request,
|
||||||
|
UploadFile,
|
||||||
WebSocket,
|
WebSocket,
|
||||||
WebSocketDisconnect,
|
WebSocketDisconnect,
|
||||||
)
|
)
|
||||||
@@ -47,6 +49,7 @@ from ..schemas import (
|
|||||||
CookieReloginRequest,
|
CookieReloginRequest,
|
||||||
DouyuConfigOut,
|
DouyuConfigOut,
|
||||||
DouyuConfigUpdate,
|
DouyuConfigUpdate,
|
||||||
|
DouyuExchangeResultImageOut,
|
||||||
DouyuGoodsOut,
|
DouyuGoodsOut,
|
||||||
DouyuTaskAccountOut,
|
DouyuTaskAccountOut,
|
||||||
DouyuTaskBatchRequest,
|
DouyuTaskBatchRequest,
|
||||||
@@ -63,6 +66,10 @@ from ..services.douyu_batch_launcher import (
|
|||||||
DOUYU_MAX_ACTIVE_BATCHES,
|
DOUYU_MAX_ACTIVE_BATCHES,
|
||||||
start_douyu_batch,
|
start_douyu_batch,
|
||||||
)
|
)
|
||||||
|
from ..services.douyu_exchange_result_image import (
|
||||||
|
ExchangeResultImageError,
|
||||||
|
save_exchange_result_image,
|
||||||
|
)
|
||||||
from ..services.douyu_goods_service import serialize_goods
|
from ..services.douyu_goods_service import serialize_goods
|
||||||
from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry
|
from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry
|
||||||
from ..services.douyu_service import (
|
from ..services.douyu_service import (
|
||||||
@@ -80,6 +87,8 @@ from ..services.douyu_service import (
|
|||||||
douyu_task_payload,
|
douyu_task_payload,
|
||||||
ensure_douyu_config,
|
ensure_douyu_config,
|
||||||
)
|
)
|
||||||
|
from ..services.file_service import FileUploadError
|
||||||
|
from ..services.file_storage import StorageUnavailableError, max_upload_size_bytes
|
||||||
from ..services.platform_fulfillment import service as platform_fulfillment_service
|
from ..services.platform_fulfillment import service as platform_fulfillment_service
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/douyu", tags=["斗鱼活动"])
|
router = APIRouter(prefix="/api/douyu", tags=["斗鱼活动"])
|
||||||
@@ -1241,6 +1250,70 @@ def cleanup_orphan_tasks(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/tasks/{task_id}/exchange-result-image",
|
||||||
|
response_model=DouyuExchangeResultImageOut,
|
||||||
|
)
|
||||||
|
def upload_exchange_result_image(
|
||||||
|
task_id: int,
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("douyu:task")),
|
||||||
|
) -> DouyuExchangeResultImageOut:
|
||||||
|
"""保存兑换结果 PNG,并绑定到对应履约任务供后续查看。"""
|
||||||
|
task = _visible_tasks_query(db, current).filter(DouyuTask.id == task_id).first()
|
||||||
|
if task is None:
|
||||||
|
raise HTTPException(status_code=404, detail="任务不存在")
|
||||||
|
platform_task = (
|
||||||
|
db.query(PlatformFulfillmentTask)
|
||||||
|
.filter(PlatformFulfillmentTask.id == int(task.platform_task_id))
|
||||||
|
.with_for_update()
|
||||||
|
.first()
|
||||||
|
if task.platform_task_id
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
limit = max_upload_size_bytes()
|
||||||
|
data = file.file.read(limit + 1)
|
||||||
|
if len(data) > limit:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=413,
|
||||||
|
detail=f"文件不能超过 {limit // (1024 * 1024)}MB",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
saved = save_exchange_result_image(
|
||||||
|
db,
|
||||||
|
task,
|
||||||
|
data=data,
|
||||||
|
filename=(file.filename or "").strip(),
|
||||||
|
uploader_id=int(current.id),
|
||||||
|
platform_task=platform_task,
|
||||||
|
)
|
||||||
|
except ExchangeResultImageError as exc:
|
||||||
|
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||||
|
except FileUploadError as exc:
|
||||||
|
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||||
|
except StorageUnavailableError as exc:
|
||||||
|
raise HTTPException(status_code=503, detail="文件存储暂时不可用") from exc
|
||||||
|
|
||||||
|
record_audit(
|
||||||
|
db,
|
||||||
|
current,
|
||||||
|
action="douyu:task:exchange_result_image",
|
||||||
|
target=f"douyu_task:{task.id}",
|
||||||
|
detail={
|
||||||
|
"platform_task_id": task.platform_task_id,
|
||||||
|
"object_key": saved["objectKey"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return DouyuExchangeResultImageOut(
|
||||||
|
object_key=str(saved["objectKey"]),
|
||||||
|
url=str(saved["url"]),
|
||||||
|
saved_at=cast(datetime, saved["savedAt"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/tasks/{task_id}", response_model=DouyuTaskOut)
|
@router.get("/tasks/{task_id}", response_model=DouyuTaskOut)
|
||||||
def get_task(
|
def get_task(
|
||||||
task_id: int,
|
task_id: int,
|
||||||
|
|||||||
@@ -1672,6 +1672,12 @@ class DouyuTaskOut(BaseModel):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class DouyuExchangeResultImageOut(BaseModel):
|
||||||
|
object_key: str
|
||||||
|
url: str
|
||||||
|
saved_at: datetime
|
||||||
|
|
||||||
|
|
||||||
class DouyuGoodsOut(BaseModel):
|
class DouyuGoodsOut(BaseModel):
|
||||||
id: int
|
id: int
|
||||||
commodity_id: str
|
commodity_id: str
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""保存斗鱼兑换结果图片,供履约任务长期查看、复制和下载。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..models import DouyuTask, PlatformFulfillmentTask
|
||||||
|
from .file_service import build_file_url, sniff_content_type, upload_file_asset
|
||||||
|
|
||||||
|
EXCHANGE_RESULT_TASK_TYPES = frozenset(
|
||||||
|
{
|
||||||
|
"exchange_goods",
|
||||||
|
"pay_locked_order",
|
||||||
|
"exchange_esports_goods",
|
||||||
|
"exchange_xpd_goods",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
EXCHANGE_RESULT_SCENE = "exchange-result"
|
||||||
|
|
||||||
|
|
||||||
|
class ExchangeResultImageError(ValueError):
|
||||||
|
"""兑换结果图片不符合任务状态或文件契约。"""
|
||||||
|
|
||||||
|
|
||||||
|
def _result_image(task: DouyuTask) -> dict[str, Any]:
|
||||||
|
result = task.result if isinstance(task.result, dict) else {}
|
||||||
|
image = result.get("exchange_result_image")
|
||||||
|
return image if isinstance(image, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def exchange_result_image_payload(
|
||||||
|
task: DouyuTask,
|
||||||
|
platform_task: PlatformFulfillmentTask | None = None,
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
"""返回任务已保存图片的稳定代理地址;没有保存时返回 ``None``。"""
|
||||||
|
image = _result_image(task)
|
||||||
|
object_key = str(
|
||||||
|
(platform_task.exchange_result_image_key if platform_task else "")
|
||||||
|
or image.get("object_key")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
if not object_key:
|
||||||
|
return None
|
||||||
|
saved_at = (
|
||||||
|
platform_task.exchange_result_image_saved_at
|
||||||
|
if platform_task
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
if saved_at is None:
|
||||||
|
raw_saved_at = image.get("saved_at")
|
||||||
|
if isinstance(raw_saved_at, str):
|
||||||
|
try:
|
||||||
|
saved_at = datetime.fromisoformat(raw_saved_at)
|
||||||
|
except ValueError:
|
||||||
|
saved_at = None
|
||||||
|
return {
|
||||||
|
"objectKey": object_key,
|
||||||
|
"url": build_file_url(object_key),
|
||||||
|
"savedAt": saved_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def save_exchange_result_image(
|
||||||
|
db: Session,
|
||||||
|
task: DouyuTask,
|
||||||
|
*,
|
||||||
|
data: bytes,
|
||||||
|
filename: str = "",
|
||||||
|
uploader_id: int,
|
||||||
|
platform_task: PlatformFulfillmentTask | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""保存 PNG 并把对象 key 同时写回斗鱼任务和履约任务。
|
||||||
|
|
||||||
|
重复调用是幂等的:已有图片直接返回,不再产生第二份对象。
|
||||||
|
"""
|
||||||
|
if task.task_type not in EXCHANGE_RESULT_TASK_TYPES:
|
||||||
|
raise ExchangeResultImageError("当前任务不是兑换任务")
|
||||||
|
if task.status != "success":
|
||||||
|
raise ExchangeResultImageError("只有兑换成功的任务可以保存结果图片")
|
||||||
|
if sniff_content_type(data) != "image/png":
|
||||||
|
raise ExchangeResultImageError("兑换结果图片必须是 PNG")
|
||||||
|
|
||||||
|
existing = exchange_result_image_payload(task, platform_task)
|
||||||
|
if existing is not None:
|
||||||
|
if platform_task and not platform_task.exchange_result_image_key:
|
||||||
|
platform_task.exchange_result_image_key = str(existing["objectKey"])
|
||||||
|
platform_task.exchange_result_image_saved_at = (
|
||||||
|
existing["savedAt"] or datetime.now(UTC).replace(microsecond=0)
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
return existing
|
||||||
|
|
||||||
|
uploaded = upload_file_asset(
|
||||||
|
db,
|
||||||
|
data=data,
|
||||||
|
filename=filename or f"douyu-exchange-result-{task.id}.png",
|
||||||
|
content_type="image/png",
|
||||||
|
scene=EXCHANGE_RESULT_SCENE,
|
||||||
|
uploader_type="user",
|
||||||
|
uploader_id=str(uploader_id),
|
||||||
|
)
|
||||||
|
saved_at = datetime.now(UTC).replace(microsecond=0)
|
||||||
|
result = dict(task.result or {})
|
||||||
|
result["exchange_result_image"] = {
|
||||||
|
"object_key": uploaded.object_key,
|
||||||
|
"content_type": uploaded.content_type,
|
||||||
|
"size": uploaded.size,
|
||||||
|
"saved_at": saved_at.isoformat(),
|
||||||
|
}
|
||||||
|
task.result = result
|
||||||
|
if platform_task is not None:
|
||||||
|
platform_task.exchange_task_id = int(task.id)
|
||||||
|
platform_task.exchange_result_image_key = uploaded.object_key
|
||||||
|
platform_task.exchange_result_image_saved_at = saved_at
|
||||||
|
db.commit()
|
||||||
|
return {
|
||||||
|
"objectKey": uploaded.object_key,
|
||||||
|
"url": uploaded.url,
|
||||||
|
"savedAt": saved_at,
|
||||||
|
}
|
||||||
@@ -56,6 +56,7 @@ from ..external_order_source import (
|
|||||||
list_pending_manual_fulfillments,
|
list_pending_manual_fulfillments,
|
||||||
lookup_pending_manual_fulfillment,
|
lookup_pending_manual_fulfillment,
|
||||||
)
|
)
|
||||||
|
from ..file_service import build_file_url
|
||||||
from .account_selector import (
|
from .account_selector import (
|
||||||
AccountCandidate,
|
AccountCandidate,
|
||||||
capability_candidate_accounts,
|
capability_candidate_accounts,
|
||||||
@@ -662,6 +663,8 @@ def record_douyu_operation_started(
|
|||||||
payload: dict[str, Any] | None = None,
|
payload: dict[str, Any] | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""记录履约上下文发起的斗鱼操作,账号任务结果由执行器补写。"""
|
"""记录履约上下文发起的斗鱼操作,账号任务结果由执行器补写。"""
|
||||||
|
if task_type == "exchange_goods" and len(douyu_task_ids) == 1:
|
||||||
|
task.exchange_task_id = int(douyu_task_ids[0])
|
||||||
_append_event(
|
_append_event(
|
||||||
db,
|
db,
|
||||||
task.id,
|
task.id,
|
||||||
@@ -1056,6 +1059,7 @@ def _task_out(
|
|||||||
task: PlatformFulfillmentTask,
|
task: PlatformFulfillmentTask,
|
||||||
*,
|
*,
|
||||||
include_qr: bool = False,
|
include_qr: bool = False,
|
||||||
|
include_exchange_task: bool = False,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
account = (
|
account = (
|
||||||
db.query(Account).filter(Account.id == task.account_id).first()
|
db.query(Account).filter(Account.id == task.account_id).first()
|
||||||
@@ -1078,6 +1082,18 @@ def _task_out(
|
|||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||||
|
exchange_task_id = task.exchange_task_id
|
||||||
|
if exchange_task_id is None and include_exchange_task:
|
||||||
|
exchange_task_id = (
|
||||||
|
db.query(DouyuTask.id)
|
||||||
|
.filter(
|
||||||
|
DouyuTask.platform_task_id == task.id,
|
||||||
|
DouyuTask.task_type == "exchange_goods",
|
||||||
|
)
|
||||||
|
.order_by(DouyuTask.id.desc())
|
||||||
|
.limit(1)
|
||||||
|
.scalar()
|
||||||
|
)
|
||||||
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
||||||
pending_role = pending_binding_role_from_result(bind_result)
|
pending_role = pending_binding_role_from_result(bind_result)
|
||||||
return {
|
return {
|
||||||
@@ -1163,6 +1179,16 @@ def _task_out(
|
|||||||
if bind_task
|
if bind_task
|
||||||
else None
|
else None
|
||||||
),
|
),
|
||||||
|
"exchangeTaskId": exchange_task_id,
|
||||||
|
"exchangeResultImage": (
|
||||||
|
{
|
||||||
|
"objectKey": task.exchange_result_image_key,
|
||||||
|
"url": build_file_url(task.exchange_result_image_key),
|
||||||
|
"savedAt": task.exchange_result_image_saved_at,
|
||||||
|
}
|
||||||
|
if task.exchange_result_image_key
|
||||||
|
else None
|
||||||
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -1189,7 +1215,7 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]:
|
|||||||
else {}
|
else {}
|
||||||
)
|
)
|
||||||
return {
|
return {
|
||||||
"task": _task_out(db, task, include_qr=True),
|
"task": _task_out(db, task, include_qr=True, include_exchange_task=True),
|
||||||
"events": [
|
"events": [
|
||||||
{
|
{
|
||||||
"id": event.id,
|
"id": event.id,
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import api from './client';
|
import api from './client';
|
||||||
import type {
|
import type {
|
||||||
DouyuConfig,
|
DouyuConfig,
|
||||||
|
DouyuExchangeResultImage,
|
||||||
DouyuGoodsItem,
|
DouyuGoodsItem,
|
||||||
DouyuRechargeChannel,
|
DouyuRechargeChannel,
|
||||||
DouyuTaskAccountItem,
|
DouyuTaskAccountItem,
|
||||||
@@ -55,6 +56,14 @@ export const douyuApi = {
|
|||||||
listTasksPaged: (params: PageParams & { batch_id?: string; include_detail?: boolean }) =>
|
listTasksPaged: (params: PageParams & { batch_id?: string; include_detail?: boolean }) =>
|
||||||
api.get<PaginatedResponse<DouyuTaskItem>, PaginatedResponse<DouyuTaskItem>>('/douyu/tasks', { params }),
|
api.get<PaginatedResponse<DouyuTaskItem>, PaginatedResponse<DouyuTaskItem>>('/douyu/tasks', { params }),
|
||||||
getTask: (taskId: number) => api.get<DouyuTaskItem, DouyuTaskItem>(`/douyu/tasks/${taskId}`),
|
getTask: (taskId: number) => api.get<DouyuTaskItem, DouyuTaskItem>(`/douyu/tasks/${taskId}`),
|
||||||
|
saveExchangeResultImage: (taskId: number, file: File) => {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('file', file);
|
||||||
|
return api.post<DouyuExchangeResultImage, DouyuExchangeResultImage>(
|
||||||
|
`/douyu/tasks/${taskId}/exchange-result-image`,
|
||||||
|
form,
|
||||||
|
);
|
||||||
|
},
|
||||||
cleanupOrphans: () =>
|
cleanupOrphans: () =>
|
||||||
api.post<{ message: string; cleaned: number; success: boolean }, { message: string; cleaned: number; success: boolean }>('/douyu/tasks/cleanup-orphans'),
|
api.post<{ message: string; cleaned: number; success: boolean }, { message: string; cleaned: number; success: boolean }>('/douyu/tasks/cleanup-orphans'),
|
||||||
stopBatch: (batchId: string) => api.post<MessageResponse, MessageResponse>(`/douyu/stop/${batchId}`),
|
stopBatch: (batchId: string) => api.post<MessageResponse, MessageResponse>(`/douyu/stop/${batchId}`),
|
||||||
|
|||||||
@@ -790,6 +790,12 @@ export interface DouyuTaskItem {
|
|||||||
finished_at: string | null;
|
finished_at: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface DouyuExchangeResultImage {
|
||||||
|
object_key: string;
|
||||||
|
url: string;
|
||||||
|
saved_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface DouyuGoodsItem {
|
export interface DouyuGoodsItem {
|
||||||
id: number;
|
id: number;
|
||||||
commodity_id: string;
|
commodity_id: string;
|
||||||
@@ -2238,6 +2244,12 @@ export interface PlatformFulfillmentTask {
|
|||||||
account: PlatformFulfillmentAccount | null;
|
account: PlatformFulfillmentAccount | null;
|
||||||
lease: { id: number; status: string; expiresAt: string | null } | null;
|
lease: { id: number; status: string; expiresAt: string | null } | null;
|
||||||
bindTask: PlatformFulfillmentBindTask | null;
|
bindTask: PlatformFulfillmentBindTask | null;
|
||||||
|
exchangeTaskId: number | null;
|
||||||
|
exchangeResultImage: {
|
||||||
|
objectKey: string;
|
||||||
|
url: string;
|
||||||
|
savedAt: string | null;
|
||||||
|
} | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PlatformFulfillmentEvent {
|
export interface PlatformFulfillmentEvent {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { Button, Spin } from 'antd';
|
import { Button, Spin } from 'antd';
|
||||||
import type { DouyuTaskItem } from '../api/types';
|
import type { DouyuTaskItem } from '../api/types';
|
||||||
import { getExchangeImage } from '../utils/exchangeImage';
|
import { getExchangeImage, savedExchangeImage } from '../utils/exchangeImage';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
task: DouyuTaskItem;
|
task: DouyuTaskItem;
|
||||||
@@ -13,15 +13,22 @@ export default function ExchangeResultImage({ task, onClick, variant = 'compact'
|
|||||||
const [url, setUrl] = useState('');
|
const [url, setUrl] = useState('');
|
||||||
const [failed, setFailed] = useState(false);
|
const [failed, setFailed] = useState(false);
|
||||||
const [gen, setGen] = useState(0);
|
const [gen, setGen] = useState(0);
|
||||||
|
const savedObjectKey = savedExchangeImage(task)?.objectKey || '';
|
||||||
|
const taskRef = useRef(task);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
taskRef.current = task;
|
||||||
|
}, [task]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let alive = true;
|
let alive = true;
|
||||||
|
setUrl('');
|
||||||
setFailed(false);
|
setFailed(false);
|
||||||
getExchangeImage(task)
|
getExchangeImage(taskRef.current)
|
||||||
.then(({ url }) => { if (alive) setUrl(url); })
|
.then(({ url }) => { if (alive) setUrl(url); })
|
||||||
.catch(() => { if (alive) setFailed(true); });
|
.catch(() => { if (alive) setFailed(true); });
|
||||||
return () => { alive = false; };
|
return () => { alive = false; };
|
||||||
}, [task, gen]);
|
}, [task.id, task.finished_at, savedObjectKey, gen]);
|
||||||
|
|
||||||
if (failed) {
|
if (failed) {
|
||||||
return (
|
return (
|
||||||
@@ -55,7 +62,7 @@ export default function ExchangeResultImage({ task, onClick, variant = 'compact'
|
|||||||
detail
|
detail
|
||||||
? {
|
? {
|
||||||
width: '100%',
|
width: '100%',
|
||||||
maxWidth: 320,
|
maxWidth: 480,
|
||||||
height: 'auto',
|
height: 'auto',
|
||||||
objectFit: 'contain',
|
objectFit: 'contain',
|
||||||
borderRadius: 8,
|
borderRadius: 8,
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import type { Dayjs } from 'dayjs';
|
import type { Dayjs } from 'dayjs';
|
||||||
import { Alert, Button, Card, DatePicker, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
|
import { Alert, Button, Card, DatePicker, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
|
||||||
import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons';
|
import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, DownloadOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import { douyuApi, platformFulfillmentApi } from '../api/modules';
|
import { douyuApi, platformFulfillmentApi } from '../api/modules';
|
||||||
import type { DouyuGoodsItem, DouyuTaskItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules';
|
import type { DouyuGoodsItem, DouyuTaskItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules';
|
||||||
import ExchangeResultImage from '../components/ExchangeResultImage';
|
import ExchangeResultImage from '../components/ExchangeResultImage';
|
||||||
|
import { copyImageToClipboard, fetchExchangeImageBlob, getExchangeImage, isExchangeTask } from '../utils/exchangeImage';
|
||||||
import { TASK_STATUS_COLORS, TASK_STATUS_LABELS, taskQrUrl } from './douyu-tasks/config';
|
import { TASK_STATUS_COLORS, TASK_STATUS_LABELS, taskQrUrl } from './douyu-tasks/config';
|
||||||
import { getErrorMessage } from '../utils/error';
|
import { getErrorMessage } from '../utils/error';
|
||||||
import { message } from '../utils/antdMessage';
|
import { message } from '../utils/antdMessage';
|
||||||
@@ -342,6 +343,11 @@ export default function PlatformFulfillmentPage() {
|
|||||||
const [douyuActionType, setDouyuActionType] = useState('');
|
const [douyuActionType, setDouyuActionType] = useState('');
|
||||||
const [douyuActionBatchId, setDouyuActionBatchId] = useState('');
|
const [douyuActionBatchId, setDouyuActionBatchId] = useState('');
|
||||||
const [douyuActionTask, setDouyuActionTask] = useState<DouyuTaskItem | null>(null);
|
const [douyuActionTask, setDouyuActionTask] = useState<DouyuTaskItem | null>(null);
|
||||||
|
const [exchangeImageViewer, setExchangeImageViewer] = useState<{
|
||||||
|
url: string;
|
||||||
|
title: string;
|
||||||
|
} | null>(null);
|
||||||
|
const exchangeImageSaveAttempts = useRef(new Set<number>());
|
||||||
const [goldAmount, setGoldAmount] = useState(30);
|
const [goldAmount, setGoldAmount] = useState(30);
|
||||||
const [giftCount, setGiftCount] = useState(1);
|
const [giftCount, setGiftCount] = useState(1);
|
||||||
|
|
||||||
@@ -427,6 +433,8 @@ export default function PlatformFulfillmentPage() {
|
|||||||
}, [douyuActionBatchId]);
|
}, [douyuActionBatchId]);
|
||||||
|
|
||||||
const selected = detail?.task || null;
|
const selected = detail?.task || null;
|
||||||
|
const selectedExchangeTaskId = selected?.exchangeTaskId ?? null;
|
||||||
|
const selectedExchangeImageKey = selected?.exchangeResultImage?.objectKey || '';
|
||||||
const qrValue = selected?.bindTask?.qrUrl || '';
|
const qrValue = selected?.bindTask?.qrUrl || '';
|
||||||
const douyuActionQrValue = douyuActionTask ? taskQrUrl(douyuActionTask) : '';
|
const douyuActionQrValue = douyuActionTask ? taskQrUrl(douyuActionTask) : '';
|
||||||
|
|
||||||
@@ -434,6 +442,31 @@ export default function PlatformFulfillmentPage() {
|
|||||||
if (qrValue) setQrOpen(true);
|
if (qrValue) setQrOpen(true);
|
||||||
}, [qrValue]);
|
}, [qrValue]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (
|
||||||
|
!selectedId
|
||||||
|
|| !selectedExchangeTaskId
|
||||||
|
|| selectedExchangeImageKey
|
||||||
|
|| exchangeImageSaveAttempts.current.has(selectedExchangeTaskId)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
exchangeImageSaveAttempts.current.add(selectedExchangeTaskId);
|
||||||
|
void douyuApi.getTask(selectedExchangeTaskId)
|
||||||
|
.then(async (task) => {
|
||||||
|
if (task.status !== 'success' || !isExchangeTask(task)) return false;
|
||||||
|
await getExchangeImage(task);
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.then((saved) => {
|
||||||
|
if (saved) void loadDetail(selectedId, true);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
// 图片补存失败不影响履约详情;下次重新打开详情时会再次尝试。
|
||||||
|
exchangeImageSaveAttempts.current.delete(selectedExchangeTaskId);
|
||||||
|
});
|
||||||
|
}, [selectedId, selectedExchangeTaskId, selectedExchangeImageKey, loadDetail]);
|
||||||
|
|
||||||
const sync = async () => {
|
const sync = async () => {
|
||||||
setSyncing(true);
|
setSyncing(true);
|
||||||
try {
|
try {
|
||||||
@@ -652,6 +685,28 @@ export default function PlatformFulfillmentPage() {
|
|||||||
void loadTasks();
|
void loadTasks();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const copyExchangeImageViewer = async (url = exchangeImageViewer?.url) => {
|
||||||
|
if (!url) return;
|
||||||
|
try {
|
||||||
|
const blob = await fetchExchangeImageBlob(url);
|
||||||
|
await copyImageToClipboard(blob);
|
||||||
|
message.success('兑换结果图片已复制');
|
||||||
|
} catch (error) {
|
||||||
|
message.error(`复制兑换结果图片失败:${getErrorMessage(error)}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const downloadExchangeImageViewer = (
|
||||||
|
url = exchangeImageViewer?.url,
|
||||||
|
title = exchangeImageViewer?.title,
|
||||||
|
) => {
|
||||||
|
if (!url) return;
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = `${title || '斗鱼兑换结果'}.png`;
|
||||||
|
link.click();
|
||||||
|
};
|
||||||
|
|
||||||
const openMapping = async (task?: PlatformFulfillmentTask) => {
|
const openMapping = async (task?: PlatformFulfillmentTask) => {
|
||||||
setMappingSku(task?.internalSkuKey || '');
|
setMappingSku(task?.internalSkuKey || '');
|
||||||
setMappingGoodsId(task?.commodityId || '');
|
setMappingGoodsId(task?.commodityId || '');
|
||||||
@@ -1147,6 +1202,55 @@ export default function PlatformFulfillmentPage() {
|
|||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{selected.exchangeResultImage ? (
|
||||||
|
<Card
|
||||||
|
size="small"
|
||||||
|
title="兑换结果凭证"
|
||||||
|
extra={(
|
||||||
|
<Space>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
icon={<CopyOutlined />}
|
||||||
|
onClick={() => void copyExchangeImageViewer(selected.exchangeResultImage!.url)}
|
||||||
|
>
|
||||||
|
复制图片
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
icon={<DownloadOutlined />}
|
||||||
|
onClick={() => downloadExchangeImageViewer(
|
||||||
|
selected.exchangeResultImage!.url,
|
||||||
|
`斗鱼兑换结果-${selected.skuName || selected.platformOrderId}`,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
下载图片
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
onClick={() => setExchangeImageViewer({
|
||||||
|
url: selected.exchangeResultImage!.url,
|
||||||
|
title: `斗鱼兑换结果-${selected.skuName || selected.platformOrderId}`,
|
||||||
|
})}
|
||||||
|
style={{ cursor: 'zoom-in', textAlign: 'center' }}
|
||||||
|
title="点击查看大图"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={selected.exchangeResultImage.url}
|
||||||
|
alt="兑换结果凭证"
|
||||||
|
style={{
|
||||||
|
width: '100%',
|
||||||
|
maxWidth: 480,
|
||||||
|
height: 'auto',
|
||||||
|
borderRadius: 8,
|
||||||
|
border: '1px solid #f0f0f0',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
display: 'grid',
|
display: 'grid',
|
||||||
@@ -1348,7 +1452,14 @@ export default function PlatformFulfillmentPage() {
|
|||||||
<QRCode value={douyuActionQrValue} size={260} />
|
<QRCode value={douyuActionQrValue} size={260} />
|
||||||
) : null}
|
) : null}
|
||||||
{douyuActionType === 'exchange_goods' && douyuActionTask.status === 'success' ? (
|
{douyuActionType === 'exchange_goods' && douyuActionTask.status === 'success' ? (
|
||||||
<ExchangeResultImage task={douyuActionTask} variant="detail" />
|
<ExchangeResultImage
|
||||||
|
task={douyuActionTask}
|
||||||
|
variant="detail"
|
||||||
|
onClick={(_task, url) => setExchangeImageViewer({
|
||||||
|
url,
|
||||||
|
title: `斗鱼兑换结果-${selected?.skuName || selected?.platformOrderId || douyuActionTask.id}`,
|
||||||
|
})}
|
||||||
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
@@ -1357,6 +1468,33 @@ export default function PlatformFulfillmentPage() {
|
|||||||
</Space>
|
</Space>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
open={Boolean(exchangeImageViewer)}
|
||||||
|
title="兑换结果图片"
|
||||||
|
width={620}
|
||||||
|
centered
|
||||||
|
footer={(
|
||||||
|
<Space>
|
||||||
|
<Button onClick={() => setExchangeImageViewer(null)}>关闭</Button>
|
||||||
|
<Button icon={<CopyOutlined />} onClick={() => void copyExchangeImageViewer()}>
|
||||||
|
复制图片
|
||||||
|
</Button>
|
||||||
|
<Button icon={<DownloadOutlined />} onClick={() => downloadExchangeImageViewer()}>
|
||||||
|
下载图片
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
)}
|
||||||
|
onCancel={() => setExchangeImageViewer(null)}
|
||||||
|
>
|
||||||
|
{exchangeImageViewer ? (
|
||||||
|
<img
|
||||||
|
src={exchangeImageViewer.url}
|
||||||
|
alt="兑换结果"
|
||||||
|
style={{ width: '100%', maxHeight: '72vh', objectFit: 'contain', display: 'block' }}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</Modal>
|
||||||
|
|
||||||
<Modal open={qrOpen && Boolean(qrValue)} title="客户扫码绑定游戏角色" footer={null} onCancel={() => setQrOpen(false)}>
|
<Modal open={qrOpen && Boolean(qrValue)} title="客户扫码绑定游戏角色" footer={null} onCancel={() => setQrOpen(false)}>
|
||||||
<Space direction="vertical" align="center" style={{ width: '100%' }}>
|
<Space direction="vertical" align="center" style={{ width: '100%' }}>
|
||||||
{qrValue ? <QRCode value={qrValue} size={260} /> : null}
|
{qrValue ? <QRCode value={qrValue} size={260} /> : null}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { DouyuTaskItem } from '../api/types';
|
import type { DouyuTaskItem } from '../api/types';
|
||||||
|
import { douyuApi } from '../api/douyu';
|
||||||
|
|
||||||
const EXCHANGE_TASK_TYPES = new Set([
|
const EXCHANGE_TASK_TYPES = new Set([
|
||||||
'exchange_goods',
|
'exchange_goods',
|
||||||
@@ -124,6 +125,21 @@ function douyuImageData(task: DouyuTaskItem): ExchangeResultImageData {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function savedExchangeImage(task: DouyuTaskItem): {
|
||||||
|
objectKey: string;
|
||||||
|
url: string;
|
||||||
|
} | null {
|
||||||
|
const saved = task.result?.exchange_result_image;
|
||||||
|
if (!saved || typeof saved !== 'object' || Array.isArray(saved)) return null;
|
||||||
|
const record = saved as Record<string, unknown>;
|
||||||
|
const objectKey = typeof record.object_key === 'string' ? record.object_key : '';
|
||||||
|
if (!objectKey) return null;
|
||||||
|
const url = typeof record.url === 'string' && record.url
|
||||||
|
? record.url
|
||||||
|
: `/api/files/object?key=${encodeURIComponent(objectKey)}`;
|
||||||
|
return { objectKey, url };
|
||||||
|
}
|
||||||
|
|
||||||
export async function drawExchangeResultImage(
|
export async function drawExchangeResultImage(
|
||||||
data: ExchangeResultImageData,
|
data: ExchangeResultImageData,
|
||||||
): Promise<Blob> {
|
): Promise<Blob> {
|
||||||
@@ -188,9 +204,9 @@ export async function drawExchangeResultImage(
|
|||||||
ctx.stroke();
|
ctx.stroke();
|
||||||
|
|
||||||
// 商品名(最多两行)
|
// 商品名(最多两行)
|
||||||
const nameLines = wrapText(ctx, info.goodsName || '未知商品', CARD_W - 56).slice(0, 2);
|
|
||||||
ctx.fillStyle = '#ffffff';
|
ctx.fillStyle = '#ffffff';
|
||||||
ctx.font = `bold 17px ${FONT_FAMILY}`;
|
ctx.font = `bold 17px ${FONT_FAMILY}`;
|
||||||
|
const nameLines = wrapText(ctx, info.goodsName || '未知商品', CARD_W - 56).slice(0, 2);
|
||||||
let nameY = avatarY + avatarR + 26;
|
let nameY = avatarY + avatarR + 26;
|
||||||
for (const line of nameLines) {
|
for (const line of nameLines) {
|
||||||
ctx.fillText(line, CARD_W / 2, nameY);
|
ctx.fillText(line, CARD_W / 2, nameY);
|
||||||
@@ -259,6 +275,14 @@ export async function copyImageToClipboard(blob: Blob): Promise<void> {
|
|||||||
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
|
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function fetchExchangeImageBlob(url: string): Promise<Blob> {
|
||||||
|
const response = await fetch(url, { credentials: 'include' });
|
||||||
|
if (!response.ok) throw new Error(`图片读取失败(HTTP ${response.status})`);
|
||||||
|
const blob = await response.blob();
|
||||||
|
if (!blob.type.startsWith('image/')) throw new Error('返回内容不是图片');
|
||||||
|
return blob;
|
||||||
|
}
|
||||||
|
|
||||||
export function clipboardImageSupported(): boolean {
|
export function clipboardImageSupported(): boolean {
|
||||||
return typeof ClipboardItem !== 'undefined' && Boolean(navigator.clipboard?.write);
|
return typeof ClipboardItem !== 'undefined' && Boolean(navigator.clipboard?.write);
|
||||||
}
|
}
|
||||||
@@ -296,10 +320,59 @@ export async function getExchangeResultImage(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getExchangeImage(task: DouyuTaskItem): Promise<CachedImage> {
|
export async function getExchangeImage(task: DouyuTaskItem): Promise<CachedImage> {
|
||||||
return getExchangeResultImage(douyuImageData(task));
|
const saved = savedExchangeImage(task);
|
||||||
|
if (saved) {
|
||||||
|
const cacheKey = `douyu:${task.id}:saved:${saved.objectKey}`;
|
||||||
|
const cached = imageCache.get(cacheKey);
|
||||||
|
if (cached) return cached;
|
||||||
|
const pending = inflightImages.get(cacheKey);
|
||||||
|
if (pending) return pending;
|
||||||
|
const creating = fetchExchangeImageBlob(saved.url).then((blob) => {
|
||||||
|
const entry = { url: saved.url, blob };
|
||||||
|
imageCache.set(cacheKey, entry);
|
||||||
|
return entry;
|
||||||
|
});
|
||||||
|
inflightImages.set(cacheKey, creating);
|
||||||
|
try {
|
||||||
|
return await creating;
|
||||||
|
} finally {
|
||||||
|
inflightImages.delete(cacheKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const cacheKey = `douyu:${task.id}:generated`;
|
||||||
|
const cached = imageCache.get(cacheKey);
|
||||||
|
if (cached) return cached;
|
||||||
|
const pending = inflightImages.get(cacheKey);
|
||||||
|
if (pending) return pending;
|
||||||
|
const creating = (async () => {
|
||||||
|
const blob = await drawExchangeResultImage(douyuImageData(task));
|
||||||
|
let url = URL.createObjectURL(blob);
|
||||||
|
try {
|
||||||
|
const file = new File([blob], `douyu-exchange-result-${task.id}.png`, {
|
||||||
|
type: 'image/png',
|
||||||
|
});
|
||||||
|
const savedImage = await douyuApi.saveExchangeResultImage(task.id, file);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
url = savedImage.url;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('兑换结果图片保存失败,暂时保留本地图片', error);
|
||||||
|
}
|
||||||
|
const entry = { url, blob };
|
||||||
|
imageCache.set(cacheKey, entry);
|
||||||
|
return entry;
|
||||||
|
})();
|
||||||
|
inflightImages.set(cacheKey, creating);
|
||||||
|
try {
|
||||||
|
return await creating;
|
||||||
|
} finally {
|
||||||
|
inflightImages.delete(cacheKey);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearExchangeImageCache(): void {
|
export function clearExchangeImageCache(): void {
|
||||||
for (const entry of imageCache.values()) URL.revokeObjectURL(entry.url);
|
for (const entry of imageCache.values()) {
|
||||||
|
if (entry.url.startsWith('blob:')) URL.revokeObjectURL(entry.url);
|
||||||
|
}
|
||||||
imageCache.clear();
|
imageCache.clear();
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user