修复履约与工单热路径二次超时(迁移188)
This commit is contained in:
@@ -914,17 +914,14 @@ export async function rematchManualFulfillments(input: Record<string, unknown> =
|
||||
}>(
|
||||
`
|
||||
WITH target AS (
|
||||
SELECT DISTINCT ON (oi.id)
|
||||
oi.id AS order_item_id,
|
||||
SELECT DISTINCT ON (f.order_item_id)
|
||||
f.order_item_id AS order_item_id,
|
||||
cfg.id AS config_id,
|
||||
cfg.canonical_product_id
|
||||
FROM fulfillments f
|
||||
JOIN order_items oi ON oi.id = f.order_item_id
|
||||
JOIN orders o ON o.id = oi.order_id
|
||||
JOIN orders o ON o.id = f.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
|
||||
)
|
||||
ON cfg.sku_key = f.internal_sku
|
||||
WHERE f.status = 'assigned' AND f.channel = 'manual'
|
||||
AND cfg.enabled = TRUE
|
||||
AND ($1 = '' OR canonicalize_internal_sku(cfg.sku_key) = $1)
|
||||
@@ -937,7 +934,7 @@ export async function rematchManualFulfillments(input: Record<string, unknown> =
|
||||
$4::date IS NULL
|
||||
OR (COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date <= $4::date
|
||||
)
|
||||
ORDER BY oi.id, cfg.id
|
||||
ORDER BY f.order_item_id, cfg.id
|
||||
)
|
||||
SELECT order_item_id, config_id, canonical_product_id
|
||||
FROM target
|
||||
|
||||
@@ -327,7 +327,21 @@ async function materializeDouyuFulfillmentTasks(input: {
|
||||
createdAfter?: string
|
||||
onlyMissing?: boolean
|
||||
}) {
|
||||
const params: unknown[] = []
|
||||
const configResult = await query<{ id: number }>(
|
||||
`
|
||||
SELECT id
|
||||
FROM manual_fulfillment_configs
|
||||
WHERE enabled = TRUE
|
||||
AND douyu_fulfillment_enabled = TRUE
|
||||
ORDER BY id
|
||||
`,
|
||||
)
|
||||
const configIds = configResult.rows.map((row) => Number(row.id)).filter((id) => id > 0)
|
||||
if (configIds.length === 0) {
|
||||
return { created: 0, updated: 0 }
|
||||
}
|
||||
|
||||
const params: unknown[] = [configIds]
|
||||
const filters: string[] = []
|
||||
const orderNo = String(input.orderNo || '').trim()
|
||||
if (orderNo) {
|
||||
@@ -354,6 +368,29 @@ async function materializeDouyuFulfillmentTasks(input: {
|
||||
: null
|
||||
const limitSql = limit ? `LIMIT ${limit}` : ''
|
||||
const onlyMissingFilter = input.onlyMissing ? 'AND existing.id IS NULL' : ''
|
||||
const targetedByOrderItem = orderItemIds.length > 0
|
||||
const candidateSourceSql = targetedByOrderItem
|
||||
? `
|
||||
FROM order_items oi
|
||||
JOIN orders o ON o.id = oi.order_id
|
||||
JOIN fulfillments f ON f.order_item_id = oi.id
|
||||
`
|
||||
: `
|
||||
FROM orders o
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT
|
||||
fulfillment.id,
|
||||
fulfillment.order_item_id,
|
||||
fulfillment.fulfillment_config_id
|
||||
FROM fulfillments fulfillment
|
||||
WHERE fulfillment.order_id = o.id
|
||||
AND fulfillment.channel = 'manual'
|
||||
AND fulfillment.status IN ('assigned', 'processing', 'completed')
|
||||
AND fulfillment.fulfillment_config_id = ANY($1::bigint[])
|
||||
OFFSET 0
|
||||
) f
|
||||
JOIN order_items oi ON oi.id = f.order_item_id
|
||||
`
|
||||
|
||||
const result = await query<{
|
||||
task_id: number
|
||||
@@ -368,22 +405,21 @@ async function materializeDouyuFulfillmentTasks(input: {
|
||||
o.platform_order_id,
|
||||
oi.id AS order_item_id,
|
||||
f.id AS fulfillment_id,
|
||||
cfg.id AS config_id,
|
||||
f.fulfillment_config_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
|
||||
${candidateSourceSql}
|
||||
LEFT JOIN douyu_fulfillment_tasks existing ON existing.order_item_id = oi.id
|
||||
WHERE cfg.enabled = TRUE
|
||||
AND cfg.douyu_fulfillment_enabled = TRUE
|
||||
WHERE f.fulfillment_config_id = ANY($1::bigint[])
|
||||
AND f.channel = 'manual'
|
||||
AND f.status IN ('assigned', 'processing', 'completed')
|
||||
AND COALESCE(o.paid_at, o.created_at) >= settings.order_match_started_at
|
||||
AND COALESCE(o.paid_at, o.created_at) >= (
|
||||
SELECT order_match_started_at
|
||||
FROM douyu_fulfillment_settings
|
||||
WHERE id = 1
|
||||
)
|
||||
${filters.length > 0 ? `AND ${filters.join('\n AND ')}` : ''}
|
||||
${onlyMissingFilter}
|
||||
ORDER BY o.id DESC, oi.id ASC
|
||||
ORDER BY COALESCE(o.paid_at, o.created_at) DESC, o.id DESC, oi.id ASC
|
||||
${limitSql}
|
||||
),
|
||||
upserted AS (
|
||||
|
||||
@@ -455,6 +455,20 @@ test(
|
||||
await touchWatermark('carrier_dispatch', { lastItemId: item1Id - 1 })
|
||||
await runCarrierDispatchJob({ config: { limit: 1, afterId: item1Id - 1 } })
|
||||
assert.ok((await readWatermarkItemId('carrier_dispatch')) >= item1Id)
|
||||
|
||||
const renamedShop = `AAA_改名工单店铺_${suffix}`
|
||||
await query(`UPDATE orders SET shop_name = $2, updated_at = NOW() WHERE id = $1`, [
|
||||
orderWithWoId,
|
||||
renamedShop,
|
||||
])
|
||||
const renamedShops = await listWorkOrderShopNames()
|
||||
assert.ok(renamedShops.includes(renamedShop))
|
||||
assert.ok(!renamedShops.includes(shopWithWo))
|
||||
|
||||
await query(`DELETE FROM work_orders WHERE id = $1`, [workOrderId])
|
||||
workOrderId = 0
|
||||
const shopsAfterDelete = await listWorkOrderShopNames()
|
||||
assert.ok(!shopsAfterDelete.includes(renamedShop))
|
||||
} finally {
|
||||
await touchWatermark('carrier_dispatch', { lastItemId: originalDispatchCursor }).catch(
|
||||
() => undefined,
|
||||
|
||||
@@ -66,29 +66,31 @@ async function loadCandidateItems(input: {
|
||||
.map(Number)
|
||||
.filter((value) => Number.isInteger(value) && value > 0)
|
||||
const params: unknown[] = [input.limit]
|
||||
const scopeAlias = input.assignedMissingCarrier ? 'f' : 'oi'
|
||||
const idColumn = input.assignedMissingCarrier ? 'f.order_item_id' : 'oi.id'
|
||||
let idFilter = ''
|
||||
if (ids.length > 0) {
|
||||
params.push(ids)
|
||||
idFilter = `AND oi.id = ANY($${params.length}::bigint[])`
|
||||
idFilter = `AND ${idColumn} = ANY($${params.length}::bigint[])`
|
||||
} else if (Number(input.afterId || 0) > 0) {
|
||||
params.push(Math.max(0, Math.trunc(Number(input.afterId))))
|
||||
idFilter = `AND oi.id > $${params.length}`
|
||||
idFilter = `AND ${idColumn} > $${params.length}`
|
||||
}
|
||||
const cutoffCreatedAt = String(input.cutoffCreatedAt || '').trim()
|
||||
let cutoffFilter = ''
|
||||
if (cutoffCreatedAt && Number.isFinite(Date.parse(cutoffCreatedAt))) {
|
||||
params.push(cutoffCreatedAt)
|
||||
cutoffFilter = `AND oi.created_at >= $${params.length}::timestamptz`
|
||||
cutoffFilter = `AND ${scopeAlias}.created_at >= $${params.length}::timestamptz`
|
||||
}
|
||||
const createdAfter = String(input.createdAfter || '').trim()
|
||||
if (createdAfter && Number.isFinite(Date.parse(createdAfter))) {
|
||||
params.push(createdAfter)
|
||||
cutoffFilter += ` AND oi.created_at >= $${params.length}::timestamptz`
|
||||
cutoffFilter += ` AND ${scopeAlias}.created_at >= $${params.length}::timestamptz`
|
||||
}
|
||||
const createdBefore = String(input.createdBefore || '').trim()
|
||||
if (createdBefore && Number.isFinite(Date.parse(createdBefore))) {
|
||||
params.push(createdBefore)
|
||||
cutoffFilter += ` AND oi.created_at < $${params.length}::timestamptz`
|
||||
cutoffFilter += ` AND ${scopeAlias}.created_at < $${params.length}::timestamptz`
|
||||
}
|
||||
const orderDirection = input.orderDirection === 'desc' ? 'DESC' : 'ASC'
|
||||
|
||||
@@ -115,9 +117,7 @@ async function loadCandidateItems(input: {
|
||||
FROM sku_channel_routes route
|
||||
JOIN internal_skus sku ON sku.id = route.internal_sku_id
|
||||
WHERE route.enabled = TRUE
|
||||
AND sku.internal_sku_key = resolve_internal_sku(
|
||||
oi.manual_sku_key, oi.sku_name, oi.sku_code
|
||||
)
|
||||
AND sku.internal_sku_key = oi.internal_sku
|
||||
`
|
||||
const lateralChannelsSql = `
|
||||
JOIN LATERAL (${lateralChannelsSelect}) capability ON jsonb_array_length(capability.channels) > 0
|
||||
@@ -131,13 +131,10 @@ async function loadCandidateItems(input: {
|
||||
? `
|
||||
WITH candidate_items AS (
|
||||
SELECT
|
||||
oi.id,
|
||||
oi.order_id,
|
||||
oi.manual_sku_key,
|
||||
oi.sku_name,
|
||||
oi.sku_code
|
||||
f.order_item_id AS id,
|
||||
f.order_id,
|
||||
f.internal_sku
|
||||
FROM fulfillments f
|
||||
JOIN order_items oi ON oi.id = f.order_item_id
|
||||
JOIN orders o ON o.id = f.order_id
|
||||
WHERE f.status = 'assigned'
|
||||
AND f.channel IN ('affiliate_dash', 'work_order')
|
||||
@@ -196,13 +193,13 @@ async function loadCandidateItems(input: {
|
||||
), '') NOT IN ('USER_APPLY_REFUND', 'affiliate_dash_cancelled')
|
||||
${idFilter}
|
||||
${cutoffFilter}
|
||||
ORDER BY oi.id ${orderDirection}
|
||||
ORDER BY f.order_item_id ${orderDirection}
|
||||
LIMIT $1
|
||||
)
|
||||
SELECT
|
||||
oi.id,
|
||||
oi.order_id,
|
||||
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku,
|
||||
oi.internal_sku,
|
||||
capability.channels
|
||||
FROM candidate_items oi
|
||||
${assignedMissingLateralSql}
|
||||
@@ -212,16 +209,20 @@ async function loadCandidateItems(input: {
|
||||
SELECT
|
||||
oi.id,
|
||||
oi.order_id,
|
||||
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku,
|
||||
oi.internal_sku,
|
||||
capability.channels
|
||||
FROM v_fulfillment_queue oi
|
||||
${lateralChannelsSql}
|
||||
WHERE oi.fulfillment_status = 'pending'
|
||||
AND oi.carrier_queue_candidate = TRUE
|
||||
${
|
||||
input.includeNonActionable
|
||||
? `AND oi.queue_bucket IN ('actionable', 'configuration', 'operator_review')`
|
||||
: `AND oi.queue_bucket = 'actionable'`
|
||||
input.includeNonActionable || input.includeLocked
|
||||
? `AND oi.carrier_queue_candidate = TRUE
|
||||
AND oi.queue_bucket IN (${
|
||||
input.includeNonActionable
|
||||
? `'actionable', 'configuration', 'operator_review'`
|
||||
: `'actionable'`
|
||||
})`
|
||||
: `AND oi.actionable_for_carrier = TRUE`
|
||||
}
|
||||
${input.includeLocked ? '' : 'AND oi.fulfillment_locked = FALSE'}
|
||||
${idFilter}
|
||||
|
||||
@@ -141,8 +141,9 @@ test('新单快速推进只处理 actionable 履约桶', () => {
|
||||
assert.ok(!advance.includes('includeNonActionable'))
|
||||
})
|
||||
|
||||
test('热路径数据库优化迁移 187 与对应仓储查询守卫生效', () => {
|
||||
test('热路径数据库优化迁移 187/188 与对应仓储查询守卫生效', () => {
|
||||
const migration187 = source('../../db/migrations/187_order_site_hotpath_optimization.sql')
|
||||
const migration188 = source('../../db/migrations/188_order_site_worker_fulfillment_hotpaths.sql')
|
||||
const taskRepo = source('../../repositories/task-repo.ts')
|
||||
const affiliateFallback = source('./affiliate-fallback-service.ts')
|
||||
const financeJobs = source('../scheduler/finance-pipeline-jobs.ts')
|
||||
@@ -158,6 +159,12 @@ test('热路径数据库优化迁移 187 与对应仓储查询守卫生效', ()
|
||||
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'))
|
||||
assert.ok(migration188.includes('idx_fulfillments_assigned_carrier_created'))
|
||||
assert.ok(migration188.includes('idx_fulfillments_assigned_manual_created'))
|
||||
assert.ok(migration188.includes('idx_fulfillments_manual_config_order'))
|
||||
assert.ok(migration188.includes('idx_orders_effective_ordered_at_cover'))
|
||||
assert.ok(migration188.includes('work_order_shop_name_projection'))
|
||||
assert.ok(migration188.includes('eligible.queue_bucket ='))
|
||||
|
||||
const jsonLookup = taskRepo.slice(
|
||||
taskRepo.indexOf('async function findExecutorTaskByJsonKeys'),
|
||||
@@ -173,9 +180,24 @@ test('热路径数据库优化迁移 187 与对应仓储查询守卫生效', ()
|
||||
financeJobs.indexOf('export async function runCarrierDispatchJob'),
|
||||
financeJobs.indexOf('export async function runProductNormalizeJob'),
|
||||
)
|
||||
const douyuService = source('../douyu-fulfillment/douyu-fulfillment-service.ts')
|
||||
const douyuMaterializeBody = douyuService.slice(
|
||||
douyuService.indexOf('async function materializeDouyuFulfillmentTasks'),
|
||||
douyuService.indexOf('async function loadPendingDouyuOrderHints'),
|
||||
)
|
||||
const carrierReconciliation = source('./carrier-reconciliation-service.ts')
|
||||
assert.ok(carrierDispatchBody.includes('WITH candidate_page AS'))
|
||||
assert.ok(carrierDispatchBody.includes('scanned_max_id'))
|
||||
assert.ok(carrierDispatchBody.includes('f.created_at'))
|
||||
assert.ok(carrierDispatchBody.includes('f.internal_sku'))
|
||||
assert.ok(!carrierDispatchBody.includes('FROM v_order_item_current oi'))
|
||||
assert.ok(!carrierDispatchBody.includes('FROM manual_fulfillment_configs WHERE enabled'))
|
||||
assert.ok(douyuMaterializeBody.includes('const configIds'))
|
||||
assert.ok(douyuMaterializeBody.includes('CROSS JOIN LATERAL'))
|
||||
assert.ok(douyuMaterializeBody.includes('COALESCE(o.paid_at, o.created_at) DESC'))
|
||||
assert.ok(!douyuMaterializeBody.includes('JOIN manual_fulfillment_configs cfg'))
|
||||
assert.ok(carrierReconciliation.includes('sku.internal_sku_key = oi.internal_sku'))
|
||||
assert.ok(!carrierReconciliation.includes('resolve_internal_sku(\\n oi.manual_sku_key'))
|
||||
assert.ok(
|
||||
!manualConfig
|
||||
.slice(manualConfig.indexOf('export async function rematchManualFulfillments'))
|
||||
@@ -186,8 +208,15 @@ test('热路径数据库优化迁移 187 与对应仓储查询守卫生效', ()
|
||||
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(shopNamesBody.includes('work_order_shop_name_projection'))
|
||||
assert.ok(!shopNamesBody.includes('WITH RECURSIVE distinct_shops AS'))
|
||||
|
||||
const workerVisibleBody = workOrderQueryRepo.slice(
|
||||
workOrderQueryRepo.indexOf('if (workerSharingId) {'),
|
||||
workOrderQueryRepo.indexOf('if (useOperationalStatus)'),
|
||||
)
|
||||
assert.ok(workerVisibleBody.includes('wo.id = ANY(ARRAY('))
|
||||
assert.ok(!workerVisibleBody.includes('worker_visible ON worker_visible.work_order_id'))
|
||||
|
||||
assert.ok(adminNotificationService.includes('pendingNotificationsCache.getOrSet('))
|
||||
assert.ok(adminNotificationService.includes('pendingNotificationsCache.clear()'))
|
||||
|
||||
@@ -55,7 +55,7 @@ test('补载体自动扫描只读取 actionable 队列', () => {
|
||||
assert.ok(
|
||||
queueActiveScopeMigration.includes("WHERE state.fulfillment_status IN ('pending', 'assigned')"),
|
||||
)
|
||||
assert.ok(carrierReconciliation.includes("oi.queue_bucket = 'actionable'"))
|
||||
assert.ok(carrierReconciliation.includes('oi.actionable_for_carrier = TRUE'))
|
||||
assert.ok(carrierReconciliation.includes('oi.carrier_queue_candidate = TRUE'))
|
||||
assert.ok(carrierReconciliation.includes('createdBefore'))
|
||||
assert.ok(carrierReconciliation.includes("orderDirection === 'desc'"))
|
||||
|
||||
@@ -173,12 +173,8 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
? Math.max(0, Math.trunc(Number(config.afterId)))
|
||||
: await readWatermarkItemId('carrier_dispatch')
|
||||
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',
|
||||
)
|
||||
const configKeys = configKeysResult.rows.map((row) => row.sku_key)
|
||||
const manualParams: unknown[] = [limit, cursor, configKeys]
|
||||
const manualCutoff = fulfillmentCreatedAfterSql(manualParams, cutoffCreatedAt)
|
||||
const manualParams: unknown[] = [limit, cursor]
|
||||
const manualCutoff = fulfillmentCreatedAfterSql(manualParams, cutoffCreatedAt, 'f')
|
||||
|
||||
const manual = await query<{
|
||||
id: number
|
||||
@@ -187,21 +183,17 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
config_id: number
|
||||
}>(
|
||||
`
|
||||
SELECT oi.id,
|
||||
oi.order_id,
|
||||
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS sku_key,
|
||||
SELECT f.order_item_id AS id,
|
||||
f.order_id,
|
||||
f.internal_sku AS sku_key,
|
||||
cfg.id AS config_id
|
||||
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
|
||||
)
|
||||
ON cfg.sku_key = f.internal_sku
|
||||
AND cfg.enabled
|
||||
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 f.order_item_id > $2
|
||||
${manualCutoff}
|
||||
ORDER BY f.order_item_id
|
||||
@@ -308,12 +300,12 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
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 params: unknown[] = mode === 'fresh' ? [freshLimit, freshCutoff] : [limit, cursor]
|
||||
const cutoffSql = fulfillmentCreatedAfterSql(params, cutoffCreatedAt, 'f')
|
||||
const scopeSql =
|
||||
mode === 'fresh' ? 'AND oi.created_at >= $2::timestamptz' : 'AND f.order_item_id > $2'
|
||||
const orderSql = mode === 'fresh' ? 'DESC' : 'ASC'
|
||||
mode === 'fresh' ? 'AND f.created_at >= $2::timestamptz' : 'AND f.order_item_id > $2'
|
||||
const orderSql =
|
||||
mode === 'fresh' ? 'f.created_at DESC, f.order_item_id DESC' : 'f.order_item_id ASC'
|
||||
const res = await query<{
|
||||
id: number | null
|
||||
sku_key: string | null
|
||||
@@ -323,16 +315,20 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
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
|
||||
f.internal_sku 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[]))
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM manual_fulfillment_configs cfg
|
||||
WHERE cfg.enabled
|
||||
AND cfg.sku_key = f.internal_sku
|
||||
)
|
||||
${scopeSql}
|
||||
${cutoffSql}
|
||||
ORDER BY f.order_item_id ${orderSql}
|
||||
ORDER BY ${orderSql}
|
||||
LIMIT $1
|
||||
),
|
||||
page_bounds AS (
|
||||
@@ -383,10 +379,11 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
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 cutoffSql = fulfillmentCreatedAfterSql(params, cutoffCreatedAt, 'f')
|
||||
const scopeSql =
|
||||
mode === 'fresh' ? 'AND oi.created_at >= $2::timestamptz' : 'AND f.order_item_id > $2'
|
||||
const orderSql = mode === 'fresh' ? 'DESC' : 'ASC'
|
||||
mode === 'fresh' ? 'AND f.created_at >= $2::timestamptz' : 'AND f.order_item_id > $2'
|
||||
const orderSql =
|
||||
mode === 'fresh' ? 'f.created_at DESC, f.order_item_id DESC' : 'f.order_item_id ASC'
|
||||
const res = await query<{
|
||||
id: number | null
|
||||
sku_key: string | null
|
||||
@@ -396,15 +393,14 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
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
|
||||
f.internal_sku 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}
|
||||
ORDER BY ${orderSql}
|
||||
LIMIT $1
|
||||
),
|
||||
page_bounds AS (
|
||||
@@ -465,10 +461,11 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
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 cutoffSql = fulfillmentCreatedAfterSql(params, cutoffCreatedAt, 'f')
|
||||
const scopeSql =
|
||||
mode === 'fresh' ? 'AND oi.created_at >= $2::timestamptz' : 'AND f.order_item_id > $2'
|
||||
const orderSql = mode === 'fresh' ? 'DESC' : 'ASC'
|
||||
mode === 'fresh' ? 'AND f.created_at >= $2::timestamptz' : 'AND f.order_item_id > $2'
|
||||
const orderSql =
|
||||
mode === 'fresh' ? 'f.created_at DESC, f.order_item_id DESC' : 'f.order_item_id ASC'
|
||||
const res = await query<{
|
||||
id: number | null
|
||||
channel: string | null
|
||||
@@ -482,14 +479,14 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
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
|
||||
f.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}
|
||||
ORDER BY ${orderSql}
|
||||
LIMIT $1
|
||||
),
|
||||
page_bounds AS (
|
||||
@@ -623,35 +620,29 @@ export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||||
async function resolveCarrierDispatchExceptions(cutoffCreatedAt: string): Promise<number> {
|
||||
// 游标会跳过已扫过的订单项;配置是后来补的,这里兜底把配置挂上。
|
||||
const attachParams: unknown[] = []
|
||||
const attachCutoff = fulfillmentCreatedAfterSql(attachParams, cutoffCreatedAt)
|
||||
const attachCutoff = fulfillmentCreatedAfterSql(attachParams, cutoffCreatedAt, 'f')
|
||||
const attachCandidates = await query<{ order_item_id: number; config_id: number }>(
|
||||
`
|
||||
SELECT DISTINCT ON (oi.id)
|
||||
oi.id AS order_item_id,
|
||||
SELECT DISTINCT ON (f.order_item_id)
|
||||
f.order_item_id AS order_item_id,
|
||||
cfg.id AS config_id
|
||||
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
|
||||
)
|
||||
ON cfg.sku_key = f.internal_sku
|
||||
AND cfg.enabled
|
||||
WHERE canonicalize_internal_sku(cfg.sku_key) = resolve_internal_sku(
|
||||
oi.manual_sku_key, oi.sku_name, oi.sku_code
|
||||
)
|
||||
AND f.status = 'assigned'
|
||||
WHERE f.status = 'assigned'
|
||||
AND f.channel = 'manual'
|
||||
AND f.fulfillment_config_id IS NULL
|
||||
AND 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
|
||||
WHERE i.order_item_id = f.order_item_id
|
||||
AND ce.reason = 'manual_config_missing'
|
||||
AND ce.status <> 'resolved'
|
||||
)
|
||||
${attachCutoff}
|
||||
ORDER BY oi.id, cfg.id
|
||||
ORDER BY f.order_item_id, cfg.id
|
||||
LIMIT 500
|
||||
`,
|
||||
attachParams,
|
||||
|
||||
@@ -4,11 +4,9 @@ import { WorkerListCache } from './worker-list-cache.js'
|
||||
/**
|
||||
* 后台工单「店铺」筛选下拉的缓存归属模块。
|
||||
*
|
||||
* 为什么要缓存:这条 SQL 从 orders(约 43 万行)出发做并行全表扫描,再与 work_orders
|
||||
* 做哈希半连接,生产实测单次 1.6 秒、读 22~28 万块(≈200MB 磁盘),而结果只有十几个
|
||||
* 店铺名,且只在「某个店铺第一次产生工单」时才会变。后台工单页每次挂载、每次改单后的
|
||||
* refreshAll 都会重新全表扫一遍,几条并发就能吃掉 4 核里的一到两个核,连接池随即见底
|
||||
* (2026-10-30 18:57 的生产事故就是这么放大的)。
|
||||
* 为什么要缓存:结果只有十几个店铺名,且只在「某个店铺第一次产生工单」时才会变。
|
||||
* 迁移 188 后底层读取窄投影,但后台工单页每次挂载、每次改单后的 refreshAll 仍会重复查询;
|
||||
* 缓存继续合并并发请求并避免无意义往返。
|
||||
*
|
||||
* 为什么单独一个文件:缓存实例要同时被「读」(admin-work-order-query-service)和
|
||||
* 「写」(建单/删单路径主动失效)引用,抽成只依赖 WorkerListCache 的中立模块,
|
||||
|
||||
@@ -1966,7 +1966,7 @@ test('打手订单状态筛选使用个人拼单份额状态', () => {
|
||||
})
|
||||
|
||||
assert.deepEqual(params, [42, ['in_progress', 'pending_acceptance']])
|
||||
assert.match(joins, /work_order_shares share_source/)
|
||||
assert.match(whereClause, /work_order_shares share_source/)
|
||||
// 份额关联改为按工单取一条代表份额,避免多份拼单把列表/统计行放大。
|
||||
assert.match(joins, /LEFT JOIN LATERAL \(/)
|
||||
assert.match(joins, /wos\.worker_id = \$1/)
|
||||
@@ -1999,7 +1999,7 @@ test('工单筛选支持内部寄售来源叠加人员条件,并保持好友
|
||||
acceptanceMode: 'internal_consignment',
|
||||
workerSharingId: 25,
|
||||
})
|
||||
assert.match(workerScopedInternalQuery.joins, /worker_visible\.work_order_id = wo\.id/)
|
||||
assert.match(workerScopedInternalQuery.whereClause, /wo\.id = ANY\(ARRAY\(/)
|
||||
assert.match(
|
||||
workerScopedInternalQuery.whereClause,
|
||||
/wo\.material_json->'consignment'->>'inventoryId' IS NOT NULL/,
|
||||
@@ -3051,13 +3051,10 @@ test('筛选统计必须有短缓存 + 并发合并,避免成本随工单量
|
||||
}
|
||||
})
|
||||
|
||||
test('后台「店铺」筛选下拉必须缓存 + 写路径失效(单次全表扫约 200MB)', async () => {
|
||||
test('后台「店铺」筛选下拉必须缓存 + 写路径失效', async () => {
|
||||
const { readFile } = await import('node:fs/promises')
|
||||
|
||||
// 背景:listWorkOrderShopNames 从 orders(43 万行)做并行全表扫描,再与 work_orders
|
||||
// 做哈希半连接。生产实测单次 1.6 秒、读 22~28 万块(≈200MB),结果却只有十几个店铺名。
|
||||
// 2026-10-30 18:57 的事故里,后台工单页每次挂载、每次改单后的 refreshAll 都重算一遍,
|
||||
// 几条并发就把 4 核打满并拖垮连接池,所以这里必须有缓存 + 主动失效。
|
||||
// 迁移 188 后用窄投影消除大表探测;页面高频刷新仍必须保持缓存和主动失效。
|
||||
const cacheModule = await readFile(
|
||||
new URL('./work-order-shop-options-cache.ts', import.meta.url),
|
||||
'utf8',
|
||||
|
||||
Reference in New Issue
Block a user