修复(斗鱼领取): 收敛任务物化与工作台检索
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
-- 184_fulfillment_search_hotpaths.sql
|
||||
--
|
||||
-- 收敛生产高频排障查询的访问路径:
|
||||
-- 1. 斗鱼/半自动按平台订单号精确定位;
|
||||
-- 2. carrier-dispatch 从活跃载体候选集反查多载体冲突。
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_orders_platform_order_id_lookup
|
||||
ON orders (platform_order_id, id DESC);
|
||||
|
||||
COMMENT ON INDEX idx_orders_platform_order_id_lookup IS
|
||||
'按平台订单号定位订单,服务斗鱼领取、半自动履约和后台排障';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_fulfillment_tasks_active_executor_item
|
||||
ON fulfillment_tasks (executor_key, order_item_id)
|
||||
WHERE task_status NOT IN (
|
||||
'closed',
|
||||
'expired',
|
||||
'failed',
|
||||
'manual_review',
|
||||
'retry_pending',
|
||||
'cancelled'
|
||||
);
|
||||
|
||||
COMMENT ON INDEX idx_fulfillment_tasks_active_executor_item IS
|
||||
'活跃履约任务按执行器和订单项反查,服务载体冲突检查';
|
||||
@@ -0,0 +1,97 @@
|
||||
-- 185_fulfillment_queue_active_scope.sql
|
||||
--
|
||||
-- 履约待办只包含仍需处理的 pending/assigned 履约记录。
|
||||
-- archived 已完成归档,不属于 actionable/configuration/operator_review/terminal 任一待办桶。
|
||||
|
||||
CREATE OR REPLACE VIEW v_fulfillment_queue AS
|
||||
WITH classified AS (
|
||||
SELECT
|
||||
state.*,
|
||||
CASE
|
||||
WHEN state.pay_status = 'refunded'
|
||||
OR state.order_status IN ('refunded', 'cancelled', 'closed')
|
||||
OR state.issue_code IN ('user_refund', 'platform_cancelled')
|
||||
THEN 'terminal'
|
||||
WHEN state.issue_category IN ('configuration', 'classification')
|
||||
OR state.issue_code IN (
|
||||
'missing_internal_sku',
|
||||
'missing_channel',
|
||||
'manual_config_missing',
|
||||
'work_rule_missing',
|
||||
'affiliate_mapping_missing'
|
||||
)
|
||||
OR COALESCE(state.fulfillment_pending_detail ->> 'carrierIssue', '') IN (
|
||||
'manual_config_missing',
|
||||
'work_rule_missing',
|
||||
'affiliate_mapping_missing',
|
||||
'missing_internal_sku',
|
||||
'missing_channel'
|
||||
)
|
||||
THEN 'configuration'
|
||||
WHEN state.issue_category = 'manual_review'
|
||||
OR state.issue_code IN (
|
||||
'carrier_manual_review',
|
||||
'carrier_retry_pending',
|
||||
'carrier_expired',
|
||||
'carrier_closed'
|
||||
)
|
||||
OR COALESCE(state.fulfillment_pending_detail ->> 'carrierIssue', '') IN (
|
||||
'carrier_task_closed',
|
||||
'carrier_task_user_refund',
|
||||
'carrier_task_retry_pending',
|
||||
'carrier_task_cancelled',
|
||||
'carrier_task_expired',
|
||||
'carrier_task_manual_review'
|
||||
)
|
||||
THEN 'operator_review'
|
||||
WHEN state.issue_code = 'state_inconsistent'
|
||||
AND state.issue_category = 'system'
|
||||
AND COALESCE(state.fulfillment_pending_detail ->> 'carrierIssue', '')
|
||||
IN ('', 'carrier_not_attempted')
|
||||
THEN 'actionable'
|
||||
WHEN state.issue_category = 'system'
|
||||
THEN 'operator_review'
|
||||
ELSE 'actionable'
|
||||
END AS queue_bucket
|
||||
FROM v_fulfillment_item_state state
|
||||
WHERE state.fulfillment_status IN ('pending', 'assigned')
|
||||
),
|
||||
eligible AS (
|
||||
SELECT
|
||||
classified.*,
|
||||
(
|
||||
classified.fulfillment_status = 'pending'
|
||||
AND classified.pay_status = 'paid'
|
||||
AND classified.order_status NOT IN ('refunded', 'cancelled', 'closed')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM fulfillment_tasks task
|
||||
WHERE task.order_item_id = classified.order_item_id
|
||||
AND task.executor_key = 'affiliate_dash'
|
||||
AND task.task_status NOT IN (
|
||||
'closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled'
|
||||
)
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM work_orders work_order
|
||||
WHERE work_order.order_item_id = classified.order_item_id
|
||||
AND work_order.status <> 'cancelled'
|
||||
)
|
||||
) AS carrier_queue_candidate
|
||||
FROM classified
|
||||
)
|
||||
SELECT
|
||||
eligible.order_item_id AS id,
|
||||
eligible.*,
|
||||
(
|
||||
eligible.carrier_queue_candidate
|
||||
AND eligible.queue_bucket = 'actionable'
|
||||
AND eligible.fulfillment_locked = FALSE
|
||||
) AS actionable_for_carrier,
|
||||
item.manual_sku_key
|
||||
FROM eligible
|
||||
JOIN order_items item ON item.id = eligible.order_item_id;
|
||||
|
||||
COMMENT ON VIEW v_fulfillment_queue IS
|
||||
'履约待办只读投影:仅覆盖 pending/assigned;四桶由正式履约状态和结构化异常派生';
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
ensureSemiAutoTasksForOrderItems,
|
||||
reconcileSemiAutoTasksForManualConfig,
|
||||
} from '../semi-auto/semi-auto-task-service.js'
|
||||
import { ensureDouyuFulfillmentTasksForOrderItems } from '../douyu-fulfillment/douyu-fulfillment-service.js'
|
||||
|
||||
/**
|
||||
* 人工履约 SKU 配置服务。
|
||||
@@ -959,6 +960,7 @@ export async function rematchManualFulfillments(input: Record<string, unknown> =
|
||||
if (updatedIds.length > 0) {
|
||||
await resolveExceptionsForItemsByReason(updatedIds, 'manual_config_missing')
|
||||
await ensureSemiAutoTasksForOrderItems(updatedIds)
|
||||
await ensureDouyuFulfillmentTasksForOrderItems(updatedIds).catch(() => undefined)
|
||||
}
|
||||
|
||||
// 配置生效后,把 SKU 对应的成本版本挂上(若已配置商品)。
|
||||
|
||||
@@ -171,11 +171,10 @@ export function hasDouyuCustomerProfile(input: {
|
||||
export async function getDouyuFulfillmentSettings() {
|
||||
const result = await query<DouyuFulfillmentSettingsRow>(
|
||||
`
|
||||
INSERT INTO douyu_fulfillment_settings (
|
||||
id, order_match_started_at, updated_at
|
||||
) VALUES (1, NOW(), NOW())
|
||||
ON CONFLICT (id) DO UPDATE SET id = EXCLUDED.id
|
||||
RETURNING order_match_started_at, updated_at
|
||||
SELECT order_match_started_at, updated_at
|
||||
FROM douyu_fulfillment_settings
|
||||
WHERE id = 1
|
||||
LIMIT 1
|
||||
`,
|
||||
)
|
||||
const row = result.rows[0]
|
||||
@@ -287,90 +286,175 @@ async function appendEvent(
|
||||
}
|
||||
|
||||
export async function ensureDouyuFulfillmentTasks(orderNo = '') {
|
||||
const settings = await getDouyuFulfillmentSettings()
|
||||
const params: unknown[] = [settings.orderMatchStartedAt]
|
||||
const filters = ['AND COALESCE(o.paid_at, o.created_at) >= $1::timestamptz']
|
||||
const normalizedOrderNo = String(orderNo || '').trim()
|
||||
if (normalizedOrderNo) {
|
||||
params.push(normalizedOrderNo)
|
||||
filters.push(`AND o.platform_order_id = $${params.length}`)
|
||||
return materializeDouyuFulfillmentTasks(
|
||||
String(orderNo || '').trim() ? { orderNo: String(orderNo).trim() } : {},
|
||||
)
|
||||
}
|
||||
|
||||
export async function ensureDouyuFulfillmentTasksForOrderItems(input: unknown[]) {
|
||||
const orderItemIds = [
|
||||
...new Set(
|
||||
(Array.isArray(input) ? input : [])
|
||||
.map(Number)
|
||||
.filter((id) => Number.isInteger(id) && id > 0),
|
||||
),
|
||||
]
|
||||
if (orderItemIds.length === 0) return { created: 0, updated: 0 }
|
||||
return materializeDouyuFulfillmentTasks({ orderItemIds })
|
||||
}
|
||||
|
||||
export async function backfillDouyuFulfillmentTasks(
|
||||
options: { limit?: number; createdAfter?: string } = {},
|
||||
) {
|
||||
return materializeDouyuFulfillmentTasks({ ...options, onlyMissing: true })
|
||||
}
|
||||
|
||||
async function materializeDouyuFulfillmentTasks(input: {
|
||||
orderNo?: string
|
||||
orderItemIds?: number[]
|
||||
limit?: number
|
||||
createdAfter?: string
|
||||
onlyMissing?: boolean
|
||||
}) {
|
||||
const params: unknown[] = []
|
||||
const filters: string[] = []
|
||||
const orderNo = String(input.orderNo || '').trim()
|
||||
if (orderNo) {
|
||||
params.push(orderNo)
|
||||
filters.push(`o.platform_order_id = $${params.length}`)
|
||||
}
|
||||
const candidates = await query<{
|
||||
order_id: number
|
||||
const orderItemIds = [
|
||||
...new Set(
|
||||
(input.orderItemIds || []).map(Number).filter((id) => Number.isInteger(id) && id > 0),
|
||||
),
|
||||
]
|
||||
if (orderItemIds.length > 0) {
|
||||
params.push(orderItemIds)
|
||||
filters.push(`oi.id = ANY($${params.length}::bigint[])`)
|
||||
}
|
||||
const createdAfter = String(input.createdAfter || '').trim()
|
||||
if (createdAfter && Number.isFinite(Date.parse(createdAfter))) {
|
||||
params.push(createdAfter)
|
||||
filters.push(`COALESCE(o.paid_at, o.created_at) >= $${params.length}::timestamptz`)
|
||||
}
|
||||
const limit =
|
||||
Number.isInteger(input.limit) && Number(input.limit) > 0
|
||||
? Math.min(20_000, Math.trunc(Number(input.limit)))
|
||||
: null
|
||||
const limitSql = limit ? `LIMIT ${limit}` : ''
|
||||
const onlyMissingFilter = input.onlyMissing ? 'AND existing.id IS NULL' : ''
|
||||
|
||||
const result = await query<{
|
||||
task_id: number
|
||||
order_item_id: number
|
||||
fulfillment_id: number
|
||||
config_id: number
|
||||
platform_order_id: string
|
||||
inserted: boolean
|
||||
}>(
|
||||
`
|
||||
WITH candidates AS (
|
||||
SELECT
|
||||
o.id AS order_id,
|
||||
o.platform_order_id,
|
||||
oi.id AS order_item_id,
|
||||
f.id AS fulfillment_id,
|
||||
cfg.id AS config_id,
|
||||
existing.id AS existing_task_id
|
||||
FROM orders o
|
||||
JOIN order_items oi ON oi.order_id = o.id
|
||||
JOIN fulfillments f ON f.order_item_id = oi.id
|
||||
JOIN manual_fulfillment_configs cfg ON cfg.id = f.fulfillment_config_id
|
||||
JOIN douyu_fulfillment_settings settings ON settings.id = 1
|
||||
LEFT JOIN douyu_fulfillment_tasks existing ON existing.order_item_id = oi.id
|
||||
WHERE cfg.enabled = TRUE
|
||||
AND cfg.douyu_fulfillment_enabled = TRUE
|
||||
AND f.channel = 'manual'
|
||||
AND f.status IN ('assigned', 'processing', 'completed')
|
||||
AND COALESCE(o.paid_at, o.created_at) >= settings.order_match_started_at
|
||||
${filters.length > 0 ? `AND ${filters.join('\n AND ')}` : ''}
|
||||
${onlyMissingFilter}
|
||||
ORDER BY o.id DESC, oi.id ASC
|
||||
${limitSql}
|
||||
),
|
||||
upserted AS (
|
||||
INSERT INTO douyu_fulfillment_tasks (
|
||||
order_id, order_item_id, fulfillment_id, manual_fulfillment_config_id,
|
||||
status, created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
candidate.order_id,
|
||||
candidate.order_item_id,
|
||||
candidate.fulfillment_id,
|
||||
candidate.config_id,
|
||||
'waiting_profile',
|
||||
NOW(),
|
||||
NOW()
|
||||
FROM candidates candidate
|
||||
ON CONFLICT (order_item_id) DO UPDATE SET
|
||||
fulfillment_id = EXCLUDED.fulfillment_id,
|
||||
manual_fulfillment_config_id = EXCLUDED.manual_fulfillment_config_id,
|
||||
updated_at = NOW()
|
||||
WHERE douyu_fulfillment_tasks.fulfillment_id IS DISTINCT FROM EXCLUDED.fulfillment_id
|
||||
OR douyu_fulfillment_tasks.manual_fulfillment_config_id
|
||||
IS DISTINCT FROM EXCLUDED.manual_fulfillment_config_id
|
||||
RETURNING id, order_item_id, (xmax = 0) AS inserted
|
||||
),
|
||||
created_events AS (
|
||||
INSERT INTO douyu_fulfillment_events (
|
||||
task_id, event_type, actor_type, detail_json, created_at
|
||||
)
|
||||
SELECT
|
||||
upserted.id,
|
||||
'task_created',
|
||||
'system',
|
||||
jsonb_build_object('platformOrderId', candidate.platform_order_id),
|
||||
NOW()
|
||||
FROM upserted
|
||||
JOIN candidates candidate ON candidate.order_item_id = upserted.order_item_id
|
||||
WHERE upserted.inserted
|
||||
RETURNING task_id
|
||||
)
|
||||
SELECT
|
||||
o.id AS order_id,
|
||||
oi.id AS order_item_id,
|
||||
f.id AS fulfillment_id,
|
||||
cfg.id AS config_id,
|
||||
o.platform_order_id
|
||||
FROM orders o
|
||||
JOIN order_items oi ON oi.order_id = o.id
|
||||
JOIN fulfillments f ON f.order_item_id = oi.id
|
||||
JOIN manual_fulfillment_configs cfg ON cfg.id = f.fulfillment_config_id
|
||||
WHERE cfg.enabled = TRUE
|
||||
AND cfg.douyu_fulfillment_enabled = TRUE
|
||||
AND f.channel = 'manual'
|
||||
AND f.status IN ('assigned', 'processing', 'completed')
|
||||
${filters.join('\n ')}
|
||||
ORDER BY o.id DESC, oi.id ASC
|
||||
upserted.id AS task_id,
|
||||
upserted.order_item_id,
|
||||
candidate.platform_order_id,
|
||||
upserted.inserted
|
||||
FROM upserted
|
||||
JOIN candidates candidate ON candidate.order_item_id = upserted.order_item_id
|
||||
ORDER BY upserted.order_item_id
|
||||
`,
|
||||
params,
|
||||
)
|
||||
if (candidates.rows.length === 0) return { created: 0, updated: 0 }
|
||||
|
||||
let created = 0
|
||||
const createdOrderNos = new Set<string>()
|
||||
await withTransaction(async (client) => {
|
||||
for (const row of candidates.rows) {
|
||||
const inserted = await client.query<{ id: number; inserted: boolean }>(
|
||||
`
|
||||
INSERT INTO douyu_fulfillment_tasks (
|
||||
order_id, order_item_id, fulfillment_id, manual_fulfillment_config_id,
|
||||
status, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, 'waiting_profile', NOW(), NOW())
|
||||
ON CONFLICT (order_item_id) DO UPDATE SET
|
||||
fulfillment_id = EXCLUDED.fulfillment_id,
|
||||
manual_fulfillment_config_id = EXCLUDED.manual_fulfillment_config_id,
|
||||
updated_at = CASE
|
||||
WHEN douyu_fulfillment_tasks.fulfillment_id IS DISTINCT FROM EXCLUDED.fulfillment_id
|
||||
OR douyu_fulfillment_tasks.manual_fulfillment_config_id
|
||||
IS DISTINCT FROM EXCLUDED.manual_fulfillment_config_id
|
||||
THEN NOW()
|
||||
ELSE douyu_fulfillment_tasks.updated_at
|
||||
END
|
||||
RETURNING id, (xmax = 0) AS inserted
|
||||
`,
|
||||
[row.order_id, row.order_item_id, row.fulfillment_id, row.config_id],
|
||||
)
|
||||
const taskId = Number(inserted.rows[0]?.id || 0)
|
||||
if (!taskId) continue
|
||||
if (inserted.rows[0]?.inserted) {
|
||||
created += 1
|
||||
createdOrderNos.add(row.platform_order_id)
|
||||
await appendEvent(client, taskId, 'task_created', 'system', {
|
||||
platformOrderId: row.platform_order_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
const createdRows = result.rows.filter((row) => row.inserted)
|
||||
const createdOrderNos = new Set(createdRows.map((row) => row.platform_order_id))
|
||||
for (const platformOrderId of createdOrderNos) {
|
||||
publishCustomerOrderRealtimeChange(platformOrderId, 'douyu_fulfillment_task_created')
|
||||
}
|
||||
return { created, updated: candidates.rows.length - created }
|
||||
if (createdRows.length > 0) {
|
||||
publishRealtimeEvent({
|
||||
type: 'order.changed',
|
||||
entityId: 0,
|
||||
scopes: ['admin_douyu_fulfillment'],
|
||||
operation: 'refresh',
|
||||
data: { douyuFulfillmentTaskCreated: true },
|
||||
admin: true,
|
||||
})
|
||||
}
|
||||
return {
|
||||
created: createdRows.length,
|
||||
updated: result.rows.length - createdRows.length,
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureDouyuFulfillmentTasksAutomatically() {
|
||||
async function backfillDouyuFulfillmentTasksAutomatically() {
|
||||
if (automaticDiscoveryInFlight) return automaticDiscoveryInFlight
|
||||
if (Date.now() - lastAutomaticDiscoveryAt < AUTO_DISCOVERY_INTERVAL_MS) return null
|
||||
|
||||
lastAutomaticDiscoveryAt = Date.now()
|
||||
const run = ensureDouyuFulfillmentTasks()
|
||||
const run = backfillDouyuFulfillmentTasks({
|
||||
limit: 500,
|
||||
createdAfter: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
})
|
||||
.catch((error) => {
|
||||
lastAutomaticDiscoveryAt = 0
|
||||
throw error
|
||||
@@ -390,7 +474,6 @@ async function loadTaskByOrderNo(orderNo: string) {
|
||||
errorCode: 'douyu_order_no_required',
|
||||
})
|
||||
}
|
||||
await ensureDouyuFulfillmentTasks(normalized)
|
||||
const settings = await getDouyuFulfillmentSettings()
|
||||
const result = await query<DouyuTaskRow>(
|
||||
`${TASK_SELECT}
|
||||
@@ -640,12 +723,14 @@ async function applyLiveState(task: DouyuTaskRow, live: LiveBindingState) {
|
||||
}
|
||||
|
||||
async function applyLiveStates(entries: Array<{ task: DouyuTaskRow; live: LiveBindingState }>) {
|
||||
if (entries.length === 0) return
|
||||
if (entries.length === 0) return { changed: 0, changedOrderNos: new Set<string>() }
|
||||
const now = nowIso()
|
||||
const changedOrderNos = new Set<string>()
|
||||
let changed = 0
|
||||
await withTransaction(async (client) => {
|
||||
for (const entry of entries) {
|
||||
if (await updateTaskFromLiveState(client, entry.task, entry.live, now)) {
|
||||
changed += 1
|
||||
changedOrderNos.add(entry.task.platform_order_id)
|
||||
}
|
||||
}
|
||||
@@ -653,6 +738,7 @@ async function applyLiveStates(entries: Array<{ task: DouyuTaskRow; live: LiveBi
|
||||
for (const platformOrderId of changedOrderNos) {
|
||||
publishCustomerOrderRealtimeChange(platformOrderId, 'douyu_binding_state_changed')
|
||||
}
|
||||
return { changed, changedOrderNos }
|
||||
}
|
||||
|
||||
function isLiveBindingState(value: unknown): value is LiveBindingState {
|
||||
@@ -1063,8 +1149,8 @@ async function syncLiveStatesForTasks(tasks: DouyuTaskRow[], force = false) {
|
||||
const task = taskBySessionId.get(Number(live.sessionId))
|
||||
return task ? [{ task, live }] : []
|
||||
})
|
||||
await applyLiveStates(entries)
|
||||
if (entries.length > 0) {
|
||||
const applied = await applyLiveStates(entries)
|
||||
if (applied.changed > 0) {
|
||||
publishRealtimeEvent({
|
||||
type: 'order.changed',
|
||||
entityId: 0,
|
||||
@@ -1092,7 +1178,7 @@ export async function reconcileDouyuFulfillmentStates() {
|
||||
}
|
||||
|
||||
export async function syncDouyuFulfillmentTasks() {
|
||||
const synced = await ensureDouyuFulfillmentTasks()
|
||||
const synced = await backfillDouyuFulfillmentTasks()
|
||||
const states = await reconcileDouyuFulfillmentStates()
|
||||
return { ...synced, checked: states.checked }
|
||||
}
|
||||
@@ -1105,49 +1191,65 @@ export async function listDouyuFulfillmentTasks(
|
||||
pageSize?: unknown
|
||||
} = {},
|
||||
) {
|
||||
await ensureDouyuFulfillmentTasksAutomatically()
|
||||
await backfillDouyuFulfillmentTasksAutomatically()
|
||||
const page = Math.max(1, Number(input.page || 1))
|
||||
const pageSize = Math.max(1, Math.min(100, Number(input.pageSize || 20)))
|
||||
const keyword = String(input.keyword || '').trim()
|
||||
const status = String(input.status || '').trim()
|
||||
const settings = await getDouyuFulfillmentSettings()
|
||||
const params: unknown[] = [settings.orderMatchStartedAt]
|
||||
const filters: string[] = ['COALESCE(o.paid_at, o.created_at) >= $1::timestamptz']
|
||||
if (keyword) {
|
||||
params.push(`%${keyword}%`)
|
||||
filters.push(`(
|
||||
o.platform_order_id ILIKE $${params.length}
|
||||
OR oi.sku_name ILIKE $${params.length}
|
||||
OR task.customer_role_name ILIKE $${params.length}
|
||||
)`)
|
||||
const exactOrderNo = /^\d{12,32}$/.test(keyword) ? keyword : ''
|
||||
|
||||
async function loadPage(mode: 'exact' | 'fuzzy') {
|
||||
const params: unknown[] = [settings.orderMatchStartedAt]
|
||||
const filters: string[] = ['COALESCE(o.paid_at, o.created_at) >= $1::timestamptz']
|
||||
if (keyword) {
|
||||
params.push(mode === 'exact' ? keyword : `%${keyword}%`)
|
||||
filters.push(
|
||||
mode === 'exact'
|
||||
? `o.platform_order_id = $${params.length}`
|
||||
: `(
|
||||
o.platform_order_id ILIKE $${params.length}
|
||||
OR oi.sku_name ILIKE $${params.length}
|
||||
OR task.customer_role_name ILIKE $${params.length}
|
||||
)`,
|
||||
)
|
||||
}
|
||||
if (status) {
|
||||
params.push(status)
|
||||
filters.push(`task.status = $${params.length}`)
|
||||
}
|
||||
const where = filters.length ? `WHERE ${filters.join(' AND ')}` : ''
|
||||
const count = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total
|
||||
FROM douyu_fulfillment_tasks task
|
||||
JOIN orders o ON o.id = task.order_id
|
||||
JOIN order_items oi ON oi.id = task.order_item_id
|
||||
${where}`,
|
||||
params,
|
||||
)
|
||||
const total = Number(count.rows[0]?.total || 0)
|
||||
if (total === 0) return { total, rows: [] as DouyuTaskRow[] }
|
||||
params.push(pageSize, (page - 1) * pageSize)
|
||||
const rows = await query<DouyuTaskRow>(
|
||||
`${TASK_SELECT}
|
||||
${where}
|
||||
ORDER BY task.updated_at DESC, task.id DESC
|
||||
LIMIT $${params.length - 1} OFFSET $${params.length}`,
|
||||
params,
|
||||
)
|
||||
return { total, rows: rows.rows }
|
||||
}
|
||||
if (status) {
|
||||
params.push(status)
|
||||
filters.push(`task.status = $${params.length}`)
|
||||
|
||||
let result = await loadPage(exactOrderNo ? 'exact' : 'fuzzy')
|
||||
if (exactOrderNo && result.total === 0) {
|
||||
result = await loadPage('fuzzy')
|
||||
}
|
||||
const where = filters.length ? `WHERE ${filters.join(' AND ')}` : ''
|
||||
const count = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total
|
||||
FROM douyu_fulfillment_tasks task
|
||||
JOIN orders o ON o.id = task.order_id
|
||||
JOIN order_items oi ON oi.id = task.order_item_id
|
||||
${where}`,
|
||||
params,
|
||||
)
|
||||
params.push(pageSize, (page - 1) * pageSize)
|
||||
const rows = await query<DouyuTaskRow>(
|
||||
`${TASK_SELECT}
|
||||
${where}
|
||||
ORDER BY task.updated_at DESC, task.id DESC
|
||||
LIMIT $${params.length - 1} OFFSET $${params.length}`,
|
||||
params,
|
||||
)
|
||||
return {
|
||||
items: rows.rows.map((task) => ({
|
||||
items: result.rows.map((task) => ({
|
||||
...task,
|
||||
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
|
||||
})),
|
||||
pagination: { page, pageSize, total: Number(count.rows[0]?.total || 0) },
|
||||
pagination: { page, pageSize, total: result.total },
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* 斗鱼领取任务物化与精确检索集成测试(需要已完成迁移的真实 PostgreSQL)。
|
||||
*
|
||||
* 运行:
|
||||
* DOUYU_FULFILLMENT_TEST_DATABASE_URL="$DATABASE_URL" \
|
||||
* npx tsx --test src/services/douyu-fulfillment/douyu-fulfillment.integration.test.ts
|
||||
*/
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
const TEST_DATABASE_URL = String(process.env.DOUYU_FULFILLMENT_TEST_DATABASE_URL || '').trim()
|
||||
|
||||
test(
|
||||
'人工配置挂载后按订单项物化斗鱼任务,并可精确检索且保持幂等',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 DOUYU_FULFILLMENT_TEST_DATABASE_URL' : false },
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
const { closeDb, query } = await import('../../db/client.js')
|
||||
const { ensureDouyuFulfillmentTasksForOrderItems, listDouyuFulfillmentTasks } =
|
||||
await import('./douyu-fulfillment-service.js')
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
const platformOrderId = `IT-DOUYU-${suffix}`
|
||||
const internalSku = `集成斗鱼领取-${suffix}`
|
||||
let orderId = 0
|
||||
let configId = 0
|
||||
|
||||
try {
|
||||
const config = await query<{ id: number }>(
|
||||
`INSERT INTO manual_fulfillment_configs (
|
||||
sku_key, platform_key, credit_quantity, cost_mode, enabled,
|
||||
douyu_fulfillment_enabled, created_at, updated_at
|
||||
) VALUES ($1, 'nanhang', 1, 'fixed', TRUE, TRUE, NOW(), NOW())
|
||||
RETURNING id`,
|
||||
[internalSku],
|
||||
)
|
||||
configId = Number(config.rows[0]!.id)
|
||||
|
||||
const order = await query<{ id: number }>(
|
||||
`INSERT INTO orders (
|
||||
provider, platform, shop_id, shop_name, platform_order_id,
|
||||
order_status, pay_status, total_amount, paid_at, created_at, updated_at
|
||||
) VALUES (
|
||||
'integration-test', 'integration-test', $1, '集成斗鱼测试店', $2,
|
||||
'paid', 'paid', 9900, NOW(), NOW(), NOW()
|
||||
) RETURNING id`,
|
||||
[`shop-${suffix}`, platformOrderId],
|
||||
)
|
||||
orderId = Number(order.rows[0]!.id)
|
||||
|
||||
const item = await query<{ id: number }>(
|
||||
`INSERT INTO order_items (
|
||||
order_id, sku_code, sku_name, quantity, spec_json,
|
||||
revenue_amount_fen, revenue_basis, created_at, updated_at
|
||||
) VALUES (
|
||||
$1, $2, $2, 1, $3::jsonb, 9900, 'order_total', NOW(), NOW()
|
||||
) RETURNING id`,
|
||||
[orderId, `sku-${suffix}`, JSON.stringify({ skuNick: internalSku })],
|
||||
)
|
||||
const orderItemId = Number(item.rows[0]!.id)
|
||||
|
||||
const fulfillment = await query(
|
||||
`UPDATE fulfillments
|
||||
SET internal_sku = $2,
|
||||
route_status = 'configured',
|
||||
channel = 'manual',
|
||||
carrier_status = 'ready',
|
||||
status = 'assigned',
|
||||
source = 'integration_test',
|
||||
fulfillment_config_id = $3,
|
||||
updated_at = NOW()
|
||||
WHERE order_item_id = $1`,
|
||||
[orderItemId, internalSku, configId],
|
||||
)
|
||||
assert.equal(fulfillment.rowCount, 1)
|
||||
|
||||
const first = await ensureDouyuFulfillmentTasksForOrderItems([orderItemId])
|
||||
assert.equal(first.created, 1)
|
||||
|
||||
const second = await ensureDouyuFulfillmentTasksForOrderItems([orderItemId])
|
||||
assert.equal(second.created, 0)
|
||||
|
||||
const tasks = await query<{ status: string; manual_fulfillment_config_id: number }>(
|
||||
`SELECT status, manual_fulfillment_config_id
|
||||
FROM douyu_fulfillment_tasks
|
||||
WHERE order_item_id = $1`,
|
||||
[orderItemId],
|
||||
)
|
||||
assert.equal(tasks.rows.length, 1)
|
||||
assert.equal(tasks.rows[0]?.status, 'waiting_profile')
|
||||
assert.equal(Number(tasks.rows[0]?.manual_fulfillment_config_id), configId)
|
||||
|
||||
const createdEvents = await query<{ count: number }>(
|
||||
`SELECT COUNT(*)::int AS count
|
||||
FROM douyu_fulfillment_events event
|
||||
JOIN douyu_fulfillment_tasks task ON task.id = event.task_id
|
||||
WHERE task.order_item_id = $1
|
||||
AND event.event_type = 'task_created'`,
|
||||
[orderItemId],
|
||||
)
|
||||
assert.equal(createdEvents.rows[0]?.count, 1)
|
||||
|
||||
const listed = await listDouyuFulfillmentTasks({
|
||||
keyword: platformOrderId,
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
})
|
||||
assert.equal(listed.pagination.total, 1)
|
||||
assert.equal(listed.items[0]?.platform_order_id, platformOrderId)
|
||||
} finally {
|
||||
await query(
|
||||
`DELETE FROM integration_outbox
|
||||
WHERE payload_json->'data'->>'platformOrderId' = $1`,
|
||||
[platformOrderId],
|
||||
).catch(() => undefined)
|
||||
if (orderId > 0) {
|
||||
await query('DELETE FROM orders WHERE id = $1', [orderId]).catch(() => undefined)
|
||||
}
|
||||
if (configId > 0) {
|
||||
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId]).catch(
|
||||
() => undefined,
|
||||
)
|
||||
}
|
||||
await closeDb()
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -1,5 +1,8 @@
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
import { reconcileDouyuFulfillmentStates } from './douyu-fulfillment-service.js'
|
||||
import {
|
||||
backfillDouyuFulfillmentTasks,
|
||||
reconcileDouyuFulfillmentStates,
|
||||
} from './douyu-fulfillment-service.js'
|
||||
|
||||
const DEFAULT_RECONCILE_SECONDS = 900
|
||||
|
||||
@@ -18,6 +21,10 @@ function intervalMs() {
|
||||
async function run() {
|
||||
if (stopped) return
|
||||
try {
|
||||
await backfillDouyuFulfillmentTasks({
|
||||
limit: 500,
|
||||
createdAfter: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
})
|
||||
await reconcileDouyuFulfillmentStates()
|
||||
} catch (error) {
|
||||
logWarn('[douyu-fulfillment]', '低频对账失败', { error })
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
loadActiveCarrierEvidenceForItem,
|
||||
} from './carrier-evidence-service.js'
|
||||
import { attachFulfillmentConfigurations } from './fulfillment-state-service.js'
|
||||
import { ensureDouyuFulfillmentTasksForOrderItems } from '../douyu-fulfillment/douyu-fulfillment-service.js'
|
||||
|
||||
function parseObject(value: unknown): Record<string, unknown> {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
@@ -218,6 +219,7 @@ export async function ensureCarrierForOrderItem(input: {
|
||||
],
|
||||
onlyWhenCanonicalProductNull: true,
|
||||
})
|
||||
await ensureDouyuFulfillmentTasksForOrderItems([Number(item.id)]).catch(() => undefined)
|
||||
if (
|
||||
row.semi_auto_enabled === true &&
|
||||
['huya', 'weibo'].includes(String(row.semi_auto_platform || ''))
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* carrier-dispatch 多载体冲突反查集成测试(需要已完成迁移的真实 PostgreSQL)。
|
||||
*
|
||||
* 运行:
|
||||
* CARRIER_DISPATCH_TEST_DATABASE_URL="$DATABASE_URL" \
|
||||
* npx tsx --test src/services/fulfillment/carrier-dispatch.integration.test.ts
|
||||
*/
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
const TEST_DATABASE_URL = String(process.env.CARRIER_DISPATCH_TEST_DATABASE_URL || '').trim()
|
||||
|
||||
test(
|
||||
'冲突检测只返回同时存在接单工单和自动发货任务的已分配订单项',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 CARRIER_DISPATCH_TEST_DATABASE_URL' : false },
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
const { closeDb, query } = await import('../../db/client.js')
|
||||
const { findConflictingCarrierOrderItems } =
|
||||
await import('../scheduler/finance-pipeline-jobs.js')
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
let orderId = 0
|
||||
let profileId = 0
|
||||
const workOrderIds: number[] = []
|
||||
|
||||
try {
|
||||
const order = await query<{ id: number }>(
|
||||
`INSERT INTO orders (
|
||||
provider, platform, shop_id, shop_name, platform_order_id,
|
||||
order_status, pay_status, total_amount, paid_at, created_at, updated_at
|
||||
) VALUES (
|
||||
'integration-test', 'integration-test', $1, '集成冲突测试店', $2,
|
||||
'paid', 'paid', 1000, NOW(), NOW(), NOW()
|
||||
) RETURNING id`,
|
||||
[`shop-${suffix}`, `IT-CARRIER-CONFLICT-${suffix}`],
|
||||
)
|
||||
orderId = Number(order.rows[0]!.id)
|
||||
|
||||
const conflictItem = await query<{ id: number }>(
|
||||
`INSERT INTO order_items (
|
||||
order_id, sku_code, sku_name, quantity, created_at, updated_at
|
||||
) VALUES ($1, $2, $2, 1, NOW(), NOW())
|
||||
RETURNING id`,
|
||||
[orderId, `冲突订单项-${suffix}`],
|
||||
)
|
||||
const conflictItemId = Number(conflictItem.rows[0]!.id)
|
||||
const cleanItem = await query<{ id: number }>(
|
||||
`INSERT INTO order_items (
|
||||
order_id, sku_code, sku_name, quantity, created_at, updated_at
|
||||
) VALUES ($1, $2, $2, 1, NOW(), NOW())
|
||||
RETURNING id`,
|
||||
[orderId, `正常订单项-${suffix}`],
|
||||
)
|
||||
const cleanItemId = Number(cleanItem.rows[0]!.id)
|
||||
|
||||
await query(
|
||||
`UPDATE fulfillments
|
||||
SET channel = 'affiliate_dash',
|
||||
status = 'assigned',
|
||||
carrier_status = 'ready',
|
||||
source = 'integration_test',
|
||||
updated_at = NOW()
|
||||
WHERE order_item_id = ANY($1::bigint[])`,
|
||||
[[conflictItemId, cleanItemId]],
|
||||
)
|
||||
|
||||
const conflictWorkOrder = await query<{ id: number }>(
|
||||
`INSERT INTO work_orders (
|
||||
work_order_no, order_id, order_item_id, platform_order_id,
|
||||
product_name, status, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, 'accepted', NOW(), NOW())
|
||||
RETURNING id`,
|
||||
[
|
||||
`IT-CONFLICT-WO-${suffix}`,
|
||||
orderId,
|
||||
conflictItemId,
|
||||
`IT-CARRIER-CONFLICT-${suffix}`,
|
||||
`冲突工单-${suffix}`,
|
||||
],
|
||||
)
|
||||
workOrderIds.push(Number(conflictWorkOrder.rows[0]!.id))
|
||||
const cleanWorkOrder = await query<{ id: number }>(
|
||||
`INSERT INTO work_orders (
|
||||
work_order_no, order_id, order_item_id, platform_order_id,
|
||||
product_name, status, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, 'accepted', NOW(), NOW())
|
||||
RETURNING id`,
|
||||
[
|
||||
`IT-CLEAN-WO-${suffix}`,
|
||||
orderId,
|
||||
cleanItemId,
|
||||
`IT-CARRIER-CONFLICT-${suffix}`,
|
||||
`正常工单-${suffix}`,
|
||||
],
|
||||
)
|
||||
workOrderIds.push(Number(cleanWorkOrder.rows[0]!.id))
|
||||
|
||||
const profile = await query<{ id: number }>(
|
||||
`INSERT INTO fulfillment_profiles (
|
||||
profile_key, name, executor_key, requires_claim, auto_dispatch,
|
||||
inventory_strategy, config_json, created_at, updated_at
|
||||
) VALUES ($1, '集成冲突自动发货', 'affiliate_dash', TRUE, FALSE,
|
||||
'static_pool', '{}'::jsonb, NOW(), NOW())
|
||||
RETURNING id`,
|
||||
[`it-carrier-conflict-${suffix}`],
|
||||
)
|
||||
profileId = Number(profile.rows[0]!.id)
|
||||
await query(
|
||||
`INSERT INTO fulfillment_tasks (
|
||||
order_id, order_item_id, unit_index, task_no, provider, platform,
|
||||
shop_id, shop_name, platform_order_id, profile_id, executor_key,
|
||||
task_status, created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
$1, $2, 1, $3, provider, platform, shop_id, shop_name, platform_order_id,
|
||||
$4, 'affiliate_dash', 'paid', NOW(), NOW()
|
||||
FROM orders
|
||||
WHERE id = $1`,
|
||||
[orderId, conflictItemId, `IT-CONFLICT-TASK-${suffix}`, profileId],
|
||||
)
|
||||
|
||||
const conflicts = await findConflictingCarrierOrderItems({
|
||||
limit: 200,
|
||||
cutoffCreatedAt: new Date(0).toISOString(),
|
||||
orderItemIds: [conflictItemId, cleanItemId],
|
||||
})
|
||||
assert.deepEqual(
|
||||
conflicts.rows.map((row) => Number(row.id)),
|
||||
[conflictItemId],
|
||||
)
|
||||
} finally {
|
||||
if (workOrderIds.length > 0) {
|
||||
await query('DELETE FROM work_orders WHERE id = ANY($1::bigint[])', [workOrderIds]).catch(
|
||||
() => undefined,
|
||||
)
|
||||
}
|
||||
if (orderId > 0) {
|
||||
await query('DELETE FROM orders WHERE id = $1', [orderId]).catch(() => undefined)
|
||||
}
|
||||
if (profileId > 0) {
|
||||
await query('DELETE FROM fulfillment_profiles WHERE id = $1', [profileId]).catch(
|
||||
() => undefined,
|
||||
)
|
||||
}
|
||||
await closeDb()
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -458,7 +458,8 @@ export async function reconcilePendingCarriers(
|
||||
`
|
||||
SELECT count(*)::int AS count
|
||||
FROM v_fulfillment_queue oi
|
||||
WHERE oi.carrier_queue_candidate = TRUE
|
||||
WHERE oi.fulfillment_status = 'pending'
|
||||
AND oi.carrier_queue_candidate = TRUE
|
||||
`,
|
||||
)
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
publishAdminOrderRealtimeChange,
|
||||
publishCustomerOrderRealtimeChangeByOrderIds,
|
||||
} from '../realtime/realtime-event-service.js'
|
||||
import { ensureDouyuFulfillmentTasksForOrderItems } from '../douyu-fulfillment/douyu-fulfillment-service.js'
|
||||
|
||||
/**
|
||||
* 管道 A:渠道判定。
|
||||
@@ -459,6 +460,12 @@ export async function assignPendingOrderItemChannels(
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
})
|
||||
await ensureDouyuFulfillmentTasksForOrderItems(assignedItemIds).catch((error) => {
|
||||
logWarn('[channel-assign]', '斗鱼领取任务主动物化失败,等待有界回填', {
|
||||
orderItemIds: assignedItemIds,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
})
|
||||
await scheduleVoucherConsumeForOrderItems(assignedItemIds, 'order_received').catch(
|
||||
(error) => {
|
||||
logWarn('[channel-assign]', '订单收到后安排自动核销失败', {
|
||||
@@ -686,6 +693,12 @@ export async function assignOrderItemsAfterCarrierReady(input: {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
})
|
||||
await ensureDouyuFulfillmentTasksForOrderItems(assignedIds).catch((error) => {
|
||||
logWarn('[channel-assign]', '指定人工渠道后物化斗鱼领取任务失败', {
|
||||
orderItemIds: assignedIds,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
})
|
||||
await scheduleVoucherConsumeForOrderItems(assignedIds, 'order_received').catch((error) => {
|
||||
logWarn('[channel-assign]', '指定渠道后安排自动核销失败', {
|
||||
orderItemIds: assignedIds,
|
||||
@@ -1611,7 +1624,7 @@ export async function retryPendingCarrierGroup(input: {
|
||||
[ids],
|
||||
)
|
||||
if (manualConfigs.rows.length > 0) {
|
||||
await attachFulfillmentConfigurations({
|
||||
const configured = await attachFulfillmentConfigurations({
|
||||
mappings: manualConfigs.rows.map((row) => ({
|
||||
orderItemId: Number(row.order_item_id),
|
||||
configId: Number(row.config_id),
|
||||
@@ -1622,6 +1635,16 @@ export async function retryPendingCarrierGroup(input: {
|
||||
expected: { status: 'assigned', channel: 'manual' },
|
||||
onlyWhenCanonicalProductNull: true,
|
||||
})
|
||||
if (configured.length > 0) {
|
||||
await ensureDouyuFulfillmentTasksForOrderItems(configured.map((row) => Number(row.id))).catch(
|
||||
(error) => {
|
||||
logWarn('[channel-assign]', '人工载体补齐后物化斗鱼领取任务失败', {
|
||||
orderItemIds: configured.map((row) => Number(row.id)),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
if (assignedItemIds.length > 0) {
|
||||
await normalizeProductsForItems(assignedItemIds).catch(() => undefined)
|
||||
|
||||
@@ -52,10 +52,48 @@ test('斗鱼客户读取不再阻塞调用 live-hub,状态由 Webhook 收敛',
|
||||
|
||||
assert.ok(customerRead.includes('return localCustomerFulfillment(task)'))
|
||||
assert.ok(cachedRead.includes('return localCustomerFulfillment'))
|
||||
assert.ok(!customerRead.includes('ensureDouyuFulfillmentTasks'))
|
||||
assert.ok(!cachedRead.includes('ensureDouyuFulfillmentTasks'))
|
||||
assert.ok(!customerRead.includes('ensureLiveSession'))
|
||||
assert.ok(!cachedRead.includes('ensureLiveSession'))
|
||||
})
|
||||
|
||||
test('斗鱼任务由配置挂载事件主动物化,列表只做有界缺失回填', () => {
|
||||
const douyuService = source('../douyu-fulfillment/douyu-fulfillment-service.ts')
|
||||
const financeJobs = source('../scheduler/finance-pipeline-jobs.ts')
|
||||
const channelAssign = source('./channel-assign-service.ts')
|
||||
const carrierCreation = source('./carrier-creation-service.ts')
|
||||
const listRead = douyuService.slice(
|
||||
douyuService.indexOf('export async function listDouyuFulfillmentTasks'),
|
||||
douyuService.indexOf('export async function getDouyuFulfillmentDetail'),
|
||||
)
|
||||
const settingsRead = douyuService.slice(
|
||||
douyuService.indexOf('export async function getDouyuFulfillmentSettings'),
|
||||
douyuService.indexOf('export async function updateDouyuFulfillmentSettings'),
|
||||
)
|
||||
|
||||
assert.ok(listRead.includes('backfillDouyuFulfillmentTasksAutomatically'))
|
||||
assert.ok(!listRead.includes('await ensureDouyuFulfillmentTasks()'))
|
||||
assert.ok(settingsRead.includes('SELECT order_match_started_at'))
|
||||
assert.ok(!settingsRead.includes('INSERT INTO douyu_fulfillment_settings'))
|
||||
assert.ok(douyuService.includes('onlyMissing: true'))
|
||||
assert.ok(financeJobs.includes('ensureDouyuFulfillmentTasksForOrderItems'))
|
||||
assert.ok(channelAssign.includes('ensureDouyuFulfillmentTasksForOrderItems'))
|
||||
assert.ok(carrierCreation.includes('ensureDouyuFulfillmentTasksForOrderItems'))
|
||||
})
|
||||
|
||||
test('载体冲突检查从活跃载体候选集反查,不逐订单项执行三次全表探测', () => {
|
||||
const financeJobs = source('../scheduler/finance-pipeline-jobs.ts')
|
||||
const conflictQuery = financeJobs.slice(
|
||||
financeJobs.indexOf('export async function findConflictingCarrierOrderItems'),
|
||||
financeJobs.indexOf('export async function runCarrierDispatchJob'),
|
||||
)
|
||||
|
||||
assert.ok(conflictQuery.includes('WITH active_carrier_types AS'))
|
||||
assert.ok(conflictQuery.includes('HAVING COUNT(DISTINCT carrier.carrier_type) > 1'))
|
||||
assert.ok(!conflictQuery.includes('v_fulfillment_queue'))
|
||||
})
|
||||
|
||||
test('新单快速推进只处理 actionable 履约桶', () => {
|
||||
const channelAssign = source('./channel-assign-service.ts')
|
||||
const advance = channelAssign.slice(
|
||||
|
||||
@@ -24,6 +24,10 @@ const queueBucketMigration = readFileSync(
|
||||
new URL('../../db/migrations/162_fulfillment_queue_buckets.sql', import.meta.url),
|
||||
'utf8',
|
||||
)
|
||||
const queueActiveScopeMigration = readFileSync(
|
||||
new URL('../../db/migrations/185_fulfillment_queue_active_scope.sql', import.meta.url),
|
||||
'utf8',
|
||||
)
|
||||
|
||||
test('自动发货历史非活跃任务默认阻止后台自动重开', () => {
|
||||
assert.ok(carrierCreation.includes('INACTIVE_CARRIER_TASK_STATUSES.includes'))
|
||||
@@ -48,6 +52,9 @@ test('补载体自动扫描只读取 actionable 队列', () => {
|
||||
assert.ok(queueBucketMigration.includes("'operator_review'"))
|
||||
assert.ok(queueBucketMigration.includes("'terminal'"))
|
||||
assert.ok(queueBucketMigration.includes('actionable_for_carrier'))
|
||||
assert.ok(
|
||||
queueActiveScopeMigration.includes("WHERE state.fulfillment_status IN ('pending', 'assigned')"),
|
||||
)
|
||||
assert.ok(carrierReconciliation.includes("oi.queue_bucket = 'actionable'"))
|
||||
assert.ok(carrierReconciliation.includes('oi.carrier_queue_candidate = TRUE'))
|
||||
assert.ok(carrierReconciliation.includes('createdBefore'))
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
syncCostSnapshotsForItems,
|
||||
} from '../cost-center/cost-snapshot-service.js'
|
||||
import { formatShanghaiDate, shiftDate } from '../../utils/finance-date-range.js'
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
import {
|
||||
recordPipelineError,
|
||||
touchWatermark,
|
||||
@@ -38,6 +39,7 @@ import {
|
||||
publishAdminOrderRealtimeChange,
|
||||
publishCustomerOrderRealtimeChangeByOrderIds,
|
||||
} from '../realtime/realtime-event-service.js'
|
||||
import { ensureDouyuFulfillmentTasksForOrderItems } from '../douyu-fulfillment/douyu-fulfillment-service.js'
|
||||
|
||||
/**
|
||||
* 财务与履约管道作业。
|
||||
@@ -95,49 +97,77 @@ export async function runChannelAssignJob(job: JsonObject = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function findConflictingCarrierOrderItems(input: {
|
||||
limit: number
|
||||
cutoffCreatedAt?: string
|
||||
orderItemIds?: number[]
|
||||
}) {
|
||||
const params: unknown[] = [Math.max(1, Math.trunc(input.limit))]
|
||||
const filters: string[] = []
|
||||
const cutoffCreatedAt = String(input.cutoffCreatedAt || '').trim()
|
||||
if (cutoffCreatedAt && Number.isFinite(Date.parse(cutoffCreatedAt))) {
|
||||
params.push(cutoffCreatedAt)
|
||||
filters.push(`oi.created_at >= $${params.length}::timestamptz`)
|
||||
}
|
||||
const orderItemIds = [
|
||||
...new Set(
|
||||
(input.orderItemIds || []).map(Number).filter((id) => Number.isInteger(id) && id > 0),
|
||||
),
|
||||
]
|
||||
if (orderItemIds.length > 0) {
|
||||
params.push(orderItemIds)
|
||||
filters.push(`oi.id = ANY($${params.length}::bigint[])`)
|
||||
}
|
||||
|
||||
const result = await query<{
|
||||
id: number
|
||||
channel: string
|
||||
sku_code: string
|
||||
internal_sku: string
|
||||
}>(
|
||||
`
|
||||
WITH active_carrier_types AS (
|
||||
SELECT work_order.order_item_id, 'work_order'::text AS carrier_type
|
||||
FROM work_orders work_order
|
||||
WHERE work_order.order_item_id IS NOT NULL
|
||||
AND work_order.status <> 'cancelled'
|
||||
UNION
|
||||
SELECT task.order_item_id, task.executor_key AS carrier_type
|
||||
FROM fulfillment_tasks task
|
||||
WHERE task.executor_key IN ('affiliate_dash', 'manual_dispatch')
|
||||
AND task.task_status NOT IN (
|
||||
'closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled'
|
||||
)
|
||||
),
|
||||
conflicts AS (
|
||||
SELECT carrier.order_item_id
|
||||
FROM active_carrier_types carrier
|
||||
GROUP BY carrier.order_item_id
|
||||
HAVING COUNT(DISTINCT carrier.carrier_type) > 1
|
||||
)
|
||||
SELECT
|
||||
oi.id,
|
||||
oi.fulfillment_channel AS channel,
|
||||
oi.sku_code,
|
||||
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku
|
||||
FROM conflicts conflict
|
||||
JOIN v_order_item_current oi ON oi.id = conflict.order_item_id
|
||||
WHERE oi.fulfillment_status = 'assigned'
|
||||
${filters.length > 0 ? `AND ${filters.join('\n AND ')}` : ''}
|
||||
ORDER BY oi.id
|
||||
LIMIT $1
|
||||
`,
|
||||
params,
|
||||
)
|
||||
return result
|
||||
}
|
||||
|
||||
export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
const config = jobConfig(job)
|
||||
const cutoffCreatedAt = await getFulfillmentAutomationCutoff()
|
||||
const limit = clampInt(config.limit, 200, 1, 2000)
|
||||
const freshWindowMinutes = clampInt(config.freshWindowMinutes, 15, 1, 120)
|
||||
const freshLimit = clampInt(config.freshLimit, 200, 1, 2000)
|
||||
const freshCutoff = new Date(Date.now() - freshWindowMinutes * 60_000).toISOString()
|
||||
const reconcileCursor =
|
||||
config.carrierReconcileAfterId != null
|
||||
? Math.max(0, Math.trunc(Number(config.carrierReconcileAfterId)))
|
||||
: await readWatermarkItemId('carrier_reconcile')
|
||||
const freshReconciled = await reconcilePendingCarriers({
|
||||
limit: Math.min(freshLimit, 200),
|
||||
createdAfter: freshCutoff,
|
||||
orderDirection: 'desc',
|
||||
...(cutoffCreatedAt ? { cutoffCreatedAt } : {}),
|
||||
})
|
||||
const historicalReconciled = await reconcilePendingCarriers({
|
||||
limit: Math.min(limit, 200),
|
||||
afterId: reconcileCursor,
|
||||
createdBefore: freshCutoff,
|
||||
...(cutoffCreatedAt ? { cutoffCreatedAt } : {}),
|
||||
})
|
||||
const reconciled = {
|
||||
...historicalReconciled,
|
||||
scanned: freshReconciled.scanned + historicalReconciled.scanned,
|
||||
workOrdersCreated: freshReconciled.workOrdersCreated + historicalReconciled.workOrdersCreated,
|
||||
affiliateTasksCreated:
|
||||
freshReconciled.affiliateTasksCreated + historicalReconciled.affiliateTasksCreated,
|
||||
fallbacksSelected: freshReconciled.fallbacksSelected + historicalReconciled.fallbacksSelected,
|
||||
failed: freshReconciled.failed + historicalReconciled.failed,
|
||||
}
|
||||
await touchWatermark('carrier_reconcile', { lastItemId: historicalReconciled.nextCursor })
|
||||
const repairedAssigned = await reconcilePendingCarriers({
|
||||
limit: Math.min(limit, 200),
|
||||
includeAssignedMissingCarrier: true,
|
||||
...(cutoffCreatedAt ? { cutoffCreatedAt } : {}),
|
||||
})
|
||||
await assignPendingOrderItemChannels({
|
||||
batchSize: 500,
|
||||
maxBatches: 1,
|
||||
...(cutoffCreatedAt ? { cutoffCreatedAt } : {}),
|
||||
}).catch(() => undefined)
|
||||
const cursor =
|
||||
config.afterId != null
|
||||
? Math.max(0, Math.trunc(Number(config.afterId)))
|
||||
@@ -192,6 +222,14 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
attached = configured.length
|
||||
if (attached > 0) {
|
||||
await ensureSemiAutoTasksForOrderItems(manual.rows.map((row) => Number(row.id)))
|
||||
await ensureDouyuFulfillmentTasksForOrderItems(configured.map((row) => Number(row.id))).catch(
|
||||
(error) => {
|
||||
logWarn('[carrier-dispatch]', '斗鱼领取任务主动物化失败,等待有界回填', {
|
||||
orderItemIds: configured.map((row) => Number(row.id)),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
},
|
||||
)
|
||||
const orderIds = manual.rows.map((row) => Number(row.order_id))
|
||||
for (const orderId of new Set(orderIds)) {
|
||||
publishAdminOrderRealtimeChange(orderId)
|
||||
@@ -200,6 +238,44 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
const freshCutoff = new Date(Date.now() - freshWindowMinutes * 60_000).toISOString()
|
||||
const reconcileCursor =
|
||||
config.carrierReconcileAfterId != null
|
||||
? Math.max(0, Math.trunc(Number(config.carrierReconcileAfterId)))
|
||||
: await readWatermarkItemId('carrier_reconcile')
|
||||
const freshReconciled = await reconcilePendingCarriers({
|
||||
limit: Math.min(freshLimit, 200),
|
||||
createdAfter: freshCutoff,
|
||||
orderDirection: 'desc',
|
||||
...(cutoffCreatedAt ? { cutoffCreatedAt } : {}),
|
||||
})
|
||||
const historicalReconciled = await reconcilePendingCarriers({
|
||||
limit: Math.min(limit, 200),
|
||||
afterId: reconcileCursor,
|
||||
createdBefore: freshCutoff,
|
||||
...(cutoffCreatedAt ? { cutoffCreatedAt } : {}),
|
||||
})
|
||||
const reconciled = {
|
||||
...historicalReconciled,
|
||||
scanned: freshReconciled.scanned + historicalReconciled.scanned,
|
||||
workOrdersCreated: freshReconciled.workOrdersCreated + historicalReconciled.workOrdersCreated,
|
||||
affiliateTasksCreated:
|
||||
freshReconciled.affiliateTasksCreated + historicalReconciled.affiliateTasksCreated,
|
||||
fallbacksSelected: freshReconciled.fallbacksSelected + historicalReconciled.fallbacksSelected,
|
||||
failed: freshReconciled.failed + historicalReconciled.failed,
|
||||
}
|
||||
await touchWatermark('carrier_reconcile', { lastItemId: historicalReconciled.nextCursor })
|
||||
const repairedAssigned = await reconcilePendingCarriers({
|
||||
limit: Math.min(limit, 200),
|
||||
includeAssignedMissingCarrier: true,
|
||||
...(cutoffCreatedAt ? { cutoffCreatedAt } : {}),
|
||||
})
|
||||
await assignPendingOrderItemChannels({
|
||||
batchSize: 500,
|
||||
maxBatches: 1,
|
||||
...(cutoffCreatedAt ? { cutoffCreatedAt } : {}),
|
||||
}).catch(() => undefined)
|
||||
|
||||
// 人工渠道但没有配置:进「人工 SKU 未配置」队列。
|
||||
const missingManualParams: unknown[] = [limit, cursor, configKeys]
|
||||
const missingManualCutoff = fulfillmentCreatedAfterSql(missingManualParams, cutoffCreatedAt)
|
||||
@@ -340,43 +416,10 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
}
|
||||
|
||||
// 已分配订单出现两个真实执行方时不能继续算正常渠道,必须进冲突队列人工处置。
|
||||
const conflictingCarrierParams: unknown[] = [limit]
|
||||
const conflictingCarrierCutoff = fulfillmentCreatedAfterSql(
|
||||
conflictingCarrierParams,
|
||||
const conflictingCarriers = await findConflictingCarrierOrderItems({
|
||||
limit,
|
||||
cutoffCreatedAt,
|
||||
)
|
||||
const conflictingCarriers = await query<{
|
||||
id: number
|
||||
channel: string
|
||||
sku_code: string
|
||||
internal_sku: string
|
||||
}>(
|
||||
`
|
||||
SELECT oi.id, oi.fulfillment_channel AS channel, oi.sku_code,
|
||||
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku
|
||||
FROM v_order_item_current oi
|
||||
WHERE oi.fulfillment_status = 'assigned'
|
||||
AND (
|
||||
EXISTS (SELECT 1 FROM work_orders wo WHERE wo.order_item_id = oi.id AND wo.status <> 'cancelled')
|
||||
)::int + (
|
||||
EXISTS (
|
||||
SELECT 1 FROM fulfillment_tasks ft
|
||||
WHERE ft.order_item_id = oi.id AND ft.executor_key = 'affiliate_dash'
|
||||
AND ft.task_status NOT IN ('closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled')
|
||||
)
|
||||
)::int + (
|
||||
EXISTS (
|
||||
SELECT 1 FROM fulfillment_tasks ft
|
||||
WHERE ft.order_item_id = oi.id AND ft.executor_key = 'manual_dispatch'
|
||||
AND ft.task_status NOT IN ('closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled')
|
||||
)
|
||||
)::int > 1
|
||||
${conflictingCarrierCutoff}
|
||||
ORDER BY oi.id
|
||||
LIMIT $1
|
||||
`,
|
||||
conflictingCarrierParams,
|
||||
)
|
||||
})
|
||||
for (const row of conflictingCarriers.rows) {
|
||||
exceptionEntries.push({
|
||||
reason: 'routing_conflict',
|
||||
@@ -474,7 +517,7 @@ async function resolveCarrierDispatchExceptions(cutoffCreatedAt: string): Promis
|
||||
attachParams,
|
||||
)
|
||||
if (attachCandidates.rows.length > 0) {
|
||||
await attachFulfillmentConfigurations({
|
||||
const attached = await attachFulfillmentConfigurations({
|
||||
mappings: attachCandidates.rows.map((row) => ({
|
||||
orderItemId: Number(row.order_item_id),
|
||||
configId: Number(row.config_id),
|
||||
@@ -482,6 +525,16 @@ async function resolveCarrierDispatchExceptions(cutoffCreatedAt: string): Promis
|
||||
expected: { status: 'assigned', channel: 'manual' },
|
||||
onlyWhenConfigNull: true,
|
||||
})
|
||||
if (attached.length > 0) {
|
||||
await ensureDouyuFulfillmentTasksForOrderItems(attached.map((row) => Number(row.id))).catch(
|
||||
(error) => {
|
||||
logWarn('[carrier-dispatch]', '异常收口后物化斗鱼领取任务失败', {
|
||||
orderItemIds: attached.map((row) => Number(row.id)),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const carrierParams: unknown[] = []
|
||||
|
||||
@@ -40,7 +40,7 @@ import {
|
||||
Typography,
|
||||
} from 'antd'
|
||||
import type { MenuProps } from 'antd'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Outlet, useLocation, useNavigate } from 'react-router'
|
||||
|
||||
@@ -83,6 +83,23 @@ import dayjs from '@/lib/dayjs'
|
||||
|
||||
const SIDEBAR_COLLAPSED_KEY = 'react-admin-sidebar-collapsed'
|
||||
const NOTIFICATION_SOUND_KEY = 'admin-notification-sound-enabled'
|
||||
const DOUYU_REFRESH_DEBOUNCE_MS = 500
|
||||
const douyuRefreshTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
|
||||
function invalidateDouyuQueriesSoon(
|
||||
queryClient: QueryClient,
|
||||
queryKey: readonly unknown[],
|
||||
delayMs = DOUYU_REFRESH_DEBOUNCE_MS,
|
||||
) {
|
||||
const key = JSON.stringify(queryKey)
|
||||
const existing = douyuRefreshTimers.get(key)
|
||||
if (existing) clearTimeout(existing)
|
||||
const timer = setTimeout(() => {
|
||||
douyuRefreshTimers.delete(key)
|
||||
void queryClient.invalidateQueries({ queryKey })
|
||||
}, delayMs)
|
||||
douyuRefreshTimers.set(key, timer)
|
||||
}
|
||||
|
||||
export default function AdminLayout() {
|
||||
const navigate = useNavigate()
|
||||
@@ -211,7 +228,7 @@ export default function AdminLayout() {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-notifications'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-tasks'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-orders'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-douyu-fulfillment'] })
|
||||
invalidateDouyuQueriesSoon(queryClient, ['admin-douyu-fulfillment'], 0)
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-dashboard-summary'] })
|
||||
},
|
||||
// 会话过期时清登录态回登录页,避免 SSE 带着失效 token 无限重连刷 401。
|
||||
@@ -563,7 +580,7 @@ function applyAdminRealtimeEvent(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
) {
|
||||
if (event.type === 'order.changed' && event.scopes.includes('admin_douyu_fulfillment')) {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-douyu-fulfillment'] })
|
||||
invalidateDouyuQueriesSoon(queryClient, ['admin-douyu-fulfillment'])
|
||||
}
|
||||
if (event.type === 'order.changed' && event.scopes.includes('admin_semi_auto_tasks')) {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-tasks'] })
|
||||
|
||||
@@ -94,6 +94,7 @@ const EVENT_LABELS: Record<string, string> = {
|
||||
export default function AdminDouyuFulfillmentPage() {
|
||||
const { message } = App.useApp()
|
||||
const queryClient = useQueryClient()
|
||||
const [keywordInput, setKeywordInput] = useState('')
|
||||
const [keyword, setKeyword] = useState('')
|
||||
const [status, setStatus] = useState('')
|
||||
const [page, setPage] = useState(1)
|
||||
@@ -296,9 +297,17 @@ export default function AdminDouyuFulfillmentPage() {
|
||||
<Input.Search
|
||||
allowClear
|
||||
placeholder="订单号 / 商品 / 角色名"
|
||||
value={keyword}
|
||||
value={keywordInput}
|
||||
onChange={(event) => {
|
||||
setKeyword(event.target.value)
|
||||
const next = event.target.value
|
||||
setKeywordInput(next)
|
||||
if (!next.trim()) {
|
||||
setKeyword('')
|
||||
setPage(1)
|
||||
}
|
||||
}}
|
||||
onSearch={(value) => {
|
||||
setKeyword(value.trim())
|
||||
setPage(1)
|
||||
}}
|
||||
style={{ width: 300 }}
|
||||
|
||||
@@ -10,6 +10,7 @@ const page = readFileSync(
|
||||
new URL('../src/pages/admin/AdminDouyuFulfillmentPage.tsx', import.meta.url),
|
||||
'utf8',
|
||||
)
|
||||
const layout = readFileSync(new URL('../src/layouts/AdminLayout.tsx', import.meta.url), 'utf8')
|
||||
|
||||
test('斗鱼领取列表必须把筛选参数直接交给 axios', () => {
|
||||
assert.match(service, /'\/api\/v1\/admin\/douyu-fulfillment\/tasks',\s*params\)/)
|
||||
@@ -22,3 +23,20 @@ test('斗鱼领取列表查询键必须包含关键词和状态', () => {
|
||||
/queryKey:\s*\['admin-douyu-fulfillment',\s*keyword,\s*status,\s*page,\s*pageSize\]/,
|
||||
)
|
||||
})
|
||||
|
||||
test('斗鱼领取搜索只在提交时触发查询,输入过程不逐字请求', () => {
|
||||
assert.match(page, /onSearch=\{\(value\)\s*=>\s*\{[\s\S]*setKeyword\(value\.trim\(\)\)/)
|
||||
assert.doesNotMatch(
|
||||
page,
|
||||
/onChange=\{\(event\)\s*=>\s*\{[\s\S]*setKeyword\(event\.target\.value\)/,
|
||||
)
|
||||
})
|
||||
|
||||
test('斗鱼实时事件必须合并刷新,不能每条 SSE 都触发列表重拉', () => {
|
||||
assert.match(layout, /DOUYU_REFRESH_DEBOUNCE_MS\s*=\s*500/)
|
||||
assert.match(layout, /invalidateDouyuQueriesSoon/)
|
||||
assert.doesNotMatch(
|
||||
layout,
|
||||
/event\.scopes\.includes\('admin_douyu_fulfillment'\)\)\s*\{\s*void queryClient\.invalidateQueries/,
|
||||
)
|
||||
})
|
||||
|
||||
+11
-5
@@ -3,16 +3,16 @@ type: 权威架构与实施计划
|
||||
description: 订单、内部 SKU、履约路由、履约执行、商品、成本与财务的唯一权威口径及重构计划。
|
||||
tags: [订单, 内部SKU, 履约, 商品, 成本, 财务, 迁移]
|
||||
status: authoritative
|
||||
version: 2.40
|
||||
updated_at: 2026-11-27
|
||||
version: 2.41
|
||||
updated_at: 2026-11-28
|
||||
---
|
||||
|
||||
# 统一订单、履约与财务模型
|
||||
|
||||
> 状态:**唯一权威文档**。
|
||||
> 最后校准:2026-11-27。
|
||||
> 最后校准:2026-11-28。
|
||||
> 生产基线:迁移 `175`(2026-11-19 核对)。
|
||||
> 开发基线:迁移 `181`(仅本地,尚未部署生产)。
|
||||
> 开发基线:迁移 `185`(仅本地,尚未部署生产)。
|
||||
>
|
||||
> 从本文件生效起,订单、内部 SKU、履约渠道、履约载体、标准商品、成本和财务相关实现,
|
||||
> 只能以本文件为业务口径。其他旧分析只作为历史资料,不再具备设计或验收效力。
|
||||
@@ -456,6 +456,9 @@ manual fulfillment
|
||||
- 斗鱼客户页 `GET /api/v1/douyu-fulfillment/<订单号>` 和 live-hub 后台任务详情 GET 必须是纯读:
|
||||
不得在读取接口中同步准备账号、调用平台或触发全量订单同步。未准备完成时返回 `preparing`
|
||||
或现有安全投影,后续由事务事件更新并通过 SSE 通知页面重读。
|
||||
- 斗鱼领取任务在主链路写入人工配置关联后按 `orderItemId` 定向物化,不等待客户打开链接或
|
||||
后台列表触发。后台列表只允许执行最近 30 天、最多 500 条、15 秒节流的缺失任务回填;
|
||||
手工同步可执行一次全量缺失回填,但不得逐条覆盖全部历史候选。
|
||||
- live-hub 的低频对账只允许补齐状态 Outbox 和异常任务,不得重新承担正常订单发现;
|
||||
正常订单发现完全由 order_site 事务 Outbox 驱动。
|
||||
- 后台“任务 → 半自动履约”由 SSE 失效通知驱动读取,不得对列表或详情做固定秒级轮询。
|
||||
@@ -1265,7 +1268,7 @@ docs/archive/
|
||||
|
||||
## 十三、当前下一步
|
||||
|
||||
截至 2026-11-25,生产基线为 `175`,当前开发基线为 `181`。迁移 `152` 保护订单来源快照,
|
||||
截至 2026-11-28,生产基线为 `175`,当前开发基线为 `185`。迁移 `152` 保护订单来源快照,
|
||||
迁移 `158–160` 收口寄卖登记人同步、寄卖平台与自动匹配设置;
|
||||
迁移 `161` 一次建立人工渠道半自动任务、内置 Connector 默认值、账号级 Cookie JSON 凭证、
|
||||
任务凭证引用和最终约束;迁移 `162` 建立履约待办四桶只读投影、补载体专用索引和新单优先扫描口径。
|
||||
@@ -1297,6 +1300,9 @@ pending 角色快照、`role_identity_source` 与 `verification_basis`。
|
||||
排障留档,不进入绑定 verdict。
|
||||
迁移 `181` 建立系统邀请码、邀请权限、邀请事件、注册来源字段和冻结连坐触发器;
|
||||
个人邀请码继续使用 `worker_users.invite_code` 原字段,迁移不改名、不改值、不重算。
|
||||
迁移 `184` 增加平台订单号精确检索和活跃履约任务执行器反查索引,消除载体冲突检查对每个
|
||||
已分配订单项执行三次探测的计划。迁移 `185` 将 `v_fulfillment_queue` 收敛为仅包含
|
||||
`pending / assigned` 履约记录,`archived` 不再进入待办投影或阻塞补载体扫描。
|
||||
迁移 `169` 增加客户游戏角色资料字段(`customer_game_role_name` / `customer_game_role_id` /
|
||||
`customer_game_server_zone`),并允许从工单素材回退合并;当前客户资料要求角色名、UID 和区服三项齐全,
|
||||
其中 `customer_game_role_id` 只校验非空,不校验格式。客户页流程收敛为
|
||||
|
||||
Reference in New Issue
Block a user