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:
yml2213
2026-10-26 13:04:51 +08:00
parent 73908119dc
commit a3e2bdb7c4
22 changed files with 1575 additions and 390 deletions
@@ -1,3 +1,5 @@
import type { PoolClient } from 'pg'
import { query, withTransaction } from '../../db/client.js'
import type { JsonObject } from '../../types/json.js'
import { createHttpError } from '../../utils/http.js'
@@ -8,7 +10,8 @@ import {
buildManualFulfillmentReference,
} from './manual-fulfillment-note.js'
import {
consumePlatformCredit,
consumePlatformCreditWithClient,
PLATFORM_CREDIT_KEYS,
type PlatformCreditKey,
} from '../cost-center/platform-credit-service.js'
@@ -52,6 +55,28 @@ type PendingRow = {
fulfilled_at: string | null
}
type ConfirmContextRow = {
order_item_id: number
order_id: number
order_id_resolved: number
platform_order_id: string
provider: string
shop_id: string
sku_code: string
sku_name: string
revenue_fen: string
canonical_product_id: number | null
fulfillment_mode: string
config_id: number | null
platform_key: string
credit_quantity: string
cost_mode: string
credit_unit_price_fen: string
work_order_id: number | null
work_order_no: string | null
work_product_rule_id: number | null
}
/**
* 列出客服的人工履约待办。
*
@@ -128,7 +153,12 @@ export async function listManualFulfillmentPending(
o.shop_id,
oi.sku_code,
oi.sku_name,
COALESCE(NULLIF(oi.spec_json->>'skuNick',''), NULLIF(oi.spec_json->>'outSkuSn','')) AS internal_sku,
COALESCE(
NULLIF(oi.spec_json->>'skuNick',''),
NULLIF(oi.spec_json->>'outSkuSn',''),
NULLIF(oi.sku_code,''),
NULLIF(oi.sku_name,'')
) AS internal_sku,
COALESCE(oi.revenue_amount_fen, 0)::bigint AS revenue_fen,
COALESCE(o.paid_at, o.created_at) AS paid_at,
cfg.id AS config_id,
@@ -167,135 +197,134 @@ export async function confirmManualFulfillment(payload: JsonObject, session: Adm
)
const now = nowIso()
const context = await query<{
order_item_id: number
order_id: number
order_id_resolved: number
platform_order_id: string
provider: string
shop_id: string
sku_code: string
sku_name: string
revenue_fen: string
canonical_product_id: number | null
fulfillment_mode: string
config_id: number | null
platform_key: string
credit_quantity: string
cost_mode: string
credit_unit_price_fen: string
work_order_id: number | null
work_order_no: string | null
work_product_rule_id: number | null
fulfilled_at: string | null
}>(
`
WITH fulfilled AS (
SELECT cs.order_item_id, MAX(cs.created_at) AS fulfilled_at
FROM cost_snapshots cs
WHERE cs.subject_type = 'manual_case' AND cs.superseded_at IS NULL
GROUP BY cs.order_item_id
)
SELECT
oi.id AS order_item_id,
oi.order_id,
o.id AS order_id_resolved,
o.platform_order_id,
o.provider,
o.shop_id,
oi.sku_code,
oi.sku_name,
COALESCE(oi.revenue_amount_fen, 0)::bigint AS revenue_fen,
oi.canonical_product_id,
oi.fulfillment_mode,
oi.fulfillment_config_id AS config_id,
COALESCE(cfg.platform_key, '') AS platform_key,
COALESCE(cfg.credit_quantity, 0)::bigint AS credit_quantity,
COALESCE(cfg.cost_mode, 'variable') AS cost_mode,
COALESCE((fp.config_json->>'rechargeUnitPriceFen')::bigint, 1) AS credit_unit_price_fen,
wo.id AS work_order_id,
wo.work_order_no,
wo.product_rule_id AS work_product_rule_id,
fulfilled.fulfilled_at
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
LEFT JOIN manual_fulfillment_configs cfg ON cfg.id = oi.fulfillment_config_id
LEFT JOIN fulfillment_profiles fp ON fp.profile_key = 'manual_' || cfg.platform_key
LEFT JOIN LATERAL (
SELECT id, product_rule_id, work_order_no FROM work_orders
WHERE order_item_id = oi.id ORDER BY id DESC LIMIT 1
) wo ON TRUE
LEFT JOIN fulfilled ON fulfilled.order_item_id = oi.id
WHERE oi.id = $1
LIMIT 1
`,
[orderItemId],
)
// 钱与成本必须同一事务:先锁订单项、复查未履约,再扣款、最后写快照。
// 任何一步失败(余额不足、成本版本缺失、重复快照)都整体回滚,不会留下「扣了钱没记成本」。
return withTransaction(async (client) => {
// 配置可能晚于订单创建:确认前按 SKU 再匹配一次(与定时 rematch 同口径),
// 保证「配置好之后的新单」不需要人工再点一次「重新匹配」。
await matchManualFulfillmentConfigWithClient(client, orderItemId, now)
const row = context.rows[0]
if (!row) {
throw createHttpError('订单项不存在', {
statusCode: 404,
errorCode: 'manual_fulfillment_order_item_not_found',
})
}
if (row.fulfillment_mode !== 'manual') {
throw createHttpError('该订单项不是人工履约', {
statusCode: 409,
errorCode: 'manual_fulfillment_not_manual',
})
}
if (row.fulfilled_at) {
throw createHttpError('该订单项已确认过履约,不能重复操作', {
statusCode: 409,
errorCode: 'manual_fulfillment_already_done',
})
}
if (!row.config_id) {
throw createHttpError('该商品还没有配置履约渠道,请先在成本中心配置', {
statusCode: 409,
errorCode: 'manual_fulfillment_config_missing',
})
}
const context = await client.query<ConfirmContextRow>(
`
SELECT
oi.id AS order_item_id,
oi.order_id,
o.id AS order_id_resolved,
o.platform_order_id,
o.provider,
o.shop_id,
oi.sku_code,
oi.sku_name,
COALESCE(oi.revenue_amount_fen, 0)::bigint AS revenue_fen,
oi.canonical_product_id,
oi.fulfillment_mode,
oi.fulfillment_config_id AS config_id,
COALESCE(cfg.platform_key, '') AS platform_key,
COALESCE(cfg.credit_quantity, 0)::bigint AS credit_quantity,
COALESCE(cfg.cost_mode, 'variable') AS cost_mode,
COALESCE((fp.config_json->>'rechargeUnitPriceFen')::bigint, 1) AS credit_unit_price_fen,
wo.id AS work_order_id,
wo.work_order_no,
wo.product_rule_id AS work_product_rule_id
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
LEFT JOIN manual_fulfillment_configs cfg ON cfg.id = oi.fulfillment_config_id
LEFT JOIN fulfillment_profiles fp ON fp.profile_key = 'manual_' || cfg.platform_key
LEFT JOIN LATERAL (
SELECT id, product_rule_id, work_order_no FROM work_orders
WHERE order_item_id = oi.id ORDER BY id DESC LIMIT 1
) wo ON TRUE
WHERE oi.id = $1
LIMIT 1
FOR UPDATE OF oi
`,
[orderItemId],
)
const platformKey = row.platform_key as PlatformCreditKey | 'fund_cash'
const creditQuantity = Number(row.credit_quantity || 0)
const unitPriceFen = Number(row.credit_unit_price_fen || 1)
// 成本:固定成本用配置值;成本不固定必须客服手填。
let costFen: number
if (creditQuantity > 0) {
costFen = creditQuantity * unitPriceFen
} else {
const provided = payload.costFen ?? payload.cost_fen ?? payload.amountFen
costFen = normalizeCostFen(provided)
if (costFen === 0) {
throw createHttpError('该商品成本不固定,请填写本次实际成本', {
statusCode: 400,
errorCode: 'manual_fulfillment_cost_required',
const row = context.rows[0]
if (!row) {
throw createHttpError('订单项不存在', {
statusCode: 404,
errorCode: 'manual_fulfillment_order_item_not_found',
})
}
if (row.fulfillment_mode !== 'manual') {
throw createHttpError('该订单项不是人工履约', {
statusCode: 409,
errorCode: 'manual_fulfillment_not_manual',
})
}
if (!row.config_id) {
throw createHttpError('该商品还没有配置履约渠道,请先在成本中心配置', {
statusCode: 409,
errorCode: 'manual_fulfillment_config_missing',
})
}
const platformKey = row.platform_key as PlatformCreditKey | 'fund_cash'
if (platformKey !== 'fund_cash' && !PLATFORM_CREDIT_KEYS.includes(platformKey)) {
throw createHttpError('该商品的人工履约平台配置无效,请重新配置', {
statusCode: 409,
errorCode: 'manual_fulfillment_config_invalid',
})
}
}
const note = optionalText(payload.note, 300)
const payeeName = optionalText(payload.payeeName ?? payload.payee_name, 120)
const fulfillmentReference = buildManualFulfillmentReference({
workOrderNo: row.work_order_no,
platformOrderId: row.platform_order_id,
orderItemId,
})
// 锁内复查:并发/双击的第二个请求会等锁,醒来后看到快照直接拒绝,不会重复扣款。
const existing = await client.query<{ id: number }>(
`SELECT id FROM cost_snapshots
WHERE subject_type = 'manual_case' AND order_item_id = $1 AND superseded_at IS NULL
LIMIT 1`,
[orderItemId],
)
if (existing.rows[0]) {
throw createHttpError('该订单项已确认过履约,不能重复操作', {
statusCode: 409,
errorCode: 'manual_fulfillment_already_done',
})
}
// 1. 先扣额度(积分平台走积分钱包;备用金现金走现有 fund_* 链路)。
let creditEntryId: number | null = null
let fundExpenseId: number | null = null
let balanceAfter: number | null = null
const creditQuantity = Number(row.credit_quantity || 0)
const unitPriceFen = Number(row.credit_unit_price_fen || 1)
if (platformKey !== 'fund_cash' && creditQuantity <= 0) {
throw createHttpError('该人工 SKU 的积分配置无效,请先在成本中心重新配置', {
statusCode: 409,
errorCode: 'manual_fulfillment_config_invalid',
})
}
if (platformKey === 'fund_cash') {
// 备用金现金:复用现有客服备用金支出链路(扣余额 + 写 fund_entries + manual_expenses)。
const { writeFundExpense } = await import('../admin/admin-fund-service.js')
const fundAccountId = await resolveFundAccountId(session)
const written = await withTransaction(async (client) => {
return writeFundExpense(client, {
const costPlan = resolveManualFulfillmentCost({
creditQuantity,
unitPriceFen,
providedCostFen: payload.costFen ?? payload.cost_fen ?? payload.amountFen,
})
const costFen = costPlan.costFen
const payeeName = optionalText(payload.payeeName ?? payload.payee_name, 120)
const note = optionalText(payload.note, 300)
const fulfillmentReference = buildManualFulfillmentReference({
workOrderNo: row.work_order_no,
platformOrderId: row.platform_order_id,
orderItemId,
})
// 先把成本项/版本解析完再扣钱:版本缺失不能发生在扣款之后。
const costItemId = await resolveManualCostItemIdWithClient(client)
const versionId = await resolveCostVersionIdWithClient(client, costItemId, row, now)
if (!versionId) {
throw createHttpError('该成本项没有可用的成本版本,请先在成本中心配置后重试', {
statusCode: 409,
errorCode: 'manual_fulfillment_cost_version_missing',
})
}
let fundExpenseId: number | null = null
let creditEntryId: number | null = null
let balanceAfter: number | null = null
let subjectSource: 'manual_expense' | 'platform_credit'
if (platformKey === 'fund_cash') {
// 备用金现金:复用唯一写入口,但把 client 传进去,和快照共用同一个事务。
const fundAccountId = await resolveFundAccountId(session, client)
const { writeFundExpense } = await import('../admin/admin-fund-service.js')
const written = await writeFundExpense(client, {
agentAccountId: fundAccountId,
amountFen: costFen,
category: 'other',
@@ -312,115 +341,122 @@ export async function confirmManualFulfillment(payload: JsonObject, session: Adm
maxLength: 500,
}),
actorUserId: session.userId,
// 同一订单可能有多个同价人工项:幂等由订单项锁 + 快照唯一索引保证,
// 这里放开 24 小时同金额同收款方的通用防重,避免误拦第二个订单项。
allowDuplicate: true,
})
})
fundExpenseId = Number(written.expense.id)
balanceAfter = written.balanceAfterFen
} else if (creditQuantity > 0) {
const consumed = await consumePlatformCredit({
ownerAdminUserId: session.userId,
platformKey: platformKey as PlatformCreditKey,
quantity: creditQuantity,
relatedTaskId: null,
platformRef: row.work_order_no || row.platform_order_id,
note: buildManualFulfillmentNote({
skuName: row.sku_name,
reference: fulfillmentReference,
note,
maxLength: 300,
}),
})
creditEntryId = consumed.entryId
balanceAfter = consumed.balanceAfter
}
// 2. 写 actual 成本快照(主体 = 备用金支出单 / 积分流水)。
const subjectId = fundExpenseId ?? creditEntryId ?? orderItemId
const costItemId = await resolveManualCostItemId()
const versionId = await resolveCostVersionId(costItemId, row, now)
if (!versionId) {
throw createHttpError('该成本项没有可用的成本版本,请先在成本中心配置后重试', {
statusCode: 409,
errorCode: 'manual_fulfillment_cost_version_missing',
})
}
const snapshot = await query<{ id: number }>(
`
INSERT INTO cost_snapshots (
subject_type, subject_id, order_id, order_item_id, work_order_id,
cost_item_id, cost_version_id, canonical_product_id,
quantity, unit_amount_fen, total_amount_fen, snapshot_stage, source,
metadata_json, cost_basis_at, resolved_at, created_at
) VALUES (
'manual_case', $1, $2, $3, $4,
$5, $6, $7,
1, $8, $8, 'actual', 'manual_input',
$9::jsonb, $10, $11, $11
)
ON CONFLICT (subject_type, subject_id, cost_item_id)
WHERE superseded_at IS NULL
DO NOTHING
RETURNING id
`,
[
subjectId,
row.order_id_resolved,
orderItemId,
row.work_order_id,
costItemId,
versionId,
row.canonical_product_id,
costFen,
JSON.stringify({
source: 'manual_fulfillment_confirm',
fundExpenseId = Number(written.expense.id)
balanceAfter = written.balanceAfterFen
subjectSource = 'manual_expense'
} else {
const consumed = await consumePlatformCreditWithClient(client, {
ownerAdminUserId: session.userId,
platformKey,
platformLabel: PLATFORM_LABELS[platformKey] || platformKey,
creditQuantity,
creditUnitPriceFen: unitPriceFen,
costMode: creditQuantity > 0 ? 'fixed' : 'variable',
costFen,
fundExpenseId,
creditEntryId,
payeeName,
note,
fulfilledBy: {
userId: Number(session.userId || 0),
displayName: String(session.displayName || ''),
role: String(session.role || ''),
},
}),
now,
nowIso(),
],
)
const snapshotId = snapshot.rows[0]?.id ?? null
if (!snapshotId) {
throw createHttpError('该订单项已有人工成本快照,不能重复录入', {
statusCode: 409,
errorCode: 'manual_fulfillment_snapshot_conflict',
})
}
quantity: creditQuantity,
relatedTaskId: null,
platformRef: row.work_order_no || row.platform_order_id,
note: buildManualFulfillmentNote({
skuName: row.sku_name,
reference: fulfillmentReference,
note,
maxLength: 300,
}),
})
creditEntryId = consumed.entryId
balanceAfter = consumed.balanceAfter
subjectSource = 'platform_credit'
}
return {
orderItemId,
orderId: Number(row.order_id_resolved),
costSnapshotId: snapshotId,
platformKey,
platformLabel: PLATFORM_LABELS[platformKey] || platformKey,
creditQuantity,
costFen,
fundExpenseId,
creditEntryId,
balanceAfter,
}
// subject_id 固定为 order_item_id:不再与 manual_expenses.id /
// platform_credit_entries.id 混用,避免两张表序列撞车。
// subject_type 仍为 manual_case,资金流水只放在 metadata 里。
const snapshot = await client.query<{ id: number }>(
`
INSERT INTO cost_snapshots (
subject_type, subject_id, order_id, order_item_id, work_order_id,
cost_item_id, cost_version_id, canonical_product_id,
quantity, unit_amount_fen, total_amount_fen, snapshot_stage, source,
metadata_json, cost_basis_at, resolved_at, created_at
) VALUES (
'manual_case', $1, $2, $1, $3,
$4, $5, $6,
1, $7, $7, 'actual', 'manual_input',
$8::jsonb, $9, $9, $9
)
ON CONFLICT DO NOTHING
RETURNING id
`,
[
orderItemId,
row.order_id_resolved,
row.work_order_id,
costItemId,
versionId,
row.canonical_product_id,
costFen,
JSON.stringify({
source: 'manual_fulfillment_confirm',
subjectSource,
configId: Number(row.config_id),
platformKey,
platformLabel: PLATFORM_LABELS[platformKey] || platformKey,
creditQuantity,
creditUnitPriceFen: unitPriceFen,
costMode: costPlan.costMode,
costFen,
fundExpenseId,
creditEntryId,
balanceAfter,
payeeName,
note,
fulfilledBy: {
userId: Number(session.userId || 0),
displayName: String(session.displayName || ''),
role: String(session.role || ''),
},
}),
now,
],
)
const snapshotId = snapshot.rows[0]?.id ?? null
if (!snapshotId) {
// 订单项唯一索引兜底:任何竞态都会走到这里,抛错回滚本次扣款。
throw createHttpError('该订单项已有人工成本快照,不能重复录入', {
statusCode: 409,
errorCode: 'manual_fulfillment_snapshot_conflict',
})
}
// 人工缺成本异常立即收口,不等下一轮定时任务。
await client.query(
`UPDATE cost_exceptions
SET status = 'resolved', resolved_at = $2
WHERE subject_type = 'order_item'
AND subject_id = $1
AND reason = 'manual_cost_missing'
AND status = 'open'`,
[orderItemId, now],
)
return {
orderItemId,
orderId: Number(row.order_id_resolved),
costSnapshotId: snapshotId,
platformKey,
platformLabel: PLATFORM_LABELS[platformKey] || platformKey,
creditQuantity,
costFen,
fundExpenseId,
creditEntryId,
balanceAfter,
}
})
}
/** 客服自己的备用金账户(管理员代录时用指定账户)。 */
async function resolveFundAccountId(session: AdminSession) {
async function resolveFundAccountId(session: AdminSession, client?: Pick<PoolClient, 'query'>) {
const { getOwnAgentAccountId } = await import('../admin/admin-fund-service.js')
const own = await getOwnAgentAccountId(session.userId)
const own = await getOwnAgentAccountId(session.userId, client)
if (own) return own
throw createHttpError('当前账号还没有备用金账户', {
statusCode: 404,
@@ -428,8 +464,67 @@ async function resolveFundAccountId(session: AdminSession) {
})
}
async function resolveManualCostItemId() {
const result = await query<{ id: number }>(
/**
* 确认前按 SKU 匹配人工履约配置。
*
* 与 `rematchManualFulfillments` 使用同一套键:
* spec_json.skuNick -> spec_json.outSkuSn -> sku_code -> sku_name。
* 这样即使配置晚于订单创建,新单在确认时也能自动挂上渠道。
*/
async function matchManualFulfillmentConfigWithClient(
client: PoolClient,
orderItemId: number,
now: string,
) {
const matched = await client.query<{
id: number
canonical_product_id: number | null
}>(
`
SELECT cfg.id, cfg.canonical_product_id
FROM order_items oi
JOIN manual_fulfillment_configs cfg ON cfg.enabled = TRUE
AND (
cfg.sku_key = COALESCE(
NULLIF(oi.spec_json->>'skuNick', ''),
NULLIF(oi.spec_json->>'outSkuSn', ''),
NULLIF(oi.sku_code, ''),
NULLIF(oi.sku_name, '')
)
OR (
cfg.canonical_product_id IS NOT NULL
AND cfg.canonical_product_id = oi.canonical_product_id
)
)
WHERE oi.id = $1
AND oi.fulfillment_mode = 'manual'
AND oi.fulfillment_config_id IS NULL
ORDER BY
(cfg.canonical_product_id IS NOT NULL
AND cfg.canonical_product_id = oi.canonical_product_id) DESC,
cfg.id ASC
LIMIT 1
`,
[orderItemId],
)
const match = matched.rows[0]
if (!match) return false
await client.query(
`
UPDATE order_items
SET fulfillment_config_id = $2,
canonical_product_id = COALESCE($3, canonical_product_id),
updated_at = $4
WHERE id = $1
AND fulfillment_config_id IS NULL
`,
[orderItemId, match.id, match.canonical_product_id, now],
)
return true
}
async function resolveManualCostItemIdWithClient(client: PoolClient) {
const result = await client.query<{ id: number }>(
`SELECT id FROM cost_items WHERE code = 'sys_manual_service' AND status = 'active' LIMIT 1`,
)
const id = Number(result.rows[0]?.id || 0)
@@ -442,7 +537,8 @@ async function resolveManualCostItemId() {
return id
}
async function resolveCostVersionId(
async function resolveCostVersionIdWithClient(
client: PoolClient,
costItemId: number,
row: {
order_id_resolved: number
@@ -454,7 +550,7 @@ async function resolveCostVersionId(
},
basisAt: string,
) {
const result = await query<{ id: number }>(
const result = await client.query<{ id: number }>(
`
SELECT v.id
FROM cost_versions v
@@ -499,6 +595,40 @@ async function resolveCostVersionId(
return result.rows[0]?.id ?? null
}
/**
* 人工履约的本次成本:固定成本按「配置积分 × 平台换算率」,成本不固定必须客服手填。
* 抽成纯函数,便于单测覆盖固定/手填/非法金额三种分支。
*/
export function resolveManualFulfillmentCost(input: {
creditQuantity: number
unitPriceFen: number
providedCostFen?: unknown
}): { costFen: number; costMode: 'fixed' | 'variable' } {
const creditQuantity = Math.max(0, Math.trunc(Number(input.creditQuantity) || 0))
if (creditQuantity > 0) {
const unitPriceFen = Math.max(0, Math.trunc(Number(input.unitPriceFen) || 0))
return { costFen: creditQuantity * unitPriceFen, costMode: 'fixed' }
}
if (
input.providedCostFen === undefined ||
input.providedCostFen === null ||
input.providedCostFen === ''
) {
throw createHttpError('该商品成本不固定,请填写本次实际成本', {
statusCode: 400,
errorCode: 'manual_fulfillment_cost_required',
})
}
const costFen = normalizeCostFen(input.providedCostFen)
if (costFen <= 0) {
throw createHttpError('该商品成本不固定,请填写本次实际成本', {
statusCode: 400,
errorCode: 'manual_fulfillment_cost_required',
})
}
return { costFen, costMode: 'variable' }
}
function mapPending(row: PendingRow) {
const creditQuantity = Number(row.credit_quantity || 0)
const unitPriceFen = Number(row.credit_unit_price_fen || 1)