Files
order_site/apps/backend/src/services/cost-center/manual-fulfillment-config-service.ts
T

1380 lines
47 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { PoolClient } from 'pg'
import { query, withTransaction } from '../../db/client.js'
import { resolveExceptionsForItemsByReason } from './cost-exception-service.js'
import type { JsonObject } from '../../types/json.js'
import { createHttpError } from '../../utils/http.js'
import { formatShanghaiDate, shiftDate } from '../../utils/finance-date-range.js'
import { nowIso } from '../../utils/time.js'
import {
upsertInternalSkuChannel,
upsertInternalSkuChannelWithClient,
} 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'
import { canonicalizeInternalSku, containsCjk } from '../fulfillment/internal-sku-resolver.js'
import { refreshFactsForDates } from '../finance/refresh-facts.js'
import {
calculateManualCostFen,
normalizeManualCreditQuantity,
parseManualChannelQuantity,
} from './manual-credit-quantity.js'
import { productSourceFilterSql } from './cost-center-mappers.js'
/**
* 人工履约 SKU 配置服务。
*
* 口径(2026-10-24 确认):
* * 配置主键优先取内部 SKU(快手 spec_json.skuNick / 拼多多 spec_json.outSkuSn),
* 缺失时按 sku_code → sku_name 兜底;同名/同码算同一个商品,跨渠道共用一份配置;
* * 配置项:履约渠道(南航/乐玩/ROCK/备用金现金/统一结算)+ 消耗量 + 成本模式;
* * 换算率固定:1 积分 = 1 分钱;
* * 消耗积分 0 = 成本不固定,由客服在确认履约时手填实际成本;
* * 「重新匹配」= 把配置回填到历史人工订单项,幂等可反复执行。
*
* 没有匹配引擎、没有打分:这就是一张带统计的 SKU 配置清单。
*/
export const MANUAL_PLATFORM_KEYS = ['nanhang', 'lewan', 'rock', 'fund_cash', 'on_account'] as const
export type ManualPlatformKey = (typeof MANUAL_PLATFORM_KEYS)[number]
/**
* 积分换算率(分/积分),**按平台不同**:
* 南航 1 积分 = 1 分;乐玩 1 积分 = 1 分;ROCK 1 积分 = 1 元(100 分)。
* 备用金现金不涉及积分,换算率恒为 100(1 元 = 100 分)。
*
* 真源是 fulfillment_profiles.config_json.rechargeUnitPriceFen,
* 这里只是平台档案缺失时的兜底默认值。
*/
export const DEFAULT_CREDIT_UNIT_PRICE_FEN = 1
/** 平台 → 默认换算率(分/积分)。 */
const PLATFORM_UNIT_PRICE_FEN: Record<ManualPlatformKey, number> = {
nanhang: 1,
lewan: 1,
rock: 100,
fund_cash: 100,
on_account: 100,
}
const PLATFORM_LABELS: Record<ManualPlatformKey, string> = {
nanhang: '南航平台',
lewan: '乐玩后台',
rock: 'ROCK 后台',
fund_cash: '备用金现金',
on_account: '统一结算',
}
/** 读取平台档案里配置的换算率;档案不存在时用默认表。 */
async function loadPlatformUnitPriceFen(): Promise<Record<ManualPlatformKey, number>> {
const result = await query<{ profile_key: string; config_json: Record<string, unknown> }>(
`SELECT profile_key, config_json FROM fulfillment_profiles WHERE profile_key LIKE 'manual_%'`,
)
const prices: Record<ManualPlatformKey, number> = { ...PLATFORM_UNIT_PRICE_FEN }
for (const row of result.rows) {
const raw = Number(row.config_json?.rechargeUnitPriceFen)
const key = row.profile_key.replace(/^manual_/, '') as ManualPlatformKey
if (key in prices && Number.isInteger(raw) && raw > 0) {
prices[key] = raw
}
}
return prices
}
type ScanOptions = {
fromDate: string
toDate: string
}
type ManualSkuRow = {
id: number
sku_key: string
display_name: string
shop_count: number
order_count: number
item_count: number
revenue_fen: number
first_seen_date: string | null
last_seen_date: string | null
scan_from_date: string | null
scan_to_date: string | null
config_id: number | null
config_platform_key: string | null
config_credit_quantity: number | string | null
config_cost_mode: string | null
config_canonical_product_id: number | null
config_enabled: boolean | null
config_channels_json: unknown
}
type ManualChannelConfig = {
platformKey: ManualPlatformKey
creditQuantity: number
costMode: 'fixed' | 'variable'
enabled: boolean
}
/**
* 扫描「走到人工履约」的内部 SKU,登记到 manual_sku_registry。
*
* 幂等:重复扫描按 sku_key 覆盖统计,不产生重复行。
* 已有配置的 SKU 不受影响(配置存在 manual_fulfillment_configs 里)。
*/
export async function scanManualSkus(options: ScanOptions) {
const fromDate = normalizeDate(options.fromDate, '开始日期')
const toDate = normalizeDate(options.toDate, '结束日期')
if (fromDate > toDate) {
throw createHttpError('开始日期不能晚于结束日期', {
statusCode: 400,
errorCode: 'manual_sku_scan_range_invalid',
})
}
const unitPrices = await loadPlatformUnitPriceFen()
const now = nowIso()
const result = await query<{
sku_key: string
display_name: string
shop_count: number
order_count: number
item_count: number
revenue_fen: number
first_seen_date: string
last_seen_date: string
}>(
`
WITH scoped AS (
SELECT
oi.id AS order_item_id,
oi.order_id,
o.shop_id,
oi.sku_name,
COALESCE(oi.revenue_amount_fen, 0)::bigint AS revenue_fen,
(COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date AS stat_date,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS sku_key
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE oi.fulfillment_status = 'assigned' AND oi.fulfillment_channel = 'manual'
AND (COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date
BETWEEN $1::date AND $2::date
),
keyed AS (
SELECT * FROM scoped WHERE sku_key IS NOT NULL AND sku_key <> ''
)
SELECT
sku_key,
MAX(sku_name) AS display_name,
COUNT(DISTINCT shop_id)::int AS shop_count,
COUNT(DISTINCT order_id)::int AS order_count,
COUNT(*)::int AS item_count,
SUM(revenue_fen)::bigint AS revenue_fen,
MIN(stat_date) AS first_seen_date,
MAX(stat_date) AS last_seen_date
FROM keyed
GROUP BY sku_key
`,
[fromDate, toDate],
)
const rows = result.rows
if (rows.length === 0) {
return { scanned: 0, registered: 0, fromDate, toDate }
}
await withTransaction(async (client) => {
for (const row of rows) {
await client.query(
`
INSERT INTO manual_sku_registry (
sku_key, display_name, shop_count, order_count, item_count, revenue_fen,
first_seen_date, last_seen_date, scan_from_date, scan_to_date,
created_at, updated_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7::date, $8::date, $9::date, $10::date, $11, $11
)
ON CONFLICT (sku_key) DO UPDATE
SET display_name = EXCLUDED.display_name,
shop_count = EXCLUDED.shop_count,
order_count = EXCLUDED.order_count,
item_count = EXCLUDED.item_count,
revenue_fen = EXCLUDED.revenue_fen,
first_seen_date = LEAST(
COALESCE(manual_sku_registry.first_seen_date, EXCLUDED.first_seen_date),
EXCLUDED.first_seen_date
),
last_seen_date = GREATEST(
COALESCE(manual_sku_registry.last_seen_date, EXCLUDED.last_seen_date),
EXCLUDED.last_seen_date
),
scan_from_date = EXCLUDED.scan_from_date,
scan_to_date = EXCLUDED.scan_to_date,
updated_at = EXCLUDED.updated_at
`,
[
row.sku_key,
row.display_name || '',
row.shop_count,
row.order_count,
row.item_count,
row.revenue_fen,
row.first_seen_date,
row.last_seen_date,
fromDate,
toDate,
now,
],
)
}
})
return { scanned: rows.length, registered: rows.length, fromDate, toDate }
}
/** 列出人工标准商品清单(标准商品为唯一主键,配置与订单统计只做关联)。 */
export async function listManualSkus(input: Record<string, unknown> = {}) {
const unitPrices = await loadPlatformUnitPriceFen()
const page = normalizePositiveInteger(input.page, 1, '页码')
const pageSize = Math.min(
200,
normalizePositiveInteger(input.pageSize ?? input.page_size, 20, '每页数量'),
)
const keyword = String(input.keyword || input.q || '').trim()
const status = String(input.status || '').trim()
const platformKey = String(input.platformKey || input.platform_key || '').trim()
const provider = String(input.provider || '').trim()
const conditions: string[] = [`p.status = 'active'`, `p.canonical_sku LIKE 'man:%'`]
const params: unknown[] = ['manual']
conditions.push(productSourceFilterSql(params.length))
if (keyword) {
params.push(`%${escapeLike(keyword)}%`)
const placeholder = `$${params.length}`
conditions.push(
`(p.canonical_sku ILIKE ${placeholder} OR p.canonical_name ILIKE ${placeholder})`,
)
}
if (status === 'configured') {
conditions.push('cfg.id IS NOT NULL')
} else if (status === 'unconfigured') {
conditions.push('cfg.id IS NULL')
}
if (platformKey) {
params.push(platformKey)
conditions.push(`(
cfg.platform_key = $${params.length}
OR cfg.channels_json @> jsonb_build_array(jsonb_build_object('platformKey', $${params.length}))
)`)
}
if (provider) {
params.push(provider)
conditions.push(`EXISTS (
SELECT 1 FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE oi.fulfillment_status = 'assigned' AND oi.fulfillment_channel = 'manual'
AND o.provider = $${params.length}
AND resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code)
= canonicalize_internal_sku(substring(p.canonical_sku from 5))
)`)
}
const where = conditions.join(' AND ')
const countResult = await query<{ total: number }>(
`
SELECT COUNT(*)::int AS total
FROM product_catalog p
LEFT JOIN LATERAL (
SELECT *
FROM manual_fulfillment_configs cfg
WHERE canonicalize_internal_sku(cfg.sku_key)
= canonicalize_internal_sku(substring(p.canonical_sku from 5))
ORDER BY cfg.id
LIMIT 1
) cfg ON TRUE
WHERE ${where}
`,
params,
)
const listParams = [...params, pageSize, (page - 1) * pageSize]
const result = await query<ManualSkuRow>(
`
WITH manual_stats AS (
SELECT
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS sku_key,
COUNT(DISTINCT o.shop_id)::int AS shop_count,
COUNT(DISTINCT o.id)::int AS order_count,
COUNT(*)::int AS item_count,
COALESCE(SUM(GREATEST(COALESCE(oi.revenue_amount_fen, 0), 0)), 0)::bigint
AS revenue_fen,
MIN((COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date)
AS first_seen_date,
MAX((COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date)
AS last_seen_date
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
GROUP BY 1
)
SELECT
p.id,
substring(p.canonical_sku from 5) AS sku_key,
p.canonical_name AS display_name,
COALESCE(manual_stats.shop_count, 0)::int AS shop_count,
COALESCE(manual_stats.order_count, 0)::int AS order_count,
COALESCE(manual_stats.item_count, 0)::int AS item_count,
COALESCE(manual_stats.revenue_fen, 0)::bigint AS revenue_fen,
manual_stats.first_seen_date,
manual_stats.last_seen_date,
manual_stats.first_seen_date AS scan_from_date,
manual_stats.last_seen_date AS scan_to_date,
cfg.id AS config_id,
cfg.platform_key AS config_platform_key,
cfg.credit_quantity AS config_credit_quantity,
cfg.cost_mode AS config_cost_mode,
COALESCE(cfg.canonical_product_id, p.id) AS config_canonical_product_id,
cfg.enabled AS config_enabled,
cfg.channels_json AS config_channels_json
FROM product_catalog p
LEFT JOIN LATERAL (
SELECT *
FROM manual_fulfillment_configs cfg
WHERE canonicalize_internal_sku(cfg.sku_key)
= canonicalize_internal_sku(substring(p.canonical_sku from 5))
ORDER BY cfg.id
LIMIT 1
) cfg ON TRUE
LEFT JOIN manual_stats
ON manual_stats.sku_key = canonicalize_internal_sku(substring(p.canonical_sku from 5))
WHERE ${where}
ORDER BY COALESCE(manual_stats.item_count, 0) DESC, p.canonical_name ASC, p.id ASC
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}
`,
listParams,
)
return {
items: result.rows.map((row) => mapManualSku(row, unitPrices)),
pagination: { page, pageSize, total: Number(countResult.rows[0]?.total || 0) },
}
}
/** 清单总览:已配置 / 未配置 / 覆盖单量。 */
export async function getManualSkuOverview() {
const result = await query<{
total_sku: number
configured_sku: number
unconfigured_sku: number
total_items: number
configured_items: number
unconfigured_items: number
last_scan_at: string | null
}>(
`
WITH manual_stats AS (
SELECT
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS sku_key,
COUNT(*)::int AS item_count,
MAX((COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date)
AS last_seen_date
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
GROUP BY 1
),
manual_scope AS (
SELECT p.id, p.canonical_sku, p.canonical_name, cfg.id AS config_id
FROM product_catalog p
LEFT JOIN LATERAL (
SELECT cfg.id
FROM manual_fulfillment_configs cfg
WHERE canonicalize_internal_sku(cfg.sku_key)
= canonicalize_internal_sku(substring(p.canonical_sku from 5))
ORDER BY cfg.id
LIMIT 1
) cfg ON TRUE
WHERE p.status = 'active'
AND p.canonical_sku LIKE 'man:%'
AND ${productSourceFilterSql(1)}
)
SELECT
COUNT(*)::int AS total_sku,
COUNT(*) FILTER (WHERE config_id IS NOT NULL)::int AS configured_sku,
COUNT(*) FILTER (WHERE config_id IS NULL)::int AS unconfigured_sku,
COALESCE(SUM(manual_stats.item_count), 0)::bigint AS total_items,
COALESCE(SUM(manual_stats.item_count) FILTER (WHERE config_id IS NOT NULL), 0)::bigint
AS configured_items,
COALESCE(SUM(manual_stats.item_count) FILTER (WHERE config_id IS NULL), 0)::bigint
AS unconfigured_items,
MAX(manual_stats.last_seen_date)::text AS last_scan_at
FROM manual_scope
LEFT JOIN manual_stats
ON manual_stats.sku_key = canonicalize_internal_sku(
substring(manual_scope.canonical_sku from 5)
)
`,
['manual'],
)
const row = result.rows[0]
return {
totalSku: Number(row?.total_sku || 0),
configuredSku: Number(row?.configured_sku || 0),
unconfiguredSku: Number(row?.unconfigured_sku || 0),
totalItems: Number(row?.total_items || 0),
configuredItems: Number(row?.configured_items || 0),
unconfiguredItems: Number(row?.unconfigured_items || 0),
lastScanAt: row?.last_scan_at || null,
}
}
/** 保存(新增或更新)一个人工 SKU 的履约配置。 */
export async function saveManualFulfillmentConfig(payload: JsonObject) {
const skuKey = canonicalizeInternalSku(payload.skuKey ?? payload.sku_key)
if (!skuKey || !containsCjk(skuKey)) {
throw createHttpError('必须使用包含中文的内部 SKU', {
statusCode: 400,
errorCode: 'manual_config_sku_key_required',
})
}
const channels = normalizeManualChannels(payload)
const primaryChannel = channels[0]!
const platformKey = primaryChannel.platformKey
const creditQuantity = primaryChannel.creditQuantity
const canonicalProductId = normalizeOptionalId(
payload.canonicalProductId ?? payload.canonical_product_id,
)
const enabled = payload.enabled === false ? false : true
const note = optionalText(payload.note, 300)
// 消耗积分为 0 = 成本不固定,客服确认履约时手填。
const costMode = primaryChannel.costMode
const unitPrices = await loadPlatformUnitPriceFen()
const now = nowIso()
const config = await withTransaction(async (client) => {
const existing = await client.query<{ id: number }>(
`SELECT id FROM manual_fulfillment_configs
WHERE canonicalize_internal_sku(sku_key) = $1
ORDER BY id
LIMIT 1
FOR UPDATE`,
[skuKey],
)
const existingId = Number(existing.rows[0]?.id || 0)
let resolvedProductId = canonicalProductId
if (resolvedProductId) {
const product = await client.query<{ canonical_sku: string; status: string }>(
`SELECT canonical_sku, status
FROM product_catalog
WHERE id = $1
LIMIT 1`,
[resolvedProductId],
)
if (
!product.rows[0] ||
product.rows[0].status !== 'active' ||
!String(product.rows[0].canonical_sku || '').startsWith('man:')
) {
throw createHttpError('人工履约配置只能关联有效的 man: 标准商品', {
statusCode: 400,
errorCode: 'manual_config_product_source_invalid',
})
}
}
// 人工配置本身就是该 SKU 的标准商品声明。没有显式关联时自动创建/复用
// man:<内部 SKU>,避免运营再去「标准商品」手工建一次。
if (!resolvedProductId) {
const registry = await client.query<{ display_name: string }>(
`SELECT display_name FROM manual_sku_registry
WHERE canonicalize_internal_sku(sku_key) = $1
LIMIT 1`,
[skuKey],
)
const canonicalSku = `man:${skuKey}`
if (canonicalSku.length > 64) {
throw createHttpError('内部 SKU 过长,无法生成标准商品编码', {
statusCode: 400,
errorCode: 'manual_product_sku_too_long',
})
}
const canonicalName =
String(registry.rows[0]?.display_name || skuKey)
.trim()
.slice(0, 120) || skuKey.slice(0, 120)
const product = await client.query<{ id: number }>(
`INSERT INTO product_catalog (
canonical_sku, canonical_name, category, unit_name, status,
attributes_json, created_at, updated_at
) VALUES (
$1, $2, '人工', '件', 'active',
'{"source":"manual_config","auto_created":true}'::jsonb, $3, $3
)
ON CONFLICT (canonical_sku) DO UPDATE SET
status = 'active',
canonical_name = CASE
WHEN BTRIM(product_catalog.canonical_name) = '' THEN EXCLUDED.canonical_name
ELSE product_catalog.canonical_name
END,
updated_at = EXCLUDED.updated_at
RETURNING id`,
[canonicalSku, canonicalName, now],
)
resolvedProductId = Number(product.rows[0]?.id || 0) || null
}
const result = existingId
? await client.query(
`UPDATE manual_fulfillment_configs
SET sku_key = $2, canonical_product_id = $3, platform_key = $4,
credit_quantity = $5, cost_mode = $6, enabled = $7, note = $8,
channels_json = $9::jsonb, updated_at = $10
WHERE id = $1
RETURNING *`,
[
existingId,
skuKey,
resolvedProductId,
platformKey,
creditQuantity,
costMode,
enabled,
note,
JSON.stringify(channels),
now,
],
)
: await client.query(
`INSERT INTO manual_fulfillment_configs (
sku_key, canonical_product_id, platform_key, credit_quantity,
cost_mode, enabled, note, channels_json, created_at, updated_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9, $9)
RETURNING *`,
[
skuKey,
resolvedProductId,
platformKey,
creditQuantity,
costMode,
enabled,
note,
JSON.stringify(channels),
now,
],
)
const saved = requiredRow(result.rows[0], '保存人工履约配置失败')
await syncRegistryConfigId(saved.sku_key, saved.id, client)
await upsertManualRegistryConfig(saved, client)
// 标准商品、人工配置和渠道规则必须一起提交,避免保存成功后仍未生效。
await syncManualChannelRule(saved, client)
return saved
})
// 配置补全后,失败的 pending 会因 locked=true 无法被定时任务重试,这里主动解锁并重试。
const pendingAssigned = await retryPendingManualItems(config.sku_key)
// 配置保存后立刻回填该 SKU 最近 30 天的订单项,避免必须再点一次「重新匹配」。
// 历史更早的订单项不自动回填(历史人工成本不补录);需要时再显式点「重新匹配」。
const today = formatShanghaiDate(new Date())
const rematched = await rematchManualFulfillments({
skuKey: config.sku_key,
onlyUnmatched: true,
dateFrom: shiftDate(today, -29),
dateTo: today,
})
return {
...mapManualConfig(config, unitPrices),
syncSummary: {
canonicalProductId: config.canonical_product_id ? Number(config.canonical_product_id) : null,
pendingAssigned,
rematchedItems: rematched.updatedCount,
},
}
}
async function retryPendingManualItems(skuKey: string): Promise<number> {
const key = canonicalizeInternalSku(skuKey)
if (!key) return 0
const candidates = await query<{ id: number }>(
`SELECT oi.id
FROM order_items oi
WHERE oi.fulfillment_status = 'pending'
AND resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) = $1
ORDER BY oi.id
LIMIT 500`,
[key],
)
const ids = candidates.rows.map((row) => Number(row.id))
if (ids.length === 0) return 0
await transitionFulfillmentStateBatch({
orderItemIds: ids,
expected: { status: 'pending', locked: true },
patch: { locked: false },
eventType: 'manual_config_retry_unlocked',
actor: { type: 'system' },
})
const result = await reconcilePendingCarriers({
orderItemIds: ids,
limit: ids.length,
allowFallback: true,
})
return result.fallbacksSelected
}
/** 删除一份人工履约配置(SKU 回到未配置状态)。 */
export async function deleteManualFulfillmentConfig(skuKey: string) {
const key = canonicalizeInternalSku(skuKey)
if (!key) {
throw createHttpError('内部 SKU 不能为空', {
statusCode: 400,
errorCode: 'manual_config_sku_key_required',
})
}
const deleted = await query(
`DELETE FROM manual_fulfillment_configs
WHERE canonicalize_internal_sku(sku_key) = $1
RETURNING id`,
[key],
)
await upsertInternalSkuChannel({
internalSku: key,
channel: 'manual',
priority: 90,
isFallback: true,
enabled: false,
source: 'manual_config',
configJson: { manualConfigId: null },
})
await syncRegistryConfigId(key, null)
return { skuKey: key, deleted: deleted.rowCount || 0 }
}
export type DeleteManualSkuResult = {
skuKey: string
affectedItems: number
deletedConfigs: number
deletedRegistry: number
deletedRules: number
archivedProducts: number
refreshedDays: number
skippedClosedDays: number
}
/**
* 移除人工分类(含未配置项):删除派生登记、配置和人工规则,
* 并把当前仍落在 manual 的关联订单项退回待分类,等待重新走正确渠道。
* 原始订单与订单项不会删除。
*/
export async function deleteManualSkuClassification(
skuKey: string,
): Promise<DeleteManualSkuResult> {
const key = canonicalizeInternalSku(skuKey)
if (!key) {
throw createHttpError('内部 SKU 不能为空', {
statusCode: 400,
errorCode: 'manual_config_sku_key_required',
})
}
const result = await withTransaction(async (client) => {
const items = await client.query<{ id: number; basis_date: string }>(
`
SELECT
oi.id,
(COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date::text
AS basis_date
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
AND resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) = $1
ORDER BY oi.id
FOR UPDATE OF oi
`,
[key],
)
const itemIds = items.rows.map((row) => Number(row.id))
const periodKeys = [
...new Set(items.rows.map((row) => String(row.basis_date || '').slice(0, 7)).filter(Boolean)),
]
if (periodKeys.length > 0) {
const closedPeriods = await client.query<{ period_key: string }>(
`
SELECT period_key
FROM finance_periods
WHERE status = 'closed' AND period_key = ANY($1::text[])
ORDER BY period_key
`,
[periodKeys],
)
if (closedPeriods.rows.length > 0) {
throw createHttpError(
`包含已关账期间(${closedPeriods.rows.map((row) => row.period_key).join('、')}),不能删除人工分类`,
{
statusCode: 409,
errorCode: 'finance_period_closed',
},
)
}
}
if (itemIds.length > 0) {
await client.query(`DELETE FROM cost_snapshots WHERE order_item_id = ANY($1::bigint[])`, [
itemIds,
])
const removedLinks = await client.query<{ exception_id: number }>(
`
DELETE FROM cost_exception_items
WHERE order_item_id = ANY($1::bigint[])
RETURNING exception_id
`,
[itemIds],
)
const exceptionIds = [
...new Set(removedLinks.rows.map((row) => Number(row.exception_id)).filter(Boolean)),
]
await client.query(
`
UPDATE cost_exceptions ce
SET status = 'resolved',
resolved_at = NOW(),
item_count = 0,
last_seen_at = NOW()
WHERE (
ce.order_item_id = ANY($1::bigint[])
OR ce.id = ANY($2::bigint[])
)
AND ce.status <> 'resolved'
AND NOT EXISTS (
SELECT 1 FROM cost_exception_items i WHERE i.exception_id = ce.id
)
`,
[itemIds, exceptionIds],
)
}
const configs = await client.query(
`DELETE FROM manual_fulfillment_configs
WHERE canonicalize_internal_sku(sku_key) = $1
RETURNING id`,
[key],
)
const registry = await client.query(
`DELETE FROM manual_sku_registry
WHERE canonicalize_internal_sku(sku_key) = $1
RETURNING id`,
[key],
)
const rules = await client.query(
`DELETE FROM internal_sku_channels
WHERE canonicalize_internal_sku(internal_sku) = $1 AND channel = 'manual'
RETURNING id`,
[key],
)
const products = await client.query(
`
UPDATE product_catalog
SET status = 'archived',
attributes_json = attributes_json || jsonb_build_object(
'deletedAt', $2::text,
'deletedBy', 'manual_sku_config'
),
updated_at = $2::timestamptz
WHERE status = 'active'
AND canonical_sku LIKE 'man:%'
AND canonicalize_internal_sku(substring(canonical_sku from 5)) = $1
RETURNING id
`,
[key, nowIso()],
)
if (itemIds.length > 0) {
await transitionFulfillmentStateBatchWithExecutor(client, {
orderItemIds: itemIds,
expected: { status: 'assigned', channel: 'manual' },
patch: {
status: 'pending',
channel: null,
source: '',
locked: false,
configId: null,
pendingReason: 'no_channel_capability',
pendingDetail: {
reason: 'manual_classification_removed',
removedAt: nowIso(),
},
reason: '运营移除错误的人工分类',
decidedBy: null,
decidedAt: null,
},
eventType: 'manual_classification_removed',
actor: { type: 'operator' },
reason: key,
})
}
return {
affectedItems: itemIds.length,
deletedConfigs: configs.rowCount || 0,
deletedRegistry: registry.rowCount || 0,
deletedRules: rules.rowCount || 0,
archivedProducts: products.rowCount || 0,
dates: [...new Set(items.rows.map((row) => row.basis_date).filter(Boolean))],
}
})
const refreshed = await refreshFactsForDates(result.dates)
return {
skuKey: key,
affectedItems: result.affectedItems,
deletedConfigs: result.deletedConfigs,
deletedRegistry: result.deletedRegistry,
deletedRules: result.deletedRules,
archivedProducts: result.archivedProducts,
refreshedDays: refreshed.days,
skippedClosedDays: refreshed.skippedClosed,
}
}
/**
* 重新匹配:把已配置项回填到历史人工订单项。
*
* 幂等:只填空值,已回填的不动。
*/
export async function rematchManualFulfillments(input: Record<string, unknown> = {}) {
const skuKey = String(input.skuKey ?? input.sku_key ?? '').trim()
const onlyUnmatched = input.onlyUnmatched !== false
// 定时任务只回填最近窗口,避免一次性把 10 万历史人工单变成「待履约」。
const dateFrom = normalizeOptionalDate(input.dateFrom ?? input.date_from, '开始日期')
const dateTo = normalizeOptionalDate(input.dateTo ?? input.date_to, '结束日期')
const candidates = await query<{
order_item_id: number
config_id: number
canonical_product_id: number | null
}>(
`
WITH target AS (
SELECT DISTINCT ON (oi.id)
oi.id AS order_item_id,
cfg.id AS config_id,
cfg.canonical_product_id
FROM order_items oi
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'
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 (
$3::date IS NULL
OR (COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date >= $3::date
)
AND (
$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
)
SELECT order_item_id, config_id, canonical_product_id
FROM target
ORDER BY order_item_id
`,
[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 = attached.map((row) => Number(row.id))
if (updatedIds.length > 0) {
await resolveExceptionsForItemsByReason(updatedIds, 'manual_config_missing')
}
// 配置生效后,把 SKU 对应的成本版本挂上(若已配置商品)。
await attachCostVersionsForManualConfigs()
return {
updatedCount: attached.length,
skuKey,
dateFrom,
dateTo,
}
}
/**
* 为已配置的人工 SKU 生成/刷新固定成本版本(按各平台积分换算率折算)。
*
* 成本版本是「成本金额」的唯一真源;积分消耗量记在配置里,
* 两者按固定换算率保持一致。
*/
async function attachCostVersionsForManualConfigs() {
const costItemResult = await query<{ id: number }>(
`SELECT id FROM cost_items WHERE code = 'sys_manual_service' AND status = 'active' LIMIT 1`,
)
const costItemId = Number(costItemResult.rows[0]?.id || 0)
if (!costItemId) return
await query(
`
INSERT INTO cost_versions (
cost_item_id, scope_type, provider, shop_id, canonical_product_id,
work_product_rule_id, amount_fen, rate_bps, effective_from, source,
status, change_reason, created_at, updated_at
)
SELECT
$1, 'product', '', '', cfg.canonical_product_id, NULL,
ROUND(cfg.credit_quantity * (fp.config_json->>'rechargeUnitPriceFen')::bigint, 0)::bigint,
0, '1970-01-01T00:00:00+08:00', 'manual', 'active',
'人工履约配置:积分按平台换算率折算',
NOW(), NOW()
FROM manual_fulfillment_configs cfg
JOIN fulfillment_profiles fp
ON fp.profile_key = 'manual_' || cfg.platform_key
WHERE cfg.enabled = TRUE
AND cfg.credit_quantity > 0
AND cfg.canonical_product_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM cost_versions v
WHERE v.cost_item_id = $1
AND v.scope_type = 'product'
AND v.canonical_product_id = cfg.canonical_product_id
AND v.status = 'active'
)
`,
[costItemId],
)
}
/** 配置保存/删除后同步登记表上的 config_id。 */
async function syncRegistryConfigId(skuKey: string, configId: number | null, client?: PoolClient) {
const sql = `
UPDATE manual_sku_registry
SET config_id = $2, updated_at = $3
WHERE canonicalize_internal_sku(sku_key) = $1
`
const params = [canonicalizeInternalSku(skuKey), configId, nowIso()]
if (client) {
await client.query(sql, params)
return
}
await query(sql, params)
}
/** 配置保存后确保登记表仍有同一 SKU 的记录,兼容旧扫描清单和运维查询。 */
async function upsertManualRegistryConfig(
config: {
id: number
sku_key: string
canonical_product_id: number | null
},
client?: PoolClient,
) {
const key = canonicalizeInternalSku(config.sku_key)
if (!key) return
const now = nowIso()
const sql = `
INSERT INTO manual_sku_registry (
sku_key, display_name, config_id, created_at, updated_at
)
SELECT
$1,
COALESCE(NULLIF(product.canonical_name, ''), $1),
$2,
$3,
$3
FROM (SELECT 1) seed
LEFT JOIN product_catalog product ON product.id = $4
ON CONFLICT (sku_key) DO UPDATE SET
display_name = CASE
WHEN BTRIM(manual_sku_registry.display_name) = '' THEN EXCLUDED.display_name
ELSE manual_sku_registry.display_name
END,
config_id = EXCLUDED.config_id,
updated_at = EXCLUDED.updated_at
`
const params = [key, config.id, now, config.canonical_product_id]
if (client) {
await client.query(sql, params)
return
}
await query(sql, params)
}
/** 读取单个 SKU 的配置详情(含平台标签与成本折算)。 */
export async function getManualFulfillmentConfig(skuKey: string) {
const unitPrices = await loadPlatformUnitPriceFen()
const key = canonicalizeInternalSku(skuKey)
const result = await query<{
id: number
sku_key: string
canonical_product_id: number | null
platform_key: string
credit_quantity: number | string
cost_mode: string
enabled: boolean
note: string
channels_json: unknown
created_at: string
updated_at: string
}>(
`SELECT * FROM manual_fulfillment_configs
WHERE canonicalize_internal_sku(sku_key) = $1
ORDER BY id
LIMIT 1`,
[key],
)
const row = result.rows[0]
if (!row) return null
return mapManualConfig(row, unitPrices)
}
/** 平台选项(前端下拉)。 */
export async function listManualPlatformOptions() {
const unitPrices = await loadPlatformUnitPriceFen()
return {
items: MANUAL_PLATFORM_KEYS.map((key) => ({
key,
label: PLATFORM_LABELS[key],
isCredit: key !== 'fund_cash' && key !== 'on_account',
creditUnitPriceFen: unitPrices[key],
})),
}
}
function normalizeStoredChannels(input: {
channels_json: unknown
platform_key: string
credit_quantity: number | string
cost_mode: string
enabled: boolean
}): ManualChannelConfig[] {
const raw = Array.isArray(input.channels_json) ? input.channels_json : []
const parsed: ManualChannelConfig[] = []
const seen = new Set<ManualPlatformKey>()
for (const item of raw) {
if (!item || typeof item !== 'object' || Array.isArray(item)) continue
const row = item as Record<string, unknown>
const key = String(row.platformKey || row.platform_key || '').trim() as ManualPlatformKey
if (!MANUAL_PLATFORM_KEYS.includes(key) || seen.has(key)) continue
seen.add(key)
const creditQuantity =
parseManualChannelQuantity(row.creditQuantity ?? row.credit_quantity ?? 0, key) ?? 0
parsed.push({
platformKey: key,
creditQuantity,
costMode: creditQuantity > 0 ? 'fixed' : 'variable',
enabled: row.enabled !== false,
})
}
if (parsed.length > 0) return parsed
const key = String(input.platform_key || '').trim() as ManualPlatformKey
if (!MANUAL_PLATFORM_KEYS.includes(key)) return []
const creditQuantity = parseManualChannelQuantity(input.credit_quantity, key) ?? 0
return [
{
platformKey: key,
creditQuantity,
costMode: creditQuantity > 0 ? 'fixed' : 'variable',
enabled: input.enabled !== false,
},
]
}
function mapConfiguredChannels(
channels: ManualChannelConfig[],
unitPrices: Record<ManualPlatformKey, number>,
) {
return channels.map((channel) => {
const creditUnitPriceFen = unitPrices[channel.platformKey] ?? DEFAULT_CREDIT_UNIT_PRICE_FEN
return {
platformKey: channel.platformKey,
platformLabel: PLATFORM_LABELS[channel.platformKey] || channel.platformKey,
creditQuantity: channel.creditQuantity,
costMode: channel.costMode,
costFen: calculateManualCostFen(channel.creditQuantity, creditUnitPriceFen),
creditUnitPriceFen,
enabled: channel.enabled,
isFundCash: channel.platformKey === 'fund_cash',
isOnAccount: channel.platformKey === 'on_account',
}
})
}
function mapManualSku(row: ManualSkuRow, unitPrices: Record<ManualPlatformKey, number>) {
const creditQuantity = normalizeManualCreditQuantity(row.config_credit_quantity)
const platformKey = (row.config_platform_key || '') as ManualPlatformKey
const unitPriceFen = unitPrices[platformKey] ?? DEFAULT_CREDIT_UNIT_PRICE_FEN
const channels =
row.config_id === null
? []
: normalizeStoredChannels({
channels_json: row.config_channels_json,
platform_key: row.config_platform_key || '',
credit_quantity: row.config_credit_quantity || 0,
cost_mode: row.config_cost_mode || 'variable',
enabled: row.config_enabled !== false,
})
return {
id: Number(row.id),
skuKey: row.sku_key,
displayName: row.display_name || '',
shopCount: Number(row.shop_count || 0),
orderCount: Number(row.order_count || 0),
itemCount: Number(row.item_count || 0),
revenueFen: Number(row.revenue_fen || 0),
firstSeenDate: row.first_seen_date || null,
lastSeenDate: row.last_seen_date || null,
scanFromDate: row.scan_from_date || null,
scanToDate: row.scan_to_date || null,
configured: row.config_id !== null,
config: row.config_id
? {
id: Number(row.config_id),
skuKey: row.sku_key,
platformKey: row.config_platform_key || '',
platformLabel: PLATFORM_LABELS[platformKey] || '',
creditQuantity,
costMode: row.config_cost_mode || 'variable',
costFen: calculateManualCostFen(creditQuantity, unitPriceFen),
creditUnitPriceFen: unitPriceFen,
canonicalProductId: row.config_canonical_product_id
? Number(row.config_canonical_product_id)
: null,
enabled: row.config_enabled !== false,
channels: mapConfiguredChannels(channels, unitPrices),
}
: null,
}
}
function mapManualConfig(
row: {
id: number
sku_key: string
canonical_product_id: number | null
platform_key: string
credit_quantity: number | string
cost_mode: string
enabled: boolean
note: string
channels_json: unknown
created_at: string
updated_at: string
},
unitPrices: Record<ManualPlatformKey, number>,
) {
const creditQuantity = normalizeManualCreditQuantity(row.credit_quantity)
const platformKey = row.platform_key as ManualPlatformKey
const unitPriceFen = unitPrices[platformKey] ?? DEFAULT_CREDIT_UNIT_PRICE_FEN
const channels = normalizeStoredChannels(row)
return {
id: Number(row.id),
skuKey: row.sku_key,
canonicalProductId: row.canonical_product_id ? Number(row.canonical_product_id) : null,
platformKey: row.platform_key,
platformLabel: PLATFORM_LABELS[platformKey] || row.platform_key,
creditQuantity,
costMode: row.cost_mode,
costFen: calculateManualCostFen(creditQuantity, unitPriceFen),
creditUnitPriceFen: unitPriceFen,
enabled: row.enabled,
channels: mapConfiguredChannels(channels, unitPrices),
note: row.note || '',
createdAt: row.created_at,
updatedAt: row.updated_at,
}
}
function normalizePlatformKey(value: unknown): ManualPlatformKey {
const text = String(value || '').trim()
if (!MANUAL_PLATFORM_KEYS.includes(text as ManualPlatformKey)) {
throw createHttpError('履约渠道无效', {
statusCode: 400,
errorCode: 'manual_config_platform_invalid',
})
}
return text as ManualPlatformKey
}
function normalizeManualChannels(payload: JsonObject): ManualChannelConfig[] {
const rawChannels = Array.isArray(payload.channels) ? payload.channels : []
const source =
rawChannels.length > 0
? rawChannels
: [
{
platformKey: payload.platformKey ?? payload.platform_key,
creditQuantity: payload.creditQuantity ?? payload.credit_quantity,
enabled: payload.enabled,
},
]
const seen = new Set<ManualPlatformKey>()
const channels: ManualChannelConfig[] = []
for (const raw of source) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue
const item = raw as JsonObject
const platformKey = normalizePlatformKey(item.platformKey ?? item.platform_key)
if (seen.has(platformKey)) continue
seen.add(platformKey)
const creditQuantity = normalizeCreditQuantity(
item.creditQuantity ?? item.credit_quantity ?? 0,
platformKey,
)
channels.push({
platformKey,
creditQuantity,
costMode: creditQuantity > 0 ? 'fixed' : 'variable',
enabled: item.enabled === false ? false : true,
})
}
if (channels.length === 0) {
throw createHttpError('请至少配置一个履约渠道', {
statusCode: 400,
errorCode: 'manual_config_channels_required',
})
}
if (channels.length > 10) {
throw createHttpError('单个 SKU 最多配置 10 个履约渠道', {
statusCode: 400,
errorCode: 'manual_config_channels_too_many',
})
}
return channels
}
function normalizeCreditQuantity(value: unknown, platformKey: ManualPlatformKey) {
const parsed = parseManualChannelQuantity(value, platformKey)
if (parsed === null) {
throw createHttpError(
platformKey === 'fund_cash' || platformKey === 'on_account'
? '金额必须是大于等于 0 且最多 2 位小数的数字'
: '积分渠道的消耗积分必须是非负整数',
{
statusCode: 400,
errorCode: 'manual_config_credit_invalid',
},
)
}
return parsed
}
function normalizeOptionalDate(value: unknown, label: string) {
const text = String(value || '').trim()
if (!text) return null
return normalizeDate(text, label)
}
function normalizeDate(value: unknown, label: string) {
const text = String(value || '').trim()
if (!/^\d{4}-\d{2}-\d{2}$/.test(text)) {
throw createHttpError(`${label}格式无效(应为 YYYY-MM-DD)`, {
statusCode: 400,
errorCode: 'manual_sku_date_invalid',
})
}
return text
}
function normalizePositiveInteger(value: unknown, fallback: number, label: string) {
const parsed = Number(value)
if (!value || !Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 1) {
if (!value) return fallback
throw createHttpError(`${label}必须是正整数`, {
statusCode: 400,
errorCode: 'manual_sku_pagination_invalid',
})
}
return parsed
}
function normalizeOptionalId(value: unknown) {
const parsed = Number(value)
return Number.isInteger(parsed) && parsed > 0 ? parsed : null
}
function optionalText(value: unknown, maxLength: number) {
return String(value || '')
.trim()
.slice(0, maxLength)
}
function escapeLike(value: string) {
return value.replace(/[\\%_]/g, (char) => `\\${char}`)
}
function requiredRow<T>(row: T | undefined, message: string): T {
if (!row) {
throw createHttpError(message, {
statusCode: 404,
errorCode: 'manual_config_not_found',
})
}
return row
}
/**
* 人工配置 → internal_sku_channels(内部 SKU 精确匹配)。
*/
async function syncManualChannelRule(
config: {
id: number
sku_key: string
canonical_product_id: number | null
enabled: boolean
note: string
},
client?: PoolClient,
): Promise<void> {
const skuKey = String(config.sku_key || '').trim()
if (!skuKey) return
const otherChannelSql = `
SELECT EXISTS (
SELECT 1 FROM internal_sku_channels
WHERE canonicalize_internal_sku(internal_sku) = $1
AND enabled = TRUE
AND channel <> 'manual'
) AS exists
`
const otherChannel = client
? await client.query<{ exists: boolean }>(otherChannelSql, [skuKey])
: await query<{ exists: boolean }>(otherChannelSql, [skuKey])
const hasOtherChannel = otherChannel.rows[0]?.exists === true
const channelInput = {
internalSku: skuKey,
channel: 'manual',
priority: hasOtherChannel ? 90 : 10,
isFallback: hasOtherChannel,
enabled: config.enabled !== false,
canonicalProductId: config.canonical_product_id,
source: 'manual_config',
configJson: { manualConfigId: config.id, note: String(config.note || '').slice(0, 200) },
replacePriority: true,
} as const
if (client) {
await upsertInternalSkuChannelWithClient(client, channelInput)
return
}
await upsertInternalSkuChannel(channelInput)
}