feat(fulfillment): 增加订单匹配起算时间
This commit is contained in:
@@ -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