refactor(fulfillment): 收敛配置与商品关联写入

This commit is contained in:
yml2213
2026-11-05 21:01:11 +08:00
parent fcd0c137d5
commit b424333a30
15 changed files with 481 additions and 182 deletions
@@ -7,16 +7,22 @@ import { formatShanghaiDate, shiftDate } from '../../utils/finance-date-range.js
import { nowIso } from '../../utils/time.js'
import { rebuildChannelSalesDailyFacts } from '../finance/sales-facts-channel-service.js'
import { AFFILIATE_DASH_PRICES_BASELINE } from './affiliate-dash-prices-baseline.js'
import { attachFulfillmentConfigurations } from '../fulfillment/fulfillment-state-service.js'
/**
* 清理历史上因为把商品中文名误当成 SKU 插入的非标脏商品,并将误关联的订单项重新归一到标准干净商品。
*/
export async function cleanupDirtyAffiliateDashProducts() {
await query(`
const dirtyMappings = await query<{
order_item_id: number
clean_product_id: number
expected_product_id: number
}>(`
WITH dirty_map AS (
SELECT DISTINCT ON (oi.id)
oi.id AS order_item_id,
clean.id AS clean_product_id
clean.id AS clean_product_id,
dirty.id AS expected_product_id
FROM order_items oi
JOIN product_catalog dirty ON dirty.id = oi.canonical_product_id
JOIN fulfillment_tasks ft ON ft.order_item_id = oi.id AND ft.executor_key = 'affiliate_dash'
@@ -27,11 +33,20 @@ export async function cleanupDirtyAffiliateDashProducts() {
WHERE dirty.canonical_sku ~ '^aff:[^a-z0-9_]'
ORDER BY oi.id, ft.id DESC
)
UPDATE order_items oi
SET canonical_product_id = dm.clean_product_id
FROM dirty_map dm
WHERE oi.id = dm.order_item_id
SELECT order_item_id, clean_product_id, expected_product_id
FROM dirty_map
ORDER BY order_item_id
`)
if (dirtyMappings.rows.length > 0) {
await attachFulfillmentConfigurations({
mappings: dirtyMappings.rows.map((row) => ({
orderItemId: Number(row.order_item_id),
canonicalProductId: Number(row.clean_product_id),
expectedCanonicalProductId: Number(row.expected_product_id),
})),
onlyWhenCanonicalProductDifferent: true,
})
}
await query(`
DELETE FROM sales_daily_facts
@@ -134,8 +149,6 @@ export async function syncAdminAffiliateDashProducts() {
type AffiliateSkuBackfillRow = {
affiliate_item_count: number
matched_count: number
updated_count: number
from_date: string | null
to_date: string | null
}
@@ -165,8 +178,11 @@ export async function rebuildFactsForRange(fromDate: string, toDate: string) {
* 不写 channel_product_mappings。多个任务共用同一订单项时取最新 SKU。
*/
export async function backfillAdminAffiliateDashSkus() {
const now = nowIso()
const result = await query<AffiliateSkuBackfillRow>(
const targets = await query<{
id: number
canonical_product_id: number
expected_product_id: number | null
}>(
`
WITH affiliate_item AS (
SELECT DISTINCT ON (ft.order_item_id)
@@ -184,30 +200,37 @@ export async function backfillAdminAffiliateDashSkus() {
ORDER BY ft.order_item_id, ft.created_at DESC, ft.id DESC
),
target AS (
SELECT ai.id, p.id AS canonical_product_id
SELECT
ai.id,
p.id AS canonical_product_id,
oi.canonical_product_id AS expected_product_id
FROM affiliate_item ai
JOIN product_catalog p
ON p.canonical_sku = 'aff:' || ai.sku_code
),
updated AS (
UPDATE order_items oi
SET canonical_product_id = target.canonical_product_id,
updated_at = $1
FROM target
WHERE oi.id = target.id
AND oi.canonical_product_id IS DISTINCT FROM target.canonical_product_id
RETURNING oi.id
JOIN order_items oi ON oi.id = ai.id
)
SELECT id, canonical_product_id, expected_product_id
FROM target
ORDER BY id
`,
)
const result = await query<AffiliateSkuBackfillRow>(
`
WITH affiliate_item AS (
SELECT DISTINCT ON (ft.order_item_id)
ft.order_item_id AS id
FROM fulfillment_tasks ft
WHERE ft.executor_key = 'affiliate_dash'
AND ft.task_status NOT IN ('closed','expired','failed','manual_review','retry_pending','cancelled')
AND ft.created_at >= NOW() - INTERVAL '30 days'
AND btrim(COALESCE(ft.context_json->>'skuCode', '')) <> ''
ORDER BY ft.order_item_id, ft.created_at DESC, ft.id DESC
)
SELECT
(
SELECT COUNT(DISTINCT ft.order_item_id)::int
FROM fulfillment_tasks ft
WHERE ft.executor_key = 'affiliate_dash'
AND ft.task_status NOT IN ('closed','expired','failed','manual_review','retry_pending','cancelled')
AND ft.created_at >= NOW() - INTERVAL '30 days'
SELECT COUNT(*)::int
FROM affiliate_item
) AS affiliate_item_count,
(SELECT COUNT(*)::int FROM target) AS matched_count,
(SELECT COUNT(*)::int FROM updated) AS updated_count,
(
SELECT to_char(
GREATEST(
@@ -230,13 +253,24 @@ export async function backfillAdminAffiliateDashSkus() {
JOIN orders o ON o.id = oi.order_id
) AS to_date
`,
[now],
)
const attached =
targets.rows.length > 0
? await attachFulfillmentConfigurations({
mappings: targets.rows.map((row) => ({
orderItemId: Number(row.id),
canonicalProductId: Number(row.canonical_product_id),
expectedCanonicalProductId:
row.expected_product_id === null ? null : Number(row.expected_product_id),
})),
onlyWhenCanonicalProductDifferent: true,
})
: []
const row = result.rows[0]
const affiliateItemCount = Number(row?.affiliate_item_count || 0)
const matchedCount = Number(row?.matched_count || 0)
const updatedCount = Number(row?.updated_count || 0)
const matchedCount = targets.rows.length
const updatedCount = attached.length
const skippedCount = Math.max(0, matchedCount - updatedCount)
const remainingResult = await query<{ total: number }>(
`
@@ -7,6 +7,7 @@ import { nowIso } from '../../utils/time.js'
import { upsertInternalSkuChannel } from '../fulfillment/internal-sku-channel-service.js'
import { reconcilePendingCarriers } from '../fulfillment/carrier-reconciliation-service.js'
import {
attachFulfillmentConfigurations,
transitionFulfillmentStateBatch,
transitionFulfillmentStateBatchWithExecutor,
} from '../fulfillment/fulfillment-state-service.js'
@@ -827,11 +828,14 @@ export async function rematchManualFulfillments(input: Record<string, unknown> =
const dateFrom = normalizeOptionalDate(input.dateFrom ?? input.date_from, '开始日期')
const dateTo = normalizeOptionalDate(input.dateTo ?? input.date_to, '结束日期')
const now = nowIso()
const result = await query<{ id: number }>(
const candidates = await query<{
order_item_id: number
config_id: number
canonical_product_id: number | null
}>(
`
WITH target AS (
SELECT
SELECT DISTINCT ON (oi.id)
oi.id AS order_item_id,
cfg.id AS config_id,
cfg.canonical_product_id
@@ -853,20 +857,27 @@ 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
)
UPDATE order_items oi
SET fulfillment_config_id = target.config_id,
canonical_product_id = COALESCE(target.canonical_product_id, oi.canonical_product_id),
updated_at = $5
SELECT order_item_id, config_id, canonical_product_id
FROM target
WHERE oi.id = target.order_item_id
RETURNING oi.id
ORDER BY order_item_id
`,
[skuKey, onlyUnmatched, dateFrom, dateTo, now],
[skuKey, onlyUnmatched, dateFrom, dateTo],
)
const attached = await attachFulfillmentConfigurations({
mappings: candidates.rows.map((row) => ({
orderItemId: Number(row.order_item_id),
configId: Number(row.config_id),
...(row.canonical_product_id ? { canonicalProductId: Number(row.canonical_product_id) } : {}),
})),
expected: { status: 'assigned', channel: 'manual' },
onlyWhenConfigNull: onlyUnmatched,
onlyWhenCanonicalProductNull: true,
})
// 配置补上以后,「人工 SKU 未配置」异常要立即收口,不能等人工去点。
const updatedIds = result.rows.map((row) => Number(row.id))
const updatedIds = attached.map((row) => Number(row.id))
if (updatedIds.length > 0) {
await resolveExceptionsForItemsByReason(updatedIds, 'manual_config_missing')
}
@@ -875,7 +886,7 @@ export async function rematchManualFulfillments(input: Record<string, unknown> =
await attachCostVersionsForManualConfigs()
return {
updatedCount: result.rowCount || 0,
updatedCount: attached.length,
skuKey,
dateFrom,
dateTo,
@@ -19,6 +19,7 @@ import { setAdminAffiliateProductPrice } from './affiliate-product-service.js'
import { resolvePriceEffectiveFrom } from './cost-center-normalizers.js'
import { ensureVoucherRuleForSku } from '../fulfillment/channel-assign-service.js'
import { syncCostSnapshotsForItems } from './cost-snapshot-service.js'
import { attachFulfillmentConfigurations } from '../fulfillment/fulfillment-state-service.js'
import {
resolveExceptionsForItemsByReason,
resolveOrphanCostExceptions,
@@ -1375,19 +1376,14 @@ export async function backfillAdminProductMappings(payload: JsonObject = {}) {
}
if (ids.length > 0) {
const updated = await query(
`
UPDATE order_items oi
SET canonical_product_id = input.canonical_product_id,
updated_at = NOW()
FROM unnest($1::bigint[], $2::bigint[])
AS input(id, canonical_product_id)
WHERE oi.id = input.id
AND oi.canonical_product_id IS NULL
`,
[ids, productIds],
)
updatedCount += updated.rowCount || 0
const updated = await attachFulfillmentConfigurations({
mappings: ids.map((orderItemId, index) => ({
orderItemId,
canonicalProductId: productIds[index]!,
})),
onlyWhenCanonicalProductNull: true,
})
updatedCount += updated.length
}
batches += 1
if (!all || itemsResult.rows.length < limit) break
@@ -3,6 +3,7 @@ import { resolveExceptionsForItems, upsertAggregatedException } from './cost-exc
import { readWatermarkItemId } from '../watermark-store.js'
import { upsertInternalSkuChannel } from '../fulfillment/internal-sku-channel-service.js'
import { canonicalizeInternalSku, containsCjk } from '../fulfillment/internal-sku-resolver.js'
import { attachFulfillmentConfigurations } from '../fulfillment/fulfillment-state-service.js'
/**
* 管道 B:商品归一。
@@ -188,10 +189,10 @@ async function ensureVoucherProductForItem(item: ItemRow): Promise<number | null
)
if (current.rows[0]?.status !== 'active') return null
await query(
'UPDATE order_items SET canonical_product_id = $2, updated_at = NOW() WHERE id = $1 AND canonical_product_id IS NULL',
[item.id, productId],
)
await attachFulfillmentConfigurations({
mappings: [{ orderItemId: Number(item.id), canonicalProductId: productId }],
onlyWhenCanonicalProductNull: true,
})
await query(
`
@@ -368,17 +369,15 @@ export async function normalizeOrderItemProducts(
}
if (matched.length > 0) {
await query(
`
UPDATE order_items oi
SET canonical_product_id = input.product_id, updated_at = NOW()
FROM unnest($1::bigint[], $2::bigint[]) AS input(id, product_id)
WHERE oi.id = input.id
AND oi.canonical_product_id IS NULL
`,
[matched.map((row) => row.id), matched.map((row) => row.productId)],
)
await resolveExceptionsForItems(matched.map((row) => row.id))
const attached = await attachFulfillmentConfigurations({
mappings: matched.map((row) => ({
orderItemId: row.id,
canonicalProductId: row.productId,
})),
expected: { status: 'assigned' },
onlyWhenCanonicalProductNull: true,
})
await resolveExceptionsForItems(attached.map((row) => Number(row.id)))
}
}
@@ -508,17 +507,16 @@ export async function normalizeProductsForItems(itemIds: number[]): Promise<{
matched.push({ id: item.id, productId })
}
if (matched.length > 0) {
await query(
`
UPDATE order_items oi
SET canonical_product_id = input.product_id, updated_at = NOW()
FROM unnest($1::bigint[], $2::bigint[]) AS input(id, product_id)
WHERE oi.id = input.id
AND oi.canonical_product_id IS NULL
`,
[matched.map((row) => row.id), matched.map((row) => row.productId)],
)
await resolveExceptionsForItems(matched.map((row) => row.id))
const attached = await attachFulfillmentConfigurations({
mappings: matched.map((row) => ({
orderItemId: row.id,
canonicalProductId: row.productId,
})),
expected: { status: 'assigned' },
onlyWhenCanonicalProductNull: true,
})
await resolveExceptionsForItems(attached.map((row) => Number(row.id)))
return { matched: attached.length, unmatched }
}
return { matched: matched.length, unmatched }
return { matched: 0, unmatched }
}
@@ -22,6 +22,7 @@ import {
buildTemplateProductSku,
inferTemplateUnitName,
} from './work-order-template-product-service.js'
import { attachFulfillmentConfigurations } from '../fulfillment/fulfillment-state-service.js'
export { buildTemplateProductSku, inferTemplateUnitName }
@@ -621,10 +622,10 @@ function compareMappingCandidates(left: TemplateMappingCandidate, right: Templat
async function resetImportedTemplateProductBootstrap(range: { fromDate: string; toDate: string }) {
let resetOrderItemCount = 0
for (let batch = 0; batch < 20; batch += 1) {
const result = await query<{ id: number }>(
const candidates = await query<{ id: number; expected_product_id: number }>(
`
WITH candidates AS (
SELECT oi.id
SELECT oi.id, oi.canonical_product_id AS expected_product_id
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN channel_product_mappings m
@@ -655,17 +656,22 @@ async function resetImportedTemplateProductBootstrap(range: { fromDate: string;
BETWEEN $1::date AND $2::date
LIMIT 20000
)
UPDATE order_items oi
SET canonical_product_id = NULL,
updated_at = NOW()
FROM candidates c
WHERE oi.id = c.id
RETURNING oi.id
SELECT DISTINCT id, expected_product_id
FROM candidates
ORDER BY id
`,
[range.fromDate, range.toDate],
)
resetOrderItemCount += result.rowCount || 0
if ((result.rowCount || 0) < 20000) break
if (candidates.rows.length === 0) break
const reset = await attachFulfillmentConfigurations({
mappings: candidates.rows.map((row) => ({
orderItemId: Number(row.id),
canonicalProductId: null,
expectedCanonicalProductId: Number(row.expected_product_id),
})),
})
resetOrderItemCount += reset.length
if (candidates.rows.length < 20000) break
}
const deleted = await query(
`
@@ -6,6 +6,7 @@ import { resolveFinanceDateRange } from '../../utils/finance-date-range.js'
import { nowIso } from '../../utils/time.js'
import { rebuildFactsForRange } from './affiliate-product-service.js'
import { WORK_ORDER_TEMPLATE_COST_BASELINE } from './cost-center-shared.js'
import { attachFulfillmentConfigurations } from '../fulfillment/fulfillment-state-service.js'
type WorkOrderSkuBackfillRow = {
work_order_item_count: number
@@ -64,12 +65,17 @@ export async function backfillAdminWorkOrderProductSkus(payload: Record<string,
let ruleMatchedCount = 0
let ruleUpdatedCount = 0
for (let batch = 0; batch < 40; batch += 1) {
const targetRows = await query<{ id: number; canonical_product_id: number }>(
const targetRows = await query<{
id: number
canonical_product_id: number
expected_product_id: number | null
}>(
`
WITH work_order_item AS (
SELECT DISTINCT ON (wo.order_item_id)
wo.order_item_id AS id,
wo.product_rule_id
wo.product_rule_id,
oi.canonical_product_id AS expected_product_id
FROM work_orders wo
JOIN order_items oi ON oi.id = wo.order_item_id
JOIN orders o ON o.id = oi.order_id
@@ -81,7 +87,7 @@ export async function backfillAdminWorkOrderProductSkus(payload: Record<string,
ORDER BY wo.order_item_id, wo.id DESC
LIMIT $4
)
SELECT woi.id, p.id AS canonical_product_id
SELECT woi.id, p.id AS canonical_product_id, woi.expected_product_id
FROM work_order_item woi
JOIN work_product_rules wpr ON wpr.id = woi.product_rule_id
JOIN product_catalog p ON p.canonical_sku = 'tpl:' || wpr.rule_key
@@ -95,23 +101,16 @@ export async function backfillAdminWorkOrderProductSkus(payload: Record<string,
lastRuleItemId = lastSelectedId
ruleMatchedCount += targetRows.rows.length
const updated = await query(
`
UPDATE order_items oi
SET canonical_product_id = input.canonical_product_id,
updated_at = $1
FROM unnest($2::bigint[], $3::bigint[])
AS input(id, canonical_product_id)
WHERE oi.id = input.id
AND oi.canonical_product_id IS DISTINCT FROM input.canonical_product_id
`,
[
now,
targetRows.rows.map((row) => Number(row.id)),
targetRows.rows.map((row) => Number(row.canonical_product_id)),
],
)
ruleUpdatedCount += updated.rowCount || 0
const updated = await attachFulfillmentConfigurations({
mappings: targetRows.rows.map((row) => ({
orderItemId: Number(row.id),
canonicalProductId: Number(row.canonical_product_id),
expectedCanonicalProductId:
row.expected_product_id === null ? null : Number(row.expected_product_id),
})),
onlyWhenCanonicalProductDifferent: true,
})
ruleUpdatedCount += updated.length
if (targetRows.rows.length < WORK_ORDER_BACKFILL_BATCH_SIZE) break
}
@@ -249,23 +248,14 @@ export async function backfillAdminWorkOrderProductSkus(payload: Record<string,
if (lastSelectedId <= lastTailItemId) break
lastTailItemId = lastSelectedId
const updated = await query(
`
UPDATE order_items oi
SET canonical_product_id = input.canonical_product_id,
updated_at = $1
FROM unnest($2::bigint[], $3::bigint[])
AS input(id, canonical_product_id)
WHERE oi.id = input.id
AND oi.canonical_product_id IS NULL
`,
[
now,
tailRows.rows.map((row) => Number(row.id)),
tailRows.rows.map((row) => Number(row.canonical_product_id)),
],
)
tailUpdatedCount += updated.rowCount || 0
const updated = await attachFulfillmentConfigurations({
mappings: tailRows.rows.map((row) => ({
orderItemId: Number(row.id),
canonicalProductId: Number(row.canonical_product_id),
})),
onlyWhenCanonicalProductNull: true,
})
tailUpdatedCount += updated.length
if (tailRows.rows.length < WORK_ORDER_BACKFILL_BATCH_SIZE) break
}