feat(finance): 人工成本单事务/幂等 + 配置自动匹配 + 缺成本监控
- 确认履约改为单事务:锁订单项 → 复查快照 → 扣积分/备用金 → 写成本快照; 快照失败整体回滚,不再出现「钱扣了、成本没记」 - manual_case 的 subject_id 统一为 order_item_id,新增订单项级唯一索引(迁移 111), 消除 manual_expenses.id / platform_credit_entries.id 跨表撞车 - 人工 SKU 匹配增加 sku_code / sku_name 兜底;保存配置立即回填最近 30 天, 定时任务按窗口 rematch,确认时再按 SKU 兜底匹配 - 新增 manual_cost_missing 异常队列:从首次人工配置起算,确认履约立即收口 - 补单元测试与真实 PostgreSQL 集成测试(并发、重复、强制快照失败回滚、双资金链路) - 校准财务文档并新增上线初始化/验收手册(历史人工不补录,只保证配置后的新单) 验证:backend typecheck/lint/format/check:sql/test 843(839 pass / 4 skip); frontend typecheck/lint/test 172;迁移 111 在 scratch 库全量执行 + 重跑幂等。
This commit is contained in:
@@ -672,6 +672,7 @@ async function insertAndResolveCostMissingExceptions(
|
||||
SELECT
|
||||
oi.id AS order_item_id,
|
||||
oi.canonical_product_id,
|
||||
oi.fulfillment_config_id,
|
||||
COALESCE(o.paid_at, o.created_at) AS basis_at,
|
||||
wo.id AS work_order_id,
|
||||
COALESCE(oi.fulfillment_mode, 'manual') AS fulfillment_mode
|
||||
@@ -714,6 +715,58 @@ async function insertAndResolveCostMissingExceptions(
|
||||
[fromDate, toDate],
|
||||
)
|
||||
|
||||
const manualInserted = await client.query(
|
||||
`
|
||||
WITH cutoff AS (
|
||||
SELECT MIN(created_at) AS enforce_from
|
||||
FROM manual_fulfillment_configs
|
||||
),
|
||||
item_scope AS (
|
||||
SELECT
|
||||
oi.id AS order_item_id,
|
||||
oi.fulfillment_config_id,
|
||||
COALESCE(o.paid_at, o.created_at) AS basis_at
|
||||
FROM order_items oi
|
||||
JOIN orders o ON o.id = oi.order_id
|
||||
WHERE o.pay_status IN ('paid', 'refunded')
|
||||
AND (COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date
|
||||
BETWEEN $1::date AND $2::date
|
||||
AND oi.fulfillment_mode = 'manual'
|
||||
)
|
||||
INSERT INTO cost_exceptions (
|
||||
subject_type, subject_id, order_item_id, work_order_id,
|
||||
reason, status, detail_json, created_at
|
||||
)
|
||||
SELECT
|
||||
'order_item', s.order_item_id, s.order_item_id, NULL,
|
||||
'manual_cost_missing', 'open',
|
||||
jsonb_build_object(
|
||||
'fulfillmentMode', 'manual',
|
||||
'basisAt', s.basis_at,
|
||||
'configMissing', s.fulfillment_config_id IS NULL,
|
||||
'message', CASE
|
||||
WHEN s.fulfillment_config_id IS NULL
|
||||
THEN '人工订单项未配置履约渠道,请先在成本中心配置人工 SKU'
|
||||
ELSE '人工订单项尚未确认履约并记录成本'
|
||||
END
|
||||
),
|
||||
NOW()
|
||||
FROM item_scope s
|
||||
CROSS JOIN cutoff c
|
||||
WHERE c.enforce_from IS NOT NULL
|
||||
-- 只监控「第一次配置人工履约之后」的订单项:历史人工单按既定口径不补录。
|
||||
AND s.basis_at >= c.enforce_from
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM cost_snapshots cs
|
||||
WHERE cs.subject_type = 'manual_case'
|
||||
AND cs.order_item_id = s.order_item_id
|
||||
AND cs.superseded_at IS NULL
|
||||
)
|
||||
ON CONFLICT (subject_type, subject_id, reason) DO NOTHING
|
||||
`,
|
||||
[fromDate, toDate],
|
||||
)
|
||||
|
||||
const resolved = await client.query(
|
||||
`
|
||||
UPDATE cost_exceptions ce
|
||||
@@ -730,5 +783,24 @@ async function insertAndResolveCostMissingExceptions(
|
||||
`,
|
||||
)
|
||||
|
||||
return { created: inserted.rowCount || 0, resolved: resolved.rowCount || 0 }
|
||||
const manualResolved = await client.query(
|
||||
`
|
||||
UPDATE cost_exceptions ce
|
||||
SET status = 'resolved', resolved_at = NOW()
|
||||
WHERE ce.status = 'open'
|
||||
AND ce.subject_type = 'order_item'
|
||||
AND ce.reason = 'manual_cost_missing'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM cost_snapshots cs
|
||||
WHERE cs.subject_type = 'manual_case'
|
||||
AND cs.order_item_id = ce.subject_id
|
||||
AND cs.superseded_at IS NULL
|
||||
)
|
||||
`,
|
||||
)
|
||||
|
||||
return {
|
||||
created: (inserted.rowCount || 0) + (manualInserted.rowCount || 0),
|
||||
resolved: (resolved.rowCount || 0) + (manualResolved.rowCount || 0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { query, withTransaction } from '../../db/client.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'
|
||||
|
||||
/**
|
||||
* 人工履约 SKU 配置服务。
|
||||
*
|
||||
* 口径(2026-10-24 确认):
|
||||
* * 配置主键是**内部 SKU**(快手 spec_json.skuNick / 拼多多 spec_json.outSkuSn),
|
||||
* 不是商品标题;同名 SKU 算同一个商品,跨渠道共用一份配置;
|
||||
* * 配置主键优先取内部 SKU(快手 spec_json.skuNick / 拼多多 spec_json.outSkuSn),
|
||||
* 缺失时按 sku_code → sku_name 兜底;同名/同码算同一个商品,跨渠道共用一份配置;
|
||||
* * 配置项:履约渠道(南航/乐玩/ROCK/备用金现金)+ 消耗积分 + 成本模式;
|
||||
* * 换算率固定:1 积分 = 1 分钱;
|
||||
* * 消耗积分 0 = 成本不固定,由客服在确认履约时手填实际成本;
|
||||
@@ -125,7 +126,9 @@ export async function scanManualSkus(options: ScanOptions) {
|
||||
(COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date AS stat_date,
|
||||
COALESCE(
|
||||
NULLIF(oi.spec_json->>'skuNick', ''),
|
||||
NULLIF(oi.spec_json->>'outSkuSn', '')
|
||||
NULLIF(oi.spec_json->>'outSkuSn', ''),
|
||||
NULLIF(oi.sku_code, ''),
|
||||
NULLIF(oi.sku_name, '')
|
||||
) AS sku_key
|
||||
FROM order_items oi
|
||||
JOIN orders o ON o.id = oi.order_id
|
||||
@@ -380,6 +383,15 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
||||
|
||||
const config = requiredRow(result.rows[0], '保存人工履约配置失败')
|
||||
await syncRegistryConfigId(config.sku_key, config.id)
|
||||
// 配置保存后立刻回填该 SKU 最近 30 天的订单项,避免必须再点一次「重新匹配」。
|
||||
// 历史更早的订单项不自动回填(历史人工成本不补录);需要时再显式点「重新匹配」。
|
||||
const today = formatShanghaiDate(new Date())
|
||||
await rematchManualFulfillments({
|
||||
skuKey: config.sku_key,
|
||||
onlyUnmatched: true,
|
||||
dateFrom: shiftDate(today, -29),
|
||||
dateTo: today,
|
||||
})
|
||||
return mapManualConfig(config, unitPrices)
|
||||
}
|
||||
|
||||
@@ -408,6 +420,9 @@ export async function deleteManualFulfillmentConfig(skuKey: string) {
|
||||
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 now = nowIso()
|
||||
const result = await query<{ updated_count: number }>(
|
||||
@@ -422,22 +437,32 @@ export async function rematchManualFulfillments(input: Record<string, unknown> =
|
||||
JOIN manual_fulfillment_configs cfg
|
||||
ON cfg.sku_key = COALESCE(
|
||||
NULLIF(oi.spec_json->>'skuNick', ''),
|
||||
NULLIF(oi.spec_json->>'outSkuSn', '')
|
||||
NULLIF(oi.spec_json->>'outSkuSn', ''),
|
||||
NULLIF(oi.sku_code, ''),
|
||||
NULLIF(oi.sku_name, '')
|
||||
)
|
||||
WHERE oi.fulfillment_mode = 'manual'
|
||||
AND cfg.enabled = TRUE
|
||||
AND ($1 = '' OR 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
|
||||
)
|
||||
)
|
||||
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 = $3
|
||||
updated_at = $5
|
||||
FROM target
|
||||
WHERE oi.id = target.order_item_id
|
||||
RETURNING 1
|
||||
`,
|
||||
[skuKey, onlyUnmatched, now],
|
||||
[skuKey, onlyUnmatched, dateFrom, dateTo, now],
|
||||
)
|
||||
|
||||
// 配置生效后,把 SKU 对应的成本版本挂上(若已配置商品)。
|
||||
@@ -446,6 +471,8 @@ export async function rematchManualFulfillments(input: Record<string, unknown> =
|
||||
return {
|
||||
updatedCount: result.rowCount || 0,
|
||||
skuKey,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -629,6 +656,12 @@ function normalizeCreditQuantity(value: unknown) {
|
||||
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)) {
|
||||
|
||||
@@ -290,55 +290,73 @@ export async function consumePlatformCredit(input: {
|
||||
platformRef?: string
|
||||
note?: string
|
||||
}): Promise<{ entryId: number; balanceAfter: number; amountFen: number }> {
|
||||
return withTransaction((client) => consumePlatformCreditWithClient(client, input))
|
||||
}
|
||||
|
||||
/**
|
||||
* 在调用方事务内消耗积分。
|
||||
*
|
||||
* 人工履约的「扣积分 + 写成本快照」必须在同一事务里完成,
|
||||
* 否则快照失败会留下已扣积分、未记成本的资金洞。
|
||||
*/
|
||||
export async function consumePlatformCreditWithClient(
|
||||
client: PoolClient,
|
||||
input: {
|
||||
ownerAdminUserId: number
|
||||
platformKey: PlatformCreditKey
|
||||
quantity: number
|
||||
relatedTaskId?: number | null
|
||||
platformRef?: string
|
||||
note?: string
|
||||
},
|
||||
): Promise<{ entryId: number; balanceAfter: number; amountFen: number }> {
|
||||
const unitPrices = await loadUnitPrices()
|
||||
const unitPriceFen = unitPrices[input.platformKey]
|
||||
const now = nowIso()
|
||||
|
||||
return withTransaction(async (client) => {
|
||||
await ensureAccountRow(client, input.ownerAdminUserId, input.platformKey, unitPriceFen, now)
|
||||
const account = await lockAccount(client, input.ownerAdminUserId, input.platformKey)
|
||||
const balance = Number(account.balance_quantity)
|
||||
if (balance < input.quantity) {
|
||||
throw createHttpError(
|
||||
`${PLATFORM_LABELS[input.platformKey]}积分不足(当前 ${balance},需要 ${input.quantity}),请联系主管充值`,
|
||||
{
|
||||
statusCode: 409,
|
||||
errorCode: 'platform_credit_balance_insufficient',
|
||||
},
|
||||
)
|
||||
}
|
||||
const nextBalance = balance - input.quantity
|
||||
await client.query(
|
||||
`UPDATE platform_credit_accounts
|
||||
SET balance_quantity = $2, updated_at = $3
|
||||
WHERE id = $1`,
|
||||
[account.id, nextBalance, now],
|
||||
await ensureAccountRow(client, input.ownerAdminUserId, input.platformKey, unitPriceFen, now)
|
||||
const account = await lockAccount(client, input.ownerAdminUserId, input.platformKey)
|
||||
const balance = Number(account.balance_quantity)
|
||||
if (balance < input.quantity) {
|
||||
throw createHttpError(
|
||||
`${PLATFORM_LABELS[input.platformKey]}积分不足(当前 ${balance},需要 ${input.quantity}),请联系主管充值`,
|
||||
{
|
||||
statusCode: 409,
|
||||
errorCode: 'platform_credit_balance_insufficient',
|
||||
},
|
||||
)
|
||||
const entryResult = await client.query<CreditEntryRow>(
|
||||
`
|
||||
INSERT INTO platform_credit_entries (
|
||||
account_id, entry_type, quantity_delta, balance_after, amount_fen,
|
||||
platform_ref, related_task_id, note, created_at
|
||||
) VALUES ($1, 'consume', $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING *
|
||||
`,
|
||||
[
|
||||
account.id,
|
||||
-input.quantity,
|
||||
nextBalance,
|
||||
input.quantity * unitPriceFen,
|
||||
input.platformRef || '',
|
||||
input.relatedTaskId ?? null,
|
||||
input.note || '',
|
||||
now,
|
||||
],
|
||||
)
|
||||
return {
|
||||
entryId: Number(entryResult.rows[0]?.id || 0),
|
||||
balanceAfter: nextBalance,
|
||||
amountFen: input.quantity * unitPriceFen,
|
||||
}
|
||||
})
|
||||
}
|
||||
const nextBalance = balance - input.quantity
|
||||
await client.query(
|
||||
`UPDATE platform_credit_accounts
|
||||
SET balance_quantity = $2, updated_at = $3
|
||||
WHERE id = $1`,
|
||||
[account.id, nextBalance, now],
|
||||
)
|
||||
const entryResult = await client.query<CreditEntryRow>(
|
||||
`
|
||||
INSERT INTO platform_credit_entries (
|
||||
account_id, entry_type, quantity_delta, balance_after, amount_fen,
|
||||
platform_ref, related_task_id, note, created_at
|
||||
) VALUES ($1, 'consume', $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING *
|
||||
`,
|
||||
[
|
||||
account.id,
|
||||
-input.quantity,
|
||||
nextBalance,
|
||||
input.quantity * unitPriceFen,
|
||||
input.platformRef || '',
|
||||
input.relatedTaskId ?? null,
|
||||
input.note || '',
|
||||
now,
|
||||
],
|
||||
)
|
||||
return {
|
||||
entryId: Number(entryResult.rows[0]?.id || 0),
|
||||
balanceAfter: nextBalance,
|
||||
amountFen: input.quantity * unitPriceFen,
|
||||
}
|
||||
}
|
||||
|
||||
/** 积分流水列表。 */
|
||||
|
||||
Reference in New Issue
Block a user