feat(fulfillment): 增加订单匹配起算时间
This commit is contained in:
@@ -188,6 +188,34 @@ class TestDegradation:
|
||||
|
||||
assert src.list_pending_manual_fulfillments(internal_sku_keys=[]) == []
|
||||
|
||||
def test_pending_lookup_passes_paid_at_cutoff(self, monkeypatch):
|
||||
monkeypatch.setenv("ORDER_SITE_DATABASE_URL", "postgresql://u:p@h:5432/db")
|
||||
monkeypatch.setenv("ORDER_SITE_LOOKUP_ENABLED", "true")
|
||||
cutoff = datetime(2026, 11, 18, 12, 0, tzinfo=UTC)
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def _rows(*, limit, internal_sku_keys, paid_at_from):
|
||||
captured.update(
|
||||
{
|
||||
"limit": limit,
|
||||
"internal_sku_keys": internal_sku_keys,
|
||||
"paid_at_from": paid_at_from,
|
||||
}
|
||||
)
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(src, "_fetch_pending_manual_fulfillments", _rows)
|
||||
|
||||
assert (
|
||||
src.list_pending_manual_fulfillments(
|
||||
limit=20,
|
||||
internal_sku_keys=["兔兔白日梦头盔"],
|
||||
paid_at_from=cutoff,
|
||||
)
|
||||
== []
|
||||
)
|
||||
assert captured["paid_at_from"] == cutoff
|
||||
|
||||
|
||||
class TestCacheRoundTrip:
|
||||
"""缓存读写:命中未过期快照就不查外部。"""
|
||||
|
||||
@@ -35,7 +35,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||
|
||||
HEAD_REVISION = "20261117_0085"
|
||||
HEAD_REVISION = "20261118_0087"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
|
||||
@@ -19,6 +19,7 @@ from web.backend.models import (
|
||||
IntegrationOutbox,
|
||||
PlatformCommodityMapping,
|
||||
PlatformFulfillmentEvent,
|
||||
PlatformFulfillmentSetting,
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
@@ -46,6 +47,14 @@ class _Base:
|
||||
self.session.add(self.admin)
|
||||
self.session.commit()
|
||||
self.admin_id = self.admin.id
|
||||
self.session.add(
|
||||
PlatformFulfillmentSetting(
|
||||
id=1,
|
||||
lease_duration_minutes=None,
|
||||
order_match_started_at=NOW - timedelta(days=1),
|
||||
)
|
||||
)
|
||||
self.session.commit()
|
||||
self.refresh_patch = patch.object(
|
||||
service,
|
||||
"refresh_douyu_account_state",
|
||||
@@ -168,11 +177,19 @@ class TestSyncAndMapping(_Base):
|
||||
|
||||
def test_sync_is_idempotent_and_applies_mapping(self, monkeypatch):
|
||||
self.mapping()
|
||||
cutoff = NOW - timedelta(days=1)
|
||||
captured_keys: list[str] = []
|
||||
captured_cutoff: list[datetime | None] = []
|
||||
|
||||
def _rows(*, limit: int, internal_sku_keys: list[str]):
|
||||
def _rows(
|
||||
*,
|
||||
limit: int,
|
||||
internal_sku_keys: list[str],
|
||||
paid_at_from: datetime | None,
|
||||
):
|
||||
del limit
|
||||
captured_keys.extend(internal_sku_keys)
|
||||
captured_cutoff.append(paid_at_from)
|
||||
return [
|
||||
{
|
||||
"source_order_id": "100",
|
||||
@@ -205,6 +222,7 @@ class TestSyncAndMapping(_Base):
|
||||
assert first["created"] == 1
|
||||
assert second["created"] == 0
|
||||
assert captured_keys == [INTERNAL_SKU, INTERNAL_SKU]
|
||||
assert captured_cutoff == [cutoff, cutoff]
|
||||
assert self.session.query(PlatformFulfillmentTask).count() == 1
|
||||
task = self.session.query(PlatformFulfillmentTask).one()
|
||||
assert task.execution_status == "ready"
|
||||
@@ -248,6 +266,68 @@ class TestSyncAndMapping(_Base):
|
||||
assert listed["pagination"]["total"] == 1
|
||||
assert legacy.id != mapped.id
|
||||
|
||||
def test_list_hides_tasks_created_before_order_match_cutoff(self):
|
||||
mapping = self.mapping()
|
||||
task = PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="104",
|
||||
source_order_item_id="105",
|
||||
source_fulfillment_id="205",
|
||||
platform_order_id="ORDER-105",
|
||||
sku_code=INTERNAL_SKU,
|
||||
sku_name=INTERNAL_SKU,
|
||||
internal_sku_key=INTERNAL_SKU,
|
||||
quantity=1,
|
||||
target_platform="douyu",
|
||||
scope="elite",
|
||||
commodity_mapping_id=mapping.id,
|
||||
commodity_id=COMMODITY,
|
||||
required_points=1280,
|
||||
binding_status="not_started",
|
||||
execution_status="ready",
|
||||
exchange_status="not_started",
|
||||
created_at=NOW - timedelta(hours=2),
|
||||
updated_at=NOW - timedelta(hours=2),
|
||||
)
|
||||
self.session.add(task)
|
||||
self.session.commit()
|
||||
service.update_settings(
|
||||
self.session,
|
||||
lease_duration_minutes=None,
|
||||
order_match_started_at=NOW - timedelta(hours=1),
|
||||
current=self.admin,
|
||||
)
|
||||
|
||||
listed = service.list_tasks(self.session)
|
||||
|
||||
assert listed["pagination"]["total"] == 0
|
||||
|
||||
def test_customer_session_ignores_task_before_order_match_cutoff(
|
||||
self,
|
||||
monkeypatch,
|
||||
):
|
||||
task = self.task()
|
||||
service.update_settings(
|
||||
self.session,
|
||||
lease_duration_minutes=None,
|
||||
order_match_started_at=task.created_at + timedelta(minutes=1),
|
||||
current=self.admin,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
service,
|
||||
"sync_pending_tasks",
|
||||
lambda *_args, **_kwargs: {"fetched": 0},
|
||||
)
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
service.ensure_customer_session(
|
||||
self.session,
|
||||
source_order_item_id=task.source_order_item_id,
|
||||
platform_order_id=task.platform_order_id,
|
||||
)
|
||||
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
def test_upsert_mapping_advances_existing_task(self):
|
||||
task = self.task(mapped=False)
|
||||
self.session.add(
|
||||
@@ -478,15 +558,18 @@ class TestAccountSelection(_Base):
|
||||
finite = service.update_settings(
|
||||
self.session,
|
||||
lease_duration_minutes=90,
|
||||
order_match_started_at=NOW - timedelta(days=1),
|
||||
current=self.admin,
|
||||
)
|
||||
self.session.refresh(lease)
|
||||
assert finite["leaseDurationMinutes"] == 90
|
||||
assert finite["orderMatchStartedAt"] is not None
|
||||
assert lease.expires_at is not None
|
||||
|
||||
unlimited = service.update_settings(
|
||||
self.session,
|
||||
lease_duration_minutes=None,
|
||||
order_match_started_at=NOW - timedelta(days=1),
|
||||
current=self.admin,
|
||||
)
|
||||
self.session.refresh(lease)
|
||||
|
||||
@@ -5,12 +5,23 @@ from __future__ import annotations
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
from web.backend.models import PlatformFulfillmentTask, User
|
||||
from web.backend.models import (
|
||||
PlatformFulfillmentSetting,
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from web.backend.services.platform_fulfillment import auto_allocator
|
||||
|
||||
|
||||
def test_auto_allocator_only_scans_ready_unassigned_tasks(db):
|
||||
actor = User(username="auto-alloc-actor", password_hash="h", role="super_admin")
|
||||
db.add(
|
||||
PlatformFulfillmentSetting(
|
||||
id=1,
|
||||
lease_duration_minutes=None,
|
||||
order_match_started_at=datetime.now(UTC) - timedelta(days=1),
|
||||
)
|
||||
)
|
||||
ready = PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="1",
|
||||
@@ -35,7 +46,20 @@ def test_auto_allocator_only_scans_ready_unassigned_tasks(db):
|
||||
exchange_status="not_started",
|
||||
updated_at=datetime.now(UTC) - timedelta(minutes=2),
|
||||
)
|
||||
db.add_all([actor, ready, mapped_pending])
|
||||
old_ready = PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="3",
|
||||
source_order_item_id="3",
|
||||
platform_order_id="AUTO-OLD",
|
||||
internal_sku_key="skin",
|
||||
commodity_id="commodity-1",
|
||||
execution_status="ready",
|
||||
binding_status="not_started",
|
||||
exchange_status="not_started",
|
||||
created_at=datetime.now(UTC) - timedelta(days=2),
|
||||
updated_at=datetime.now(UTC) - timedelta(days=2),
|
||||
)
|
||||
db.add_all([actor, ready, mapped_pending, old_ready])
|
||||
db.commit()
|
||||
|
||||
calls: list[int] = []
|
||||
@@ -45,8 +69,7 @@ def test_auto_allocator_only_scans_ready_unassigned_tasks(db):
|
||||
auto_allocator.service,
|
||||
"allocate_task",
|
||||
side_effect=lambda _db, *, task_id, current: (
|
||||
calls.append(task_id)
|
||||
or {"task": {"account": {"id": 9}}}
|
||||
calls.append(task_id) or {"task": {"account": {"id": 9}}}
|
||||
),
|
||||
),
|
||||
):
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""直播账号履约订单匹配起算时间
|
||||
|
||||
迁移上线即把起算时间设为当前时刻,避免历史人工订单在启用商品映射后被
|
||||
重新匹配。历史任务保留,但不进入工作台、自动选号和客户领取会话。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261118_0087"
|
||||
down_revision: str | None = "20261117_0086"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def _column_exists(table: str, column: str) -> bool:
|
||||
return bool(
|
||||
op.get_bind()
|
||||
.execute(
|
||||
sa.text(
|
||||
"SELECT COUNT(*) FROM information_schema.columns "
|
||||
"WHERE table_schema = DATABASE() "
|
||||
"AND table_name = :table AND column_name = :column"
|
||||
),
|
||||
{"table": table, "column": column},
|
||||
)
|
||||
.scalar()
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if not _column_exists(
|
||||
"platform_fulfillment_settings",
|
||||
"order_match_started_at",
|
||||
):
|
||||
op.add_column(
|
||||
"platform_fulfillment_settings",
|
||||
sa.Column("order_match_started_at", sa.DateTime(), nullable=True),
|
||||
)
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE platform_fulfillment_settings
|
||||
SET order_match_started_at = NOW()
|
||||
WHERE order_match_started_at IS NULL
|
||||
"""
|
||||
)
|
||||
)
|
||||
op.alter_column(
|
||||
"platform_fulfillment_settings",
|
||||
"order_match_started_at",
|
||||
existing_type=sa.DateTime(),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if _column_exists(
|
||||
"platform_fulfillment_settings",
|
||||
"order_match_started_at",
|
||||
):
|
||||
op.drop_column(
|
||||
"platform_fulfillment_settings",
|
||||
"order_match_started_at",
|
||||
)
|
||||
@@ -1720,6 +1720,11 @@ class PlatformFulfillmentSetting(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
lease_duration_minutes: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
order_match_started_at: Mapped[datetime] = mapped_column(
|
||||
UTCDateTime,
|
||||
nullable=False,
|
||||
default=_utcnow,
|
||||
)
|
||||
updated_by: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
@@ -1940,9 +1945,7 @@ class IntegrationOutbox(Base):
|
||||
)
|
||||
locked_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
sent_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
last_error: Mapped[str] = mapped_column(
|
||||
Text, nullable=False, default=""
|
||||
)
|
||||
last_error: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
UTCDateTime, nullable=False, default=_utcnow
|
||||
)
|
||||
|
||||
@@ -40,6 +40,7 @@ def update_settings(
|
||||
result = service.update_settings(
|
||||
db,
|
||||
lease_duration_minutes=req.lease_duration_minutes,
|
||||
order_match_started_at=req.order_match_started_at,
|
||||
current=current,
|
||||
)
|
||||
record_audit(
|
||||
|
||||
@@ -1578,6 +1578,7 @@ class PlatformFulfillmentCompleteRequest(BaseModel):
|
||||
|
||||
class PlatformFulfillmentSettingsUpdate(BaseModel):
|
||||
lease_duration_minutes: int | None = Field(..., ge=1, le=525600)
|
||||
order_match_started_at: datetime | None = None
|
||||
|
||||
|
||||
class PlatformFulfillmentCustomerSessionRequest(BaseModel):
|
||||
|
||||
@@ -158,6 +158,7 @@ def _fetch_pending_manual_fulfillments(
|
||||
limit: int = 100,
|
||||
*,
|
||||
internal_sku_keys: list[str] | None = None,
|
||||
paid_at_from: datetime | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""读取最近的人工渠道待履约订单项。
|
||||
|
||||
@@ -172,8 +173,11 @@ def _fetch_pending_manual_fulfillments(
|
||||
if not sku_keys:
|
||||
return []
|
||||
engine = _get_engine()
|
||||
paid_at_filter = (
|
||||
"AND o.paid_at >= :paid_at_from" if paid_at_from is not None else ""
|
||||
)
|
||||
sql = text(
|
||||
"""
|
||||
f"""
|
||||
SELECT o.id AS source_order_id,
|
||||
o.platform_order_id,
|
||||
o.provider,
|
||||
@@ -204,6 +208,7 @@ def _fetch_pending_manual_fulfillments(
|
||||
AND f.status = 'assigned'
|
||||
AND o.pay_status = 'paid'
|
||||
AND o.order_status NOT IN ('refunded', 'cancelled', 'closed')
|
||||
{paid_at_filter}
|
||||
AND oi.quantity = 1
|
||||
AND COALESCE(f.issue_code, '') NOT IN ('user_refund', 'platform_cancelled')
|
||||
AND COALESCE(
|
||||
@@ -218,14 +223,17 @@ def _fetch_pending_manual_fulfillments(
|
||||
)
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
params: dict[str, Any] = {
|
||||
"limit": max(1, min(limit, 500)),
|
||||
"internal_sku_keys": sku_keys,
|
||||
}
|
||||
if paid_at_from is not None:
|
||||
params["paid_at_from"] = paid_at_from
|
||||
return [
|
||||
dict(row)
|
||||
for row in conn.execute(
|
||||
sql,
|
||||
{
|
||||
"limit": max(1, min(limit, 500)),
|
||||
"internal_sku_keys": sku_keys,
|
||||
},
|
||||
params,
|
||||
).mappings()
|
||||
]
|
||||
except Exception as exc:
|
||||
@@ -237,6 +245,7 @@ def list_pending_manual_fulfillments(
|
||||
limit: int = 100,
|
||||
*,
|
||||
internal_sku_keys: list[str] | None = None,
|
||||
paid_at_from: datetime | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""返回最近的人工渠道待履约订单项快照。"""
|
||||
if not _enabled():
|
||||
@@ -252,6 +261,7 @@ def list_pending_manual_fulfillments(
|
||||
for row in _fetch_pending_manual_fulfillments(
|
||||
limit=limit,
|
||||
internal_sku_keys=sku_keys,
|
||||
paid_at_from=paid_at_from,
|
||||
):
|
||||
internal_sku_key = str(
|
||||
row.get("manual_sku_key")
|
||||
|
||||
@@ -51,18 +51,19 @@ def run_auto_allocation_once(
|
||||
10,
|
||||
3600,
|
||||
)
|
||||
candidates = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.execution_status == "ready",
|
||||
PlatformFulfillmentTask.account_id.is_(None),
|
||||
PlatformFulfillmentTask.commodity_id != "",
|
||||
PlatformFulfillmentTask.updated_at
|
||||
<= moment - timedelta(seconds=retry_seconds),
|
||||
query = db.query(PlatformFulfillmentTask).filter(
|
||||
PlatformFulfillmentTask.execution_status == "ready",
|
||||
PlatformFulfillmentTask.account_id.is_(None),
|
||||
PlatformFulfillmentTask.commodity_id != "",
|
||||
PlatformFulfillmentTask.updated_at <= moment - timedelta(seconds=retry_seconds),
|
||||
)
|
||||
match_started_at = service._order_match_started_at(db)
|
||||
if match_started_at is not None:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.created_at >= match_started_at,
|
||||
)
|
||||
.order_by(PlatformFulfillmentTask.updated_at.asc())
|
||||
.limit(batch_size)
|
||||
.all()
|
||||
candidates = (
|
||||
query.order_by(PlatformFulfillmentTask.updated_at.asc()).limit(batch_size).all()
|
||||
)
|
||||
if not candidates:
|
||||
return {"checked": 0, "allocated": 0, "failed": 0}
|
||||
@@ -84,9 +85,7 @@ def run_auto_allocation_once(
|
||||
except Exception as exc: # noqa: BLE001 - 单个任务异常不能中断整批
|
||||
db.rollback()
|
||||
failed += 1
|
||||
logger.warning(
|
||||
"直播账号履约自动选号失败 task_id={}: {}", task.id, exc
|
||||
)
|
||||
logger.warning("直播账号履约自动选号失败 task_id={}: {}", task.id, exc)
|
||||
return {
|
||||
"checked": len(candidates),
|
||||
"allocated": allocated,
|
||||
|
||||
@@ -94,18 +94,24 @@ def _mapping_for_sku(
|
||||
|
||||
|
||||
def get_settings(db: Session) -> dict[str, Any]:
|
||||
now = _now()
|
||||
row = (
|
||||
db.query(PlatformFulfillmentSetting)
|
||||
.filter(PlatformFulfillmentSetting.id == 1)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
row = PlatformFulfillmentSetting(id=1, lease_duration_minutes=None)
|
||||
row = PlatformFulfillmentSetting(
|
||||
id=1,
|
||||
lease_duration_minutes=None,
|
||||
order_match_started_at=now,
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return {
|
||||
"leaseDurationMinutes": row.lease_duration_minutes,
|
||||
"orderMatchStartedAt": _jsonable(row.order_match_started_at),
|
||||
"updatedAt": _jsonable(row.updated_at),
|
||||
}
|
||||
|
||||
@@ -114,6 +120,7 @@ def update_settings(
|
||||
db: Session,
|
||||
*,
|
||||
lease_duration_minutes: int | None,
|
||||
order_match_started_at: datetime | None = None,
|
||||
current: User,
|
||||
) -> dict[str, Any]:
|
||||
row = (
|
||||
@@ -121,10 +128,15 @@ def update_settings(
|
||||
.filter(PlatformFulfillmentSetting.id == 1)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
row = PlatformFulfillmentSetting(id=1)
|
||||
db.add(row)
|
||||
now = _now()
|
||||
if row is None:
|
||||
row = PlatformFulfillmentSetting(
|
||||
id=1,
|
||||
order_match_started_at=order_match_started_at or now,
|
||||
)
|
||||
db.add(row)
|
||||
elif order_match_started_at is not None:
|
||||
row.order_match_started_at = order_match_started_at
|
||||
row.lease_duration_minutes = lease_duration_minutes
|
||||
row.updated_by = current.id
|
||||
row.updated_at = now
|
||||
@@ -145,6 +157,7 @@ def update_settings(
|
||||
db.commit()
|
||||
return {
|
||||
"leaseDurationMinutes": row.lease_duration_minutes,
|
||||
"orderMatchStartedAt": _jsonable(row.order_match_started_at),
|
||||
"updatedAt": _jsonable(row.updated_at),
|
||||
}
|
||||
|
||||
@@ -153,6 +166,15 @@ def _lease_duration_minutes(db: Session) -> int | None:
|
||||
return get_settings(db)["leaseDurationMinutes"]
|
||||
|
||||
|
||||
def _order_match_started_at(db: Session) -> datetime | None:
|
||||
row = (
|
||||
db.query(PlatformFulfillmentSetting)
|
||||
.filter(PlatformFulfillmentSetting.id == 1)
|
||||
.first()
|
||||
)
|
||||
return row.order_match_started_at if row is not None else None
|
||||
|
||||
|
||||
def _integration_actor(db: Session) -> User:
|
||||
raw_user_id = os.getenv("PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID", "").strip()
|
||||
query = db.query(User).filter(User.is_active.is_(True))
|
||||
@@ -184,6 +206,11 @@ def _find_customer_task(
|
||||
PlatformFulfillmentTask.source_system == "order_site",
|
||||
PlatformFulfillmentTask.source_order_item_id == item_id,
|
||||
)
|
||||
match_started_at = _order_match_started_at(db)
|
||||
if match_started_at is not None:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.created_at >= match_started_at,
|
||||
)
|
||||
order_no = str(platform_order_id or "").strip()
|
||||
if order_no:
|
||||
query = query.filter(PlatformFulfillmentTask.platform_order_id == order_no)
|
||||
@@ -283,6 +310,7 @@ def _sync_pending_tasks(
|
||||
commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""只拉取已配置商品映射的人工待履约订单项并生成本地作业。"""
|
||||
match_started_at = _order_match_started_at(db)
|
||||
mappings = (
|
||||
db.query(PlatformCommodityMapping)
|
||||
.filter(
|
||||
@@ -310,6 +338,7 @@ def _sync_pending_tasks(
|
||||
rows = list_pending_manual_fulfillments(
|
||||
limit=limit,
|
||||
internal_sku_keys=list(mappings_by_sku),
|
||||
paid_at_from=match_started_at,
|
||||
)
|
||||
except OrderLookupUnavailable as exc:
|
||||
raise HTTPException(status_code=503, detail=f"订单源不可用:{exc}") from exc
|
||||
@@ -384,6 +413,7 @@ def _sync_pending_tasks(
|
||||
"updated": updated,
|
||||
"skippedUnmapped": skipped_unmapped,
|
||||
"configuredSkuCount": len(mappings_by_sku),
|
||||
"orderMatchStartedAt": _jsonable(match_started_at),
|
||||
}
|
||||
|
||||
|
||||
@@ -432,6 +462,11 @@ def list_tasks(
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
query = db.query(PlatformFulfillmentTask)
|
||||
match_started_at = _order_match_started_at(db)
|
||||
if match_started_at is not None:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.created_at >= match_started_at,
|
||||
)
|
||||
query = query.filter(
|
||||
or_(
|
||||
PlatformFulfillmentTask.commodity_mapping_id.isnot(None),
|
||||
@@ -845,16 +880,18 @@ def upsert_mapping(
|
||||
row.updated_at = _now()
|
||||
db.flush()
|
||||
|
||||
pending = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.internal_sku_key == sku_key,
|
||||
PlatformFulfillmentTask.execution_status.in_(
|
||||
["pending_mapping", "ready", "manual_required"]
|
||||
),
|
||||
)
|
||||
.all()
|
||||
match_started_at = _order_match_started_at(db)
|
||||
pending = db.query(PlatformFulfillmentTask).filter(
|
||||
PlatformFulfillmentTask.internal_sku_key == sku_key,
|
||||
PlatformFulfillmentTask.execution_status.in_(
|
||||
["pending_mapping", "ready", "manual_required"]
|
||||
),
|
||||
)
|
||||
if match_started_at is not None:
|
||||
pending = pending.filter(
|
||||
PlatformFulfillmentTask.created_at >= match_started_at,
|
||||
)
|
||||
pending = pending.all()
|
||||
for task in pending:
|
||||
_apply_mapping(task, row if row.enabled else None)
|
||||
task.updated_at = _now()
|
||||
|
||||
@@ -11,10 +11,16 @@ export const platformFulfillmentApi = {
|
||||
api.get<PlatformFulfillmentSettings, PlatformFulfillmentSettings>(
|
||||
'/platform-fulfillment/settings',
|
||||
),
|
||||
updateSettings: (leaseDurationMinutes: number | null) =>
|
||||
updateSettings: (data: {
|
||||
leaseDurationMinutes: number | null;
|
||||
orderMatchStartedAt: string | null;
|
||||
}) =>
|
||||
api.put<PlatformFulfillmentSettings, PlatformFulfillmentSettings>(
|
||||
'/platform-fulfillment/settings',
|
||||
{ lease_duration_minutes: leaseDurationMinutes },
|
||||
{
|
||||
lease_duration_minutes: data.leaseDurationMinutes,
|
||||
order_match_started_at: data.orderMatchStartedAt,
|
||||
},
|
||||
),
|
||||
listTasks: (params: {
|
||||
status?: string;
|
||||
|
||||
@@ -2120,6 +2120,7 @@ export interface PlatformFulfillmentAccount {
|
||||
|
||||
export interface PlatformFulfillmentSettings {
|
||||
leaseDurationMinutes: number | null;
|
||||
orderMatchStartedAt: string | null;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Alert, Button, Card, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
|
||||
import 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 { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { douyuApi, platformFulfillmentApi } from '../api/modules';
|
||||
@@ -267,6 +269,7 @@ export default function PlatformFulfillmentPage() {
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [leaseDurationMode, setLeaseDurationMode] = useState<'unlimited' | 'minutes' | 'hours'>('unlimited');
|
||||
const [leaseDurationValue, setLeaseDurationValue] = useState<number | null>(60);
|
||||
const [orderMatchStartedAt, setOrderMatchStartedAt] = useState<Dayjs | null>(null);
|
||||
const [savingSettings, setSavingSettings] = useState(false);
|
||||
const [douyuActionLoading, setDouyuActionLoading] = useState('');
|
||||
const [douyuActionType, setDouyuActionType] = useState('');
|
||||
@@ -542,6 +545,9 @@ export default function PlatformFulfillmentPage() {
|
||||
setLeaseDurationMode('minutes');
|
||||
setLeaseDurationValue(minutes);
|
||||
}
|
||||
setOrderMatchStartedAt(
|
||||
settings?.orderMatchStartedAt ? dayjs(settings.orderMatchStartedAt) : null,
|
||||
);
|
||||
setSettingsOpen(true);
|
||||
};
|
||||
|
||||
@@ -556,12 +562,19 @@ export default function PlatformFulfillmentPage() {
|
||||
message.warning('租约时长至少为 1 分钟');
|
||||
return;
|
||||
}
|
||||
if (!orderMatchStartedAt) {
|
||||
message.warning('请选择订单匹配起算时间');
|
||||
return;
|
||||
}
|
||||
setSavingSettings(true);
|
||||
try {
|
||||
const result = await platformFulfillmentApi.updateSettings(minutes);
|
||||
const result = await platformFulfillmentApi.updateSettings({
|
||||
leaseDurationMinutes: minutes,
|
||||
orderMatchStartedAt: orderMatchStartedAt.toISOString(),
|
||||
});
|
||||
setSettings(result);
|
||||
setSettingsOpen(false);
|
||||
message.success(`租约设置已更新为${leaseDurationLabel(result.leaseDurationMinutes)}`);
|
||||
message.success('履约同步设置已更新');
|
||||
if (selectedId) await loadDetail(selectedId);
|
||||
await loadTasks();
|
||||
} catch (error) {
|
||||
@@ -742,6 +755,7 @@ export default function PlatformFulfillmentPage() {
|
||||
</div>
|
||||
<Space wrap>
|
||||
<Tag>账号租约:{leaseDurationLabel(settings?.leaseDurationMinutes)}</Tag>
|
||||
<Tag>订单起算:{settings?.orderMatchStartedAt ? formatTime(settings.orderMatchStartedAt) : '-'}</Tag>
|
||||
<Button
|
||||
icon={<SettingOutlined />}
|
||||
disabled={!can('platform_fulfillment:admin')}
|
||||
@@ -1064,13 +1078,29 @@ export default function PlatformFulfillmentPage() {
|
||||
|
||||
<Modal
|
||||
open={settingsOpen}
|
||||
title="账号租约设置"
|
||||
title="履约同步与租约设置"
|
||||
okText="保存设置"
|
||||
confirmLoading={savingSettings}
|
||||
onOk={() => void saveLeaseSettings()}
|
||||
onCancel={() => setSettingsOpen(false)}
|
||||
>
|
||||
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
||||
<div>
|
||||
<Text strong>订单匹配起算时间</Text>
|
||||
<DatePicker
|
||||
showTime
|
||||
allowClear={false}
|
||||
value={orderMatchStartedAt}
|
||||
onChange={setOrderMatchStartedAt}
|
||||
format="YYYY-MM-DD HH:mm"
|
||||
style={{ width: '100%', marginTop: 8 }}
|
||||
/>
|
||||
<Text type="secondary">
|
||||
只同步此时间之后支付的 order_site 人工订单,历史任务保留但不再展示或自动处理。
|
||||
</Text>
|
||||
</div>
|
||||
<div>
|
||||
<Text strong>账号租约</Text>
|
||||
<Segmented
|
||||
block
|
||||
value={leaseDurationMode}
|
||||
@@ -1091,10 +1121,11 @@ export default function PlatformFulfillmentPage() {
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message={`当前设置:${leaseDurationLabel(settings?.leaseDurationMinutes)}`}
|
||||
message={`订单起算:${settings?.orderMatchStartedAt ? formatTime(settings.orderMatchStartedAt) : '-'};账号租约:${leaseDurationLabel(settings?.leaseDurationMinutes)}`}
|
||||
description="保存后会立即同步当前所有活跃租约。无限制模式不会自动回收,任务完成、释放或取消时仍会正常释放账号。"
|
||||
/>
|
||||
</Space>
|
||||
|
||||
Reference in New Issue
Block a user