修复生产PostgreSQL高CPU与15秒超时热路径(迁移187)

This commit is contained in:
yml
2026-11-28 19:50:46 +08:00
parent 2ec5ff7af5
commit f68dc7c217
12 changed files with 735 additions and 203 deletions
@@ -0,0 +1,86 @@
-- 187_order_site_hotpath_optimization.sql
--
-- 修复生产 PostgreSQL 高 CPU(137%-230%)与 15s statement_timeout 根因:
-- 1. fulfillment_tasks:affiliate_dash / kuaishou_feifei 回调 JSONB 表达式索引;
-- 以及 affiliate_dash 失败任务窄部分索引(供 runAffiliateFallback 驱动查询);
-- 2. fulfillments:已分配 affiliate_dash 未锁定、已挂载人工配置、自动/工单载体全集窄部分索引;
-- 3. orders:店铺名修剪值 + id DESC 部分索引,配合递归松散索引扫描优先命中最新工单订单;
-- 4. admin_notifications:待办默认排序表达式部分索引(urgent>high>normal, updated_at DESC, id DESC);
-- 5. work_orders / work_order_shares:接单排序与全量排行榜覆盖索引(Index Only Scan)。
-- 1. 回调反查 JSONB 精确表达式索引(消除 affiliate_dash / kuaishou_feifei 回调 15s 超时)
CREATE INDEX IF NOT EXISTS idx_fulfillment_tasks_affiliate_dash_order_no
ON fulfillment_tasks ((context_json #>> '{affiliateDash,orderNo}'), id DESC)
WHERE executor_key = 'affiliate_dash'
AND COALESCE(context_json #>> '{affiliateDash,orderNo}', '') <> '';
CREATE INDEX IF NOT EXISTS idx_fulfillment_tasks_affiliate_dash_client_order_no
ON fulfillment_tasks ((context_json #>> '{affiliateDash,clientOrderNo}'), id DESC)
WHERE executor_key = 'affiliate_dash'
AND COALESCE(context_json #>> '{affiliateDash,clientOrderNo}', '') <> '';
CREATE INDEX IF NOT EXISTS idx_fulfillment_tasks_kuaishou_feifei_platform_order_no
ON fulfillment_tasks ((context_json #>> '{kuaishouFeifei,platformOrderNo}'), id DESC)
WHERE executor_key = 'kuaishou_feifei'
AND COALESCE(context_json #>> '{kuaishouFeifei,platformOrderNo}', '') <> '';
CREATE INDEX IF NOT EXISTS idx_fulfillment_tasks_kuaishou_feifei_order_no
ON fulfillment_tasks ((context_json #>> '{kuaishouFeifei,orderNo}'), id DESC)
WHERE executor_key = 'kuaishou_feifei'
AND COALESCE(context_json #>> '{kuaishouFeifei,orderNo}', '') <> '';
-- 2. 自动发货转人工兜底驱动索引(先锁定失败任务,再按 PK 关联 fulfillments)
CREATE INDEX IF NOT EXISTS idx_fulfillment_tasks_affiliate_failed_item
ON fulfillment_tasks (order_item_id, unit_index DESC, updated_at DESC, id DESC)
WHERE executor_key = 'affiliate_dash'
AND task_status IN ('closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled');
CREATE INDEX IF NOT EXISTS idx_fulfillments_assigned_affiliate_unlocked
ON fulfillments (order_item_id, order_id)
WHERE status = 'assigned'
AND channel = 'affiliate_dash'
AND locked = FALSE;
-- 3. carrier-dispatch 人工已配 / 载体全集窄部分索引
CREATE INDEX IF NOT EXISTS idx_fulfillments_assigned_manual_configured
ON fulfillments (order_item_id, order_id)
WHERE status = 'assigned'
AND channel = 'manual'
AND fulfillment_config_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_fulfillments_assigned_carrier_all
ON fulfillments (order_item_id, order_id)
WHERE status = 'assigned'
AND channel IN ('affiliate_dash', 'work_order');
-- 4. 接单工单店铺名下拉:按店铺 + 最新订单 id DESC 优先探测工单存在性
CREATE INDEX IF NOT EXISTS idx_orders_shop_name_trimmed_id_desc
ON orders (BTRIM(shop_name) ASC, id DESC)
WHERE BTRIM(shop_name) <> '';
-- 5. 管理端待办通知排序部分索引(消除 2.3 万行堆扫排序)
CREATE INDEX IF NOT EXISTS idx_admin_notifications_visible_pending_rank
ON admin_notifications (
(CASE priority WHEN 'urgent' THEN 3 WHEN 'high' THEN 2 ELSE 1 END) DESC,
updated_at DESC,
id DESC
)
WHERE status = 'pending' AND visible = TRUE;
-- 6. 打手工单列表排序与全量排行榜覆盖索引
CREATE INDEX IF NOT EXISTS idx_work_orders_created_id_desc
ON work_orders (created_at DESC, id DESC);
CREATE INDEX IF NOT EXISTS idx_work_orders_leaderboard_accepted
ON work_orders (assigned_worker_id)
INCLUDE (order_id, platform_order_id, accepted_at)
WHERE status = 'accepted' AND assigned_worker_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_work_order_shares_accepted_cover
ON work_order_shares (worker_id, work_order_id)
INCLUDE (accepted_at)
WHERE status = 'accepted';
CREATE INDEX IF NOT EXISTS idx_work_orders_id_order_key_cover
ON work_orders (id)
INCLUDE (order_id, platform_order_id);
+42 -40
View File
@@ -406,38 +406,56 @@ export async function findTaskByClaimTokenId(
const KUAISHOU_FEIFEI_EXECUTOR_KEY = 'kuaishou_feifei'
async function findExecutorTaskByJsonKeys(
executorKey: string,
jsonFilters: Array<{ jsonPath: string; value: string }>,
): Promise<TaskRow | null> {
if (jsonFilters.length === 0) {
return null
}
const params: unknown[] = [executorKey]
const unionBranches = jsonFilters.map(({ jsonPath, value }) => {
params.push(value)
const paramRef = `$${params.length}`
return `(
SELECT ft_idx.id
FROM fulfillment_tasks ft_idx
WHERE ft_idx.executor_key = $1
AND ft_idx.context_json #>> '${jsonPath}' = ${paramRef}
AND COALESCE(ft_idx.context_json #>> '${jsonPath}', '') <> ''
ORDER BY ft_idx.id DESC
LIMIT 1
)`
})
const result = await query<TaskRow>(
`WITH candidate_ids AS (
${unionBranches.join('\n UNION ALL\n ')}
)
${buildTaskSelect()}
WHERE ft.id = (SELECT c.id FROM candidate_ids c ORDER BY c.id DESC LIMIT 1)`,
params,
)
return result.rows[0] || null
}
export async function findKuaishouFeifeiTaskByOrder(input: {
platformOrderNo?: unknown
orderNo?: unknown
}): Promise<TaskRow | null> {
const platformOrderNo = String(input.platformOrderNo || '').trim()
const orderNo = String(input.orderNo || '').trim()
const params: unknown[] = [KUAISHOU_FEIFEI_EXECUTOR_KEY]
const orderFilters: string[] = []
const jsonFilters: Array<{ jsonPath: string; value: string }> = []
if (platformOrderNo) {
params.push(platformOrderNo)
orderFilters.push(`ft.context_json #>> '{kuaishouFeifei,platformOrderNo}' = $${params.length}`)
jsonFilters.push({ jsonPath: '{kuaishouFeifei,platformOrderNo}', value: platformOrderNo })
}
if (orderNo) {
params.push(orderNo)
orderFilters.push(`ft.context_json #>> '{kuaishouFeifei,orderNo}' = $${params.length}`)
jsonFilters.push({ jsonPath: '{kuaishouFeifei,orderNo}', value: orderNo })
}
if (orderFilters.length === 0) {
return null
}
const result = await query<TaskRow>(
`${buildTaskSelect()}
WHERE ft.executor_key = $1
AND (${orderFilters.join(' OR ')})
ORDER BY ft.id DESC
LIMIT 1`,
params,
)
return result.rows[0] || null
return findExecutorTaskByJsonKeys(KUAISHOU_FEIFEI_EXECUTOR_KEY, jsonFilters)
}
export async function findAffiliateDashTaskByOrder(input: {
@@ -446,32 +464,16 @@ export async function findAffiliateDashTaskByOrder(input: {
}): Promise<TaskRow | null> {
const orderNo = String(input.orderNo || '').trim()
const clientOrderNo = String(input.clientOrderNo || '').trim()
const params: unknown[] = [AFFILIATE_DASH_EXECUTOR_KEY]
const orderFilters: string[] = []
const jsonFilters: Array<{ jsonPath: string; value: string }> = []
if (orderNo) {
params.push(orderNo)
orderFilters.push(`ft.context_json #>> '{affiliateDash,orderNo}' = $${params.length}`)
jsonFilters.push({ jsonPath: '{affiliateDash,orderNo}', value: orderNo })
}
if (clientOrderNo) {
params.push(clientOrderNo)
orderFilters.push(`ft.context_json #>> '{affiliateDash,clientOrderNo}' = $${params.length}`)
jsonFilters.push({ jsonPath: '{affiliateDash,clientOrderNo}', value: clientOrderNo })
}
if (orderFilters.length === 0) {
return null
}
const result = await query<TaskRow>(
`${buildTaskSelect()}
WHERE ft.executor_key = $1
AND (${orderFilters.join(' OR ')})
ORDER BY ft.id DESC
LIMIT 1`,
params,
)
return result.rows[0] || null
return findExecutorTaskByJsonKeys(AFFILIATE_DASH_EXECUTOR_KEY, jsonFilters)
}
export async function listTasks({
@@ -513,13 +513,41 @@ export async function listWorkOrders({
*/
export async function listWorkOrderShopNames(): Promise<string[]> {
const result = await query<{ shop_name: string }>(
// 从 orders 出发 + EXISTS 半连接:18 万工单的 hash join 实测 3.1 秒,
// 改成 orders 驱动后走 idx_work_orders_order_id 半连接,约 0.3 秒。
`SELECT DISTINCT BTRIM(o.shop_name) AS shop_name
FROM orders o
WHERE BTRIM(o.shop_name) <> ''
AND EXISTS (SELECT 1 FROM work_orders wo WHERE wo.order_id = o.id)
ORDER BY shop_name ASC`,
// 先通过递归松散索引扫描(idx_orders_shop_name_trimmed)在毫秒级列出全部非空店铺,
// 再按 idx_orders_shop_name_trimmed_id_desc 倒序探测最新订单是否存在工单,
// 避免对 55 万 orders + 24 万 work_orders 做全表哈希半连接。
`WITH RECURSIVE distinct_shops AS (
(
SELECT BTRIM(o.shop_name) AS shop_name
FROM orders o
WHERE BTRIM(o.shop_name) <> ''
ORDER BY BTRIM(o.shop_name) ASC
LIMIT 1
)
UNION ALL
SELECT next_shop.shop_name
FROM distinct_shops ds
CROSS JOIN LATERAL (
SELECT BTRIM(o.shop_name) AS shop_name
FROM orders o
WHERE BTRIM(o.shop_name) <> ''
AND BTRIM(o.shop_name) > ds.shop_name
ORDER BY BTRIM(o.shop_name) ASC
LIMIT 1
) next_shop
)
SELECT ds.shop_name
FROM distinct_shops ds
CROSS JOIN LATERAL (
SELECT 1 AS has_work_order
FROM orders o
WHERE BTRIM(o.shop_name) <> ''
AND BTRIM(o.shop_name) = ds.shop_name
AND EXISTS (SELECT 1 FROM work_orders wo WHERE wo.order_id = o.id)
ORDER BY BTRIM(o.shop_name) ASC, o.id DESC
LIMIT 1
) wo_probe
ORDER BY ds.shop_name ASC`,
)
return result.rows
.map((row) => String(row.shop_name || '').trim())
@@ -13,8 +13,10 @@ import {
type WorkerPlatformNotificationEventKey,
} from '../worker-platform/worker-platform-notification-config-service.js'
import { publishRealtimeEvent } from '../realtime/realtime-event-service.js'
import { WorkerListCache } from '../worker-platform/worker-list-cache.js'
const ADMIN_WORKER_PLATFORM_PATH = '/admin/worker-platform'
const pendingNotificationsCache = new WorkerListCache(10_000, 32)
export async function createWorkerWithdrawAdminNotification(input: {
requestId: number
@@ -221,6 +223,7 @@ export async function remindWorkerAcceptanceAdminNotification(workOrderId: numbe
soundEnabled: eventConfig.todoEnabled && eventConfig.soundEnabled,
now,
})
pendingNotificationsCache.clear()
if (notification && eventConfig.externalPushEnabled) {
void notifyInternalSafely({
title: '打手催促验收',
@@ -259,6 +262,7 @@ export async function resolveAdminNotificationEntity(
reason,
now: new Date().toISOString(),
})
pendingNotificationsCache.clear()
publishRealtimeEvent({
type: 'admin_notification.changed',
entityId,
@@ -271,14 +275,16 @@ export async function resolveAdminNotificationEntity(
export async function listAdminPendingNotifications(limit = 20) {
const normalizedLimit = Math.min(50, Math.max(1, Math.floor(Number(limit) || 20)))
const [items, pendingCount] = await Promise.all([
listPendingAdminNotifications(normalizedLimit),
countPendingAdminNotifications(),
])
return {
pendingCount,
items: items.map(mapAdminNotification),
}
return pendingNotificationsCache.getOrSet(String(normalizedLimit), async () => {
const [items, pendingCount] = await Promise.all([
listPendingAdminNotifications(normalizedLimit),
countPendingAdminNotifications(),
])
return {
pendingCount,
items: items.map(mapAdminNotification),
}
})
}
export function mapAdminNotification(row: AdminNotificationRow) {
@@ -319,6 +325,7 @@ async function createConfiguredWorkerPlatformNotification(
visible: eventConfig.todoEnabled,
soundEnabled: eventConfig.todoEnabled && eventConfig.soundEnabled,
})
pendingNotificationsCache.clear()
if (notification && eventConfig.externalPushEnabled) {
void notifyInternalSafely({
title: notification.title,
@@ -918,16 +918,17 @@ export async function rematchManualFulfillments(input: Record<string, unknown> =
oi.id AS order_item_id,
cfg.id AS config_id,
cfg.canonical_product_id
FROM v_order_item_current oi
FROM fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
JOIN orders o ON o.id = oi.order_id
JOIN manual_fulfillment_configs cfg
ON canonicalize_internal_sku(cfg.sku_key) = resolve_internal_sku(
oi.manual_sku_key, oi.sku_name, oi.sku_code
)
WHERE oi.fulfillment_status = 'assigned' AND oi.fulfillment_channel = 'manual'
WHERE f.status = 'assigned' AND f.channel = 'manual'
AND cfg.enabled = TRUE
AND ($1 = '' OR canonicalize_internal_sku(cfg.sku_key) = $1)
AND ($2 = FALSE OR oi.fulfillment_config_id IS NULL)
AND ($2 = FALSE OR f.fulfillment_config_id IS NULL)
AND (
$3::date IS NULL
OR (COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date >= $3::date
@@ -133,8 +133,7 @@ test('人工确认前必须自动匹配履约配置,配置保存/定时任务
'标准商品、人工配置和人工渠道规则必须同一事务提交',
)
assert.ok(
jobSource.includes("fulfillment_channel = 'manual'") &&
jobSource.includes('fulfillment_config_id'),
jobSource.includes("f.channel = 'manual'") && jobSource.includes('f.fulfillment_config_id'),
'人工载体管道必须挂载人工配置',
)
assert.ok(
@@ -196,7 +195,7 @@ test('人工成本缺失由管道按配置与快照生成并收口', async () =>
assert.ok(pipelineSource.includes("'manual_cost_missing'"), '管道必须产出人工成本缺失异常')
assert.ok(
pipelineSource.includes("cs.subject_type = 'manual_case'") &&
pipelineSource.includes('cs.order_item_id = oi.id'),
pipelineSource.includes('cs.order_item_id = cp.order_item_id'),
'人工成本缺失必须以人工快照是否存在为判定',
)
assert.ok(
@@ -45,6 +45,12 @@ export async function runAffiliateFallback(
basis_date: string
}>(
`
WITH failed_affiliate_items AS (
SELECT DISTINCT ft_fail.order_item_id
FROM fulfillment_tasks ft_fail
WHERE ft_fail.executor_key = 'affiliate_dash'
AND ft_fail.task_status = ANY($1::text[])
)
SELECT
oi.id,
oi.id AS order_item_id,
@@ -55,18 +61,20 @@ export async function runAffiliateFallback(
cfg.id AS config_id,
cfg.canonical_product_id AS config_product_id,
(COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date::text AS basis_date
FROM v_order_item_current oi
FROM failed_affiliate_items fai
JOIN fulfillments f
ON f.order_item_id = fai.order_item_id
AND f.status = 'assigned'
AND f.channel = 'affiliate_dash'
AND f.locked = FALSE
JOIN order_items oi ON oi.id = f.order_item_id
JOIN orders o ON o.id = oi.order_id
LEFT JOIN manual_fulfillment_configs cfg
JOIN manual_fulfillment_configs cfg
ON canonicalize_internal_sku(cfg.sku_key) = resolve_internal_sku(
oi.manual_sku_key, oi.sku_name, oi.sku_code
)
AND cfg.enabled
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'affiliate_dash'
AND oi.fulfillment_locked = FALSE
AND cfg.id IS NOT NULL
AND EXISTS (
WHERE EXISTS (
SELECT 1
FROM sku_channel_routes route
JOIN internal_skus sku ON sku.id = route.internal_sku_id
@@ -265,3 +265,220 @@ test(
}
},
)
test(
'迁移 187 回调 JSONB 反查、店铺名松散索引、待办通知排序与 carrier_dispatch 游标推进',
{ 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 { findAffiliateDashTaskByOrder, findKuaishouFeifeiTaskByOrder } =
await import('../../repositories/task-repo.js')
const { listWorkOrderShopNames } =
await import('../../repositories/worker-platform/work-order-query-repo.js')
const { listAdminPendingNotifications, resolveAdminNotificationEntity } =
await import('../admin/admin-notification-service.js')
const { createAdminNotification } =
await import('../../repositories/admin-notification-repo.js')
const { runCarrierDispatchJob } = await import('../scheduler/finance-pipeline-jobs.js')
const { readWatermarkItemId, touchWatermark } = await import('../watermark-store.js')
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
let orderWithWoId = 0
let orderWithoutWoId = 0
let profileId = 0
let workOrderId = 0
const createdNotifIds: number[] = []
const originalDispatchCursor = await readWatermarkItemId('carrier_dispatch')
try {
const shopWithWo = `AAA_工单店铺_${suffix}`
const shopWithoutWo = `AAA_无工单店铺_${suffix}`
const orderWithWo = 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, $3,
'paid', 'paid', 1000, NOW(), NOW(), NOW()
) RETURNING id`,
[`shop-wo-${suffix}`, shopWithWo, `IT-HOTPATH-WO-${suffix}`],
)
orderWithWoId = Number(orderWithWo.rows[0]!.id)
const orderWithoutWo = 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, $3,
'paid', 'paid', 1000, NOW(), NOW(), NOW()
) RETURNING id`,
[`shop-nowo-${suffix}`, shopWithoutWo, `IT-HOTPATH-NOWO-${suffix}`],
)
orderWithoutWoId = Number(orderWithoutWo.rows[0]!.id)
const item1 = 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`,
[orderWithWoId, `热路径测试商品-${suffix}`],
)
const item1Id = Number(item1.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-hotpath-profile-${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, context_json, created_at, updated_at
) VALUES (
$1, $2, 1, $3, 'affiliate', 'douyin', 's1', '店1', $4, $5, 'affiliate_dash', 'pending_payment',
jsonb_build_object('affiliateDash', jsonb_build_object('orderNo', $6::text, 'clientOrderNo', $7::text)),
NOW(), NOW()
)`,
[
orderWithWoId,
item1Id,
`IT-AFF-JSON-${suffix}`,
`IT-HOTPATH-WO-${suffix}`,
profileId,
`AFF-ORD-${suffix}`,
`AFF-CLI-${suffix}`,
],
)
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, context_json, created_at, updated_at
) VALUES (
$1, $2, 2, $3, 'kuaishou', 'kuaishou', 's2', '店2', $4, $5, 'kuaishou_feifei', 'pending_payment',
jsonb_build_object('kuaishouFeifei', jsonb_build_object('platformOrderNo', $6::text, 'orderNo', $7::text)),
NOW(), NOW()
)`,
[
orderWithWoId,
item1Id,
`IT-KS-JSON-${suffix}`,
`IT-HOTPATH-WO-${suffix}`,
profileId,
`KS-PLAT-${suffix}`,
`KS-ORD-${suffix}`,
],
)
const affByOrder = await findAffiliateDashTaskByOrder({ orderNo: `AFF-ORD-${suffix}` })
const affByClient = await findAffiliateDashTaskByOrder({ clientOrderNo: `AFF-CLI-${suffix}` })
const ksByPlatform = await findKuaishouFeifeiTaskByOrder({
platformOrderNo: `KS-PLAT-${suffix}`,
})
const ksByOrder = await findKuaishouFeifeiTaskByOrder({ orderNo: `KS-ORD-${suffix}` })
assert.equal(affByOrder?.task_no, `IT-AFF-JSON-${suffix}`)
assert.equal(affByClient?.task_no, `IT-AFF-JSON-${suffix}`)
assert.equal(ksByPlatform?.task_no, `IT-KS-JSON-${suffix}`)
assert.equal(ksByOrder?.task_no, `IT-KS-JSON-${suffix}`)
assert.equal(await findAffiliateDashTaskByOrder({ orderNo: '' }), null)
const wo = await query<{ id: number }>(
`INSERT INTO work_orders (
work_order_no, order_id, order_item_id, platform_order_id, product_name,
status, reward_amount, required_deposit_amount, created_at, updated_at
) VALUES ($1, $2, $3, $4, '热路径工单', 'open', 100, 0, NOW(), NOW())
RETURNING id`,
[`IT-WO-SHOP-${suffix}`, orderWithWoId, item1Id, `IT-HOTPATH-WO-${suffix}`],
)
workOrderId = Number(wo.rows[0]!.id)
const shops = await listWorkOrderShopNames()
assert.ok(shops.includes(shopWithWo))
assert.ok(!shops.includes(shopWithoutWo))
const normalNotif = await createAdminNotification({
notificationType: 'it_hotpath',
priority: 'normal',
entityType: 'it_hotpath_entity',
entityId: orderWithWoId,
dedupeKey: `it_hotpath_normal_${suffix}`,
title: `普通通知-${suffix}`,
body: 'body',
actionPath: '/',
now: new Date(Date.now() + 1000).toISOString(),
visible: true,
soundEnabled: false,
})
const urgentNotif = await createAdminNotification({
notificationType: 'it_hotpath',
priority: 'urgent',
entityType: 'it_hotpath_entity',
entityId: orderWithWoId,
dedupeKey: `it_hotpath_urgent_${suffix}`,
title: `紧急通知-${suffix}`,
body: 'body',
actionPath: '/',
now: new Date().toISOString(),
visible: true,
soundEnabled: false,
})
if (normalNotif) createdNotifIds.push(Number(normalNotif.id))
if (urgentNotif) createdNotifIds.push(Number(urgentNotif.id))
const pending = await listAdminPendingNotifications(50)
const urgentIdx = pending.items.findIndex(
(item) => item.notificationId === Number(urgentNotif?.id),
)
const normalIdx = pending.items.findIndex(
(item) => item.notificationId === Number(normalNotif?.id),
)
assert.ok(urgentIdx >= 0 && normalIdx >= 0 && urgentIdx < normalIdx)
await resolveAdminNotificationEntity('it_hotpath_entity', orderWithWoId, 'it_cleanup')
const afterResolve = await listAdminPendingNotifications(50)
assert.ok(!afterResolve.items.some((item) => item.notificationId === Number(urgentNotif?.id)))
// 验证 carrier_dispatch 在已分配记录全部已有异常(0 新增异常)时依然按扫描页推进游标
await query(
`UPDATE fulfillments
SET status = 'assigned', channel = 'work_order', source = 'integration_test', updated_at = NOW()
WHERE order_item_id = $1`,
[item1Id],
)
await touchWatermark('carrier_dispatch', { lastItemId: item1Id - 1 })
await runCarrierDispatchJob({ config: { limit: 1, afterId: item1Id - 1 } })
assert.ok((await readWatermarkItemId('carrier_dispatch')) >= item1Id)
} finally {
await touchWatermark('carrier_dispatch', { lastItemId: originalDispatchCursor }).catch(
() => undefined,
)
if (createdNotifIds.length > 0) {
await query('DELETE FROM admin_notifications WHERE id = ANY($1::bigint[])', [
createdNotifIds,
]).catch(() => undefined)
}
if (workOrderId > 0) {
await query('DELETE FROM work_orders WHERE id = $1', [workOrderId]).catch(() => undefined)
}
if (orderWithWoId > 0) {
await query('DELETE FROM orders WHERE id = $1', [orderWithWoId]).catch(() => undefined)
}
if (orderWithoutWoId > 0) {
await query('DELETE FROM orders WHERE id = $1', [orderWithoutWoId]).catch(() => undefined)
}
if (profileId > 0) {
await query('DELETE FROM fulfillment_profiles WHERE id = $1', [profileId]).catch(
() => undefined,
)
}
await closeDb()
}
},
)
@@ -140,3 +140,56 @@ test('新单快速推进只处理 actionable 履约桶', () => {
assert.ok(advance.includes('reconcilePendingCarriers'))
assert.ok(!advance.includes('includeNonActionable'))
})
test('热路径数据库优化迁移 187 与对应仓储查询守卫生效', () => {
const migration187 = source('../../db/migrations/187_order_site_hotpath_optimization.sql')
const taskRepo = source('../../repositories/task-repo.ts')
const affiliateFallback = source('./affiliate-fallback-service.ts')
const financeJobs = source('../scheduler/finance-pipeline-jobs.ts')
const manualConfig = source('../cost-center/manual-fulfillment-config-service.ts')
const workOrderQueryRepo = source('../../repositories/worker-platform/work-order-query-repo.ts')
const adminNotificationService = source('../admin/admin-notification-service.ts')
const workerHallService = source('../worker-platform/worker-hall-service.ts')
assert.ok(migration187.includes('idx_fulfillment_tasks_affiliate_dash_order_no'))
assert.ok(migration187.includes('idx_fulfillment_tasks_kuaishou_feifei_platform_order_no'))
assert.ok(migration187.includes('idx_fulfillment_tasks_affiliate_failed_item'))
assert.ok(migration187.includes('idx_fulfillments_assigned_manual_configured'))
assert.ok(migration187.includes('idx_orders_shop_name_trimmed_id_desc'))
assert.ok(migration187.includes('idx_admin_notifications_visible_pending_rank'))
assert.ok(migration187.includes('idx_work_orders_leaderboard_accepted'))
const jsonLookup = taskRepo.slice(
taskRepo.indexOf('async function findExecutorTaskByJsonKeys'),
taskRepo.indexOf('export async function findKuaishouFeifeiTaskByOrder'),
)
assert.ok(jsonLookup.includes('UNION ALL'))
assert.ok(!jsonLookup.includes(' OR '))
assert.ok(affiliateFallback.includes('WITH failed_affiliate_items AS'))
assert.ok(!affiliateFallback.includes('FROM v_order_item_current oi'))
const carrierDispatchBody = financeJobs.slice(
financeJobs.indexOf('export async function runCarrierDispatchJob'),
financeJobs.indexOf('export async function runProductNormalizeJob'),
)
assert.ok(carrierDispatchBody.includes('WITH candidate_page AS'))
assert.ok(carrierDispatchBody.includes('scanned_max_id'))
assert.ok(!carrierDispatchBody.includes('FROM v_order_item_current oi'))
assert.ok(
!manualConfig
.slice(manualConfig.indexOf('export async function rematchManualFulfillments'))
.includes('FROM v_order_item_current oi'),
)
const shopNamesBody = workOrderQueryRepo.slice(
workOrderQueryRepo.indexOf('export async function listWorkOrderShopNames'),
workOrderQueryRepo.indexOf('export async function countWorkOrders'),
)
assert.ok(shopNamesBody.includes('WITH RECURSIVE distinct_shops AS'))
assert.ok(shopNamesBody.includes('ORDER BY BTRIM(o.shop_name) ASC, o.id DESC'))
assert.ok(adminNotificationService.includes('pendingNotificationsCache.getOrSet('))
assert.ok(adminNotificationService.includes('pendingNotificationsCache.clear()'))
assert.ok(workerHallService.includes('HALL_ALL_LEADERBOARD_CACHE_TTL_MS'))
})
@@ -172,7 +172,7 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
config.afterId != null
? Math.max(0, Math.trunc(Number(config.afterId)))
: await readWatermarkItemId('carrier_dispatch')
let maxId = 0
const freshCutoff = new Date(Date.now() - freshWindowMinutes * 60_000).toISOString()
const configKeysResult = await query<{ sku_key: string }>(
'SELECT canonicalize_internal_sku(sku_key) AS sku_key FROM manual_fulfillment_configs WHERE enabled',
)
@@ -191,19 +191,20 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
oi.order_id,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS sku_key,
cfg.id AS config_id
FROM v_order_item_current oi
FROM fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
JOIN manual_fulfillment_configs cfg
ON canonicalize_internal_sku(cfg.sku_key) = resolve_internal_sku(
oi.manual_sku_key, oi.sku_name, oi.sku_code
)
AND cfg.enabled
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
AND oi.fulfillment_config_id IS NULL
WHERE f.status = 'assigned'
AND f.channel = 'manual'
AND f.fulfillment_config_id IS NULL
AND resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) = ANY($3::text[])
AND oi.id > $2
AND f.order_item_id > $2
${manualCutoff}
ORDER BY oi.id
ORDER BY f.order_item_id
LIMIT $1
`,
manualParams,
@@ -238,7 +239,6 @@ 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)))
@@ -304,33 +304,69 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
...(cutoffCreatedAt ? { cutoffCreatedAt } : {}),
}).catch(() => undefined)
// 人工渠道但没有配置:进「人工 SKU 未配置」队列。
const missingManualParams: unknown[] = [limit, cursor, configKeys]
const missingManualCutoff = fulfillmentCreatedAfterSql(missingManualParams, cutoffCreatedAt)
const missingManual = await query<{ id: number; sku_key: string }>(
`
SELECT oi.id,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS sku_key
FROM v_order_item_current oi
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
AND oi.fulfillment_config_id IS NULL
AND NOT (resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) = ANY($3::text[]))
AND NOT EXISTS (
SELECT 1
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
WHERE i.order_item_id = oi.id
AND ce.reason = 'manual_config_missing'
AND ce.status <> 'resolved'
// 人工渠道但没有配置:只扫描窄部分索引一页,并保留新单窗口优先。
const missingManualRows: Array<{ id: number; sku_key: string }> = []
const missingManualPageMaxIds: number[] = []
for (const mode of ['fresh', 'historical'] as const) {
const params: unknown[] =
mode === 'fresh' ? [freshLimit, freshCutoff, configKeys] : [limit, cursor, configKeys]
const cutoffSql = fulfillmentCreatedAfterSql(params, cutoffCreatedAt)
const scopeSql =
mode === 'fresh' ? 'AND oi.created_at >= $2::timestamptz' : 'AND f.order_item_id > $2'
const orderSql = mode === 'fresh' ? 'DESC' : 'ASC'
const res = await query<{
id: number | null
sku_key: string | null
scanned_max_id: number
}>(
`
WITH candidate_page AS (
SELECT
f.order_item_id,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS sku_key
FROM fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
WHERE f.status = 'assigned'
AND f.channel = 'manual'
AND f.fulfillment_config_id IS NULL
AND NOT (resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) = ANY($3::text[]))
${scopeSql}
${cutoffSql}
ORDER BY f.order_item_id ${orderSql}
LIMIT $1
),
page_bounds AS (
SELECT COALESCE(MAX(order_item_id), 0)::bigint AS scanned_max_id FROM candidate_page
),
filtered AS (
SELECT cp.order_item_id AS id, cp.sku_key
FROM candidate_page cp
WHERE NOT EXISTS (
SELECT 1
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
WHERE i.order_item_id = cp.order_item_id
AND ce.reason = 'manual_config_missing'
AND ce.status <> 'resolved'
)
)
AND oi.id > $2
${missingManualCutoff}
ORDER BY oi.id
LIMIT $1
`,
missingManualParams,
)
SELECT f.id, f.sku_key, pb.scanned_max_id
FROM page_bounds pb
LEFT JOIN filtered f ON TRUE
`,
params,
)
const scannedMax = Number(res.rows[0]?.scanned_max_id || 0)
if (mode === 'historical' && scannedMax > 0) missingManualPageMaxIds.push(scannedMax)
for (const row of res.rows) {
if (row.id != null) {
missingManualRows.push({ id: Number(row.id), sku_key: String(row.sku_key || '') })
}
}
}
const missingManual = {
rows: dedupeRowsById(missingManualRows),
}
const exceptionEntries: AggregatedExceptionEntry[] = []
for (const row of missingManual.rows) {
@@ -342,41 +378,73 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
})
}
// 已配置人工 SKU、但还没确认履约的单:进入「人工成本未记录」队列。
const pendingManualCostParams: unknown[] = [limit, cursor]
const pendingManualCostCutoff = fulfillmentCreatedAfterSql(
pendingManualCostParams,
cutoffCreatedAt,
)
const pendingManualCost = await query<{ id: number; sku_key: string }>(
`
SELECT oi.id,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS sku_key
FROM v_order_item_current oi
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
AND oi.fulfillment_config_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM cost_snapshots cs
WHERE cs.subject_type = 'manual_case'
AND cs.order_item_id = oi.id
AND cs.superseded_at IS NULL AND reversed_at IS NULL
// 已配置人工 SKU、但还没确认履约的单:按有界候选页推进游标 + 新单直达。
const pendingManualCostRows: Array<{ id: number; sku_key: string }> = []
const pendingManualCostPageMaxIds: number[] = []
for (const mode of ['fresh', 'historical'] as const) {
const params: unknown[] = mode === 'fresh' ? [freshLimit, freshCutoff] : [limit, cursor]
const cutoffSql = fulfillmentCreatedAfterSql(params, cutoffCreatedAt)
const scopeSql =
mode === 'fresh' ? 'AND oi.created_at >= $2::timestamptz' : 'AND f.order_item_id > $2'
const orderSql = mode === 'fresh' ? 'DESC' : 'ASC'
const res = await query<{
id: number | null
sku_key: string | null
scanned_max_id: number
}>(
`
WITH candidate_page AS (
SELECT
f.order_item_id,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS sku_key
FROM fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
WHERE f.status = 'assigned'
AND f.channel = 'manual'
AND f.fulfillment_config_id IS NOT NULL
${scopeSql}
${cutoffSql}
ORDER BY f.order_item_id ${orderSql}
LIMIT $1
),
page_bounds AS (
SELECT COALESCE(MAX(order_item_id), 0)::bigint AS scanned_max_id FROM candidate_page
),
filtered AS (
SELECT cp.order_item_id AS id, cp.sku_key
FROM candidate_page cp
WHERE NOT EXISTS (
SELECT 1 FROM cost_snapshots cs
WHERE cs.subject_type = 'manual_case'
AND cs.order_item_id = cp.order_item_id
AND cs.superseded_at IS NULL AND cs.reversed_at IS NULL
)
AND NOT EXISTS (
SELECT 1
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
WHERE i.order_item_id = cp.order_item_id
AND ce.reason = 'manual_cost_missing'
AND ce.status <> 'resolved'
)
)
AND NOT EXISTS (
SELECT 1
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
WHERE i.order_item_id = oi.id
AND ce.reason = 'manual_cost_missing'
AND ce.status <> 'resolved'
)
AND oi.id > $2
${pendingManualCostCutoff}
ORDER BY oi.id
LIMIT $1
`,
pendingManualCostParams,
)
SELECT f.id, f.sku_key, pb.scanned_max_id
FROM page_bounds pb
LEFT JOIN filtered f ON TRUE
`,
params,
)
const scannedMax = Number(res.rows[0]?.scanned_max_id || 0)
if (mode === 'historical' && scannedMax > 0) pendingManualCostPageMaxIds.push(scannedMax)
for (const row of res.rows) {
if (row.id != null) {
pendingManualCostRows.push({ id: Number(row.id), sku_key: String(row.sku_key || '') })
}
}
}
const pendingManualCost = {
rows: dedupeRowsById(pendingManualCostRows),
}
for (const row of pendingManualCost.rows) {
exceptionEntries.push({
@@ -387,48 +455,95 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
})
}
// 自动发货 / 接单平台被运营指定后却没有载体:不能静默卡住,进问题队列。
const missingCarrierParams: unknown[] = [limit, cursor]
const missingCarrierCutoff = fulfillmentCreatedAfterSql(missingCarrierParams, cutoffCreatedAt)
const missingCarrierRaw = await query<{
// 自动发货 / 接单平台被运营指定后却没有载体:按有界候选页扫描,避免 0 异常时每轮回到 id > 0 重扫全表。
const missingCarrierPageRows: Array<{
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
LEFT JOIN work_orders wo ON wo.order_item_id = oi.id AND wo.status <> 'cancelled'
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel IN ('affiliate_dash', 'work_order')
AND wo.id IS NULL
AND NOT 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')
}> = []
const missingCarrierPageMaxIds: number[] = []
for (const mode of ['fresh', 'historical'] as const) {
const params: unknown[] = mode === 'fresh' ? [freshLimit, freshCutoff] : [limit, cursor]
const cutoffSql = fulfillmentCreatedAfterSql(params, cutoffCreatedAt)
const scopeSql =
mode === 'fresh' ? 'AND oi.created_at >= $2::timestamptz' : 'AND f.order_item_id > $2'
const orderSql = mode === 'fresh' ? 'DESC' : 'ASC'
const res = await query<{
id: number | null
channel: string | null
sku_code: string | null
internal_sku: string | null
scanned_max_id: number
}>(
`
WITH candidate_page AS (
SELECT
f.order_item_id,
f.channel,
oi.sku_code,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku
FROM fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
WHERE f.status = 'assigned'
AND f.channel IN ('affiliate_dash', 'work_order')
${scopeSql}
${cutoffSql}
ORDER BY f.order_item_id ${orderSql}
LIMIT $1
),
page_bounds AS (
SELECT COALESCE(MAX(order_item_id), 0)::bigint AS scanned_max_id FROM candidate_page
),
filtered AS (
SELECT cp.order_item_id AS id, cp.channel, cp.sku_code, cp.internal_sku
FROM candidate_page cp
LEFT JOIN work_orders wo ON wo.order_item_id = cp.order_item_id AND wo.status <> 'cancelled'
WHERE wo.id IS NULL
AND NOT EXISTS (
SELECT 1 FROM fulfillment_tasks ft
WHERE ft.order_item_id = cp.order_item_id
AND ft.executor_key = 'affiliate_dash'
AND ft.task_status NOT IN ('closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled')
)
)
AND oi.id > $2
${missingCarrierCutoff}
ORDER BY oi.id
LIMIT $1
`,
missingCarrierParams,
)
SELECT fl.id, fl.channel, fl.sku_code, fl.internal_sku, pb.scanned_max_id
FROM page_bounds pb
LEFT JOIN filtered fl ON TRUE
`,
params,
)
const scannedMax = Number(res.rows[0]?.scanned_max_id || 0)
if (mode === 'historical' && scannedMax > 0) missingCarrierPageMaxIds.push(scannedMax)
for (const row of res.rows) {
if (row.id != null) {
missingCarrierPageRows.push({
id: Number(row.id),
channel: String(row.channel || ''),
sku_code: String(row.sku_code || ''),
internal_sku: String(row.internal_sku || ''),
})
}
}
}
const missingCarrierRaw = {
rows: dedupeRowsById(missingCarrierPageRows),
}
const queuedCarrier = await query<{ order_item_id: number }>(
`
SELECT DISTINCT i.order_item_id
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
WHERE i.order_item_id = ANY($1::bigint[])
AND ce.reason = 'carrier_missing'
AND ce.status <> 'resolved'
`,
[missingCarrierRaw.rows.map((row) => row.id)],
)
const queuedCarrier =
missingCarrierRaw.rows.length > 0
? await query<{ order_item_id: number }>(
`
SELECT DISTINCT i.order_item_id
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
WHERE i.order_item_id = ANY($1::bigint[])
AND ce.reason = 'carrier_missing'
AND ce.status <> 'resolved'
`,
[missingCarrierRaw.rows.map((row) => row.id)],
)
: { rows: [] }
const queuedSet = new Set(queuedCarrier.rows.map((row) => Number(row.order_item_id)))
const missingCarrier = {
rows: missingCarrierRaw.rows.filter((row) => !queuedSet.has(Number(row.id))),
@@ -465,16 +580,6 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
await upsertAggregatedExceptionsBatch(exceptionEntries)
}
for (const row of [
...manual.rows,
...missingManual.rows,
...pendingManualCost.rows,
...missingCarrier.rows,
...conflictingCarriers.rows,
]) {
maxId = Math.max(maxId, Number(row.id))
}
const resolved = await resolveCarrierDispatchExceptions(cutoffCreatedAt)
const fallback = await runAffiliateFallback({
limit: 200,
@@ -483,7 +588,13 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
scanned: 0,
switched: 0,
}))
const nextCursor = maxId === 0 ? 0 : maxId
const scannedHistoricalMaxIds = [
...missingManualPageMaxIds,
...pendingManualCostPageMaxIds,
...missingCarrierPageMaxIds,
...(manual.rows.length > 0 ? [Math.max(...manual.rows.map((row) => Number(row.id)))] : []),
].filter((id) => Number.isFinite(id) && id > cursor)
const nextCursor = scannedHistoricalMaxIds.length > 0 ? Math.min(...scannedHistoricalMaxIds) : 0
await touchWatermark('carrier_dispatch', { lastItemId: nextCursor })
return {
status: 'ok',
@@ -518,7 +629,8 @@ async function resolveCarrierDispatchExceptions(cutoffCreatedAt: string): Promis
SELECT DISTINCT ON (oi.id)
oi.id AS order_item_id,
cfg.id AS config_id
FROM v_order_item_current oi
FROM fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
JOIN manual_fulfillment_configs cfg
ON canonicalize_internal_sku(cfg.sku_key) = resolve_internal_sku(
oi.manual_sku_key, oi.sku_name, oi.sku_code
@@ -527,9 +639,9 @@ async function resolveCarrierDispatchExceptions(cutoffCreatedAt: string): Promis
WHERE canonicalize_internal_sku(cfg.sku_key) = resolve_internal_sku(
oi.manual_sku_key, oi.sku_name, oi.sku_code
)
AND oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
AND oi.fulfillment_config_id IS NULL
AND f.status = 'assigned'
AND f.channel = 'manual'
AND f.fulfillment_config_id IS NULL
AND EXISTS (
SELECT 1
FROM cost_exception_items i
@@ -577,13 +689,14 @@ async function resolveCarrierDispatchExceptions(cutoffCreatedAt: string): Promis
SELECT DISTINCT i.order_item_id
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
JOIN v_order_item_current oi ON oi.id = i.order_item_id
JOIN fulfillments f ON f.order_item_id = i.order_item_id
JOIN order_items oi ON oi.id = f.order_item_id
WHERE ce.reason = 'carrier_missing'
AND ce.status <> 'resolved'
AND (
(oi.fulfillment_channel = 'work_order'
(f.channel = 'work_order'
AND EXISTS (SELECT 1 FROM work_orders wo WHERE wo.order_item_id = oi.id AND wo.status <> 'cancelled'))
OR (oi.fulfillment_channel = 'affiliate_dash' AND EXISTS (
OR (f.channel = 'affiliate_dash' AND EXISTS (
SELECT 1 FROM fulfillment_tasks ft
WHERE ft.order_item_id = oi.id
AND ft.executor_key = 'affiliate_dash'
@@ -600,10 +713,11 @@ async function resolveCarrierDispatchExceptions(cutoffCreatedAt: string): Promis
SELECT DISTINCT i.order_item_id
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
JOIN v_order_item_current oi ON oi.id = i.order_item_id
JOIN fulfillments f ON f.order_item_id = i.order_item_id
JOIN order_items oi ON oi.id = f.order_item_id
WHERE ce.reason = 'manual_config_missing'
AND ce.status <> 'resolved'
AND oi.fulfillment_config_id IS NOT NULL
AND f.fulfillment_config_id IS NOT NULL
${configCutoff}
LIMIT 500
`,
@@ -614,7 +728,7 @@ async function resolveCarrierDispatchExceptions(cutoffCreatedAt: string): Promis
SELECT DISTINCT i.order_item_id
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
JOIN v_order_item_current oi ON oi.id = i.order_item_id
JOIN order_items oi ON oi.id = i.order_item_id
WHERE ce.reason = 'manual_cost_missing'
AND ce.status <> 'resolved'
AND EXISTS (
@@ -785,3 +899,13 @@ async function resolveCatchUpStart(
const candidate = lastDate < windowStart ? lastDate : windowStart
return candidate < earliest ? earliest : candidate
}
function dedupeRowsById<T extends { id: number }>(rows: T[]): T[] {
const byId = new Map<number, T>()
for (const row of rows) {
if (!byId.has(row.id)) {
byId.set(row.id, row)
}
}
return [...byId.values()]
}
@@ -40,7 +40,9 @@ const HALL_MAX_PAGE_SIZE = 20
// 彻底消解按 workerId 区分缓存导致的缓存击穿与单次 8.5 秒全表扫描问题。
// 打手自身若在 Top 10 中直接取其 rank,若未上榜则名次为 null,单数走 1.8ms 精准索引独立缓存。
const HALL_LEADERBOARD_CACHE_TTL_MS = 30_000
const HALL_ALL_LEADERBOARD_CACHE_TTL_MS = 5 * 60_000
const hallLeaderboardCache = new WorkerListCache(HALL_LEADERBOARD_CACHE_TTL_MS)
const hallAllLeaderboardCache = new WorkerListCache(HALL_ALL_LEADERBOARD_CACHE_TTL_MS, 4)
const workerPersonalCountCache = new WorkerListCache(15_000)
export async function listWorkerHallOrders(query: JsonObject = {}, session: WorkerSession) {
@@ -153,15 +155,19 @@ export async function getWorkerHallCategories(session: WorkerSession) {
export async function getWorkerHallLeaderboard(session: WorkerSession, period: unknown = 'all') {
requireActiveWorkerSession(session)
const leaderboardPeriod = period === 'daily' ? 'daily' : 'all'
// 全局公共缓存 Key,所有打手共享同一份 Top 10,TTL 30s
// 全局公共缓存 Key,所有打手共享同一份 Top 10;总榜额外复用 5 分钟二级缓存,避免每 30 秒全量扫工单
const cacheKey = JSON.stringify([leaderboardPeriod])
const entries = await hallLeaderboardCache.getOrSet(cacheKey, () =>
listWorkerCompletionLeaderboard({
limit: 10,
currentWorkerId: 0,
period: leaderboardPeriod,
}),
)
const entries = await hallLeaderboardCache.getOrSet(cacheKey, () => {
const loadLeaderboard = () =>
listWorkerCompletionLeaderboard({
limit: 10,
currentWorkerId: 0,
period: leaderboardPeriod,
})
return leaderboardPeriod === 'all'
? hallAllLeaderboardCache.getOrSet(cacheKey, loadLeaderboard)
: loadLeaderboard()
})
const currentWorkerId = Number(session.workerId)
const topEntry = entries.find((entry) => entry.workerId === currentWorkerId)
@@ -11,8 +11,8 @@ updated_at: 2026-11-28
> 状态:**唯一权威文档**。
> 最后校准:2026-11-28。
> 生产基线:迁移 `185`(2026-11-28 核对)。
> 开发基线:迁移 `186`(仅本地,尚未部署生产)。
> 生产基线:迁移 `186`(2026-11-28 部署验证)。
> 开发基线:迁移 `187`(热路径索引与 SQL 优化,仅本地)。
>
> 从本文件生效起,订单、内部 SKU、履约渠道、履约载体、标准商品、成本和财务相关实现,
> 只能以本文件为业务口径。其他旧分析只作为历史资料,不再具备设计或验收效力。
@@ -1300,6 +1300,7 @@ pending 角色快照、`role_identity_source` 与 `verification_basis`。
`pending / assigned` 履约记录,`archived` 不再进入待办投影或阻塞补载体扫描。
迁移 `186` 增加 `idx_fulfillments_assigned_carrier_active` 与 `idx_fulfillments_assigned_manual_unconfigured` 热路径部分索引,
配合渠道分配同轮挂接 `fulfillment_config_id`、`carrier-dispatch` 直连 `fulfillments` 的两段式有界游标扫描(`carrier_assigned_repair`)与斗鱼后台严格纯读(精确单号未物化时返回只读 `pendingHints`),消除后台超时、`carrier-dispatch` 长查询锁竞争与 `manual` 新单卡在未配置态等待 12–26 分钟的链路断层。
迁移 `187` 补齐 `fulfillment_tasks` 回调 JSONB 表达式索引(`affiliate_dash` / `kuaishou_feifei`)、自动发货失败任务窄索引、`fulfillments` 已配人工及自动/工单载体部分索引、`orders` 修剪店铺名倒序索引、`admin_notifications` 待办排序表达式部分索引及 `work_orders` 排行榜覆盖索引;配合 `carrier_dispatch` 有界分页游标与 `runAffiliateFallback` 失败任务反查,消除 15s 语句超时、店铺下拉/通知排序/总榜全表扫描与 `carrier_dispatch` 零异常回绕。
迁移 `169` 增加客户游戏角色资料字段(`customer_game_role_name` / `customer_game_role_id` /
`customer_game_server_zone`),并允许从工单素材回退合并;当前客户资料要求角色名、UID 和区服三项齐全,
其中 `customer_game_role_id` 只校验非空,不校验格式。客户页流程收敛为