fix(fulfillment): 收口渠道商品与统一结算边界

This commit is contained in:
yml2213
2026-11-06 17:12:44 +08:00
parent e6b3835c9f
commit a333c05df4
23 changed files with 1113 additions and 106 deletions
@@ -21,6 +21,7 @@ import {
attachFulfillmentConfigurationsWithExecutor,
transitionFulfillmentStateWithExecutor,
} from '../fulfillment/fulfillment-state-service.js'
import { upsertAggregatedException } from '../cost-center/cost-exception-service.js'
import {
calculateManualCostFen,
normalizeManualCreditQuantity,
@@ -411,6 +412,20 @@ export async function confirmManualFulfillment(payload: JsonObject, session: Adm
errorCode: 'manual_fulfillment_platform_required',
})
}
if (selectedChannel.platformKey === 'on_account') {
const existingBill = await client.query<{ id: number }>(
`SELECT id FROM on_account_bills
WHERE order_item_id = $1 AND status IN ('pending', 'reconciled')
LIMIT 1`,
[orderItemId],
)
if (existingBill.rows[0]) {
throw createHttpError('该订单项已生成统一结算账单,不能重复操作', {
statusCode: 409,
errorCode: 'manual_fulfillment_on_account_already_exists',
})
}
}
// 锁内复查:并发/双击的第二个请求会等锁,醒来后看到快照直接拒绝,不会重复扣款。
const existing = await client.query<{ id: number }>(
@@ -447,6 +462,7 @@ export async function confirmManualFulfillment(payload: JsonObject, session: Adm
providedCostFen,
})
const costFen = costPlan.costFen
const onAccountCostPending = platformKey === 'on_account' && costFen <= 0
const payeeName = optionalText(payload.payeeName ?? payload.payee_name, 120)
const note = optionalText(payload.note, 300)
const fulfillmentReference = buildManualFulfillmentReference({
@@ -455,16 +471,8 @@ export async function confirmManualFulfillment(payload: JsonObject, session: Adm
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',
})
}
// 扣款前先确定最终成本模式。统一结算未填金额时只生成待对账账单,
// 不写 0 元 actual 成本快照,避免利润被虚增。
let fundExpenseId: number | null = null
let creditEntryId: number | null = null
let balanceAfter: number | null = null
@@ -522,11 +530,22 @@ export async function confirmManualFulfillment(payload: JsonObject, session: Adm
subjectSource = 'platform_credit'
}
// subject_id 固定为 order_item_id:不再与 manual_expenses.id /
// platform_credit_entries.id 混用,避免两张表序列撞车。
// subject_type 仍为 manual_case,资金流水只放在 metadata 里。
const snapshot = await client.query<{ id: number }>(
`
let snapshotId: number | null = null
if (!onAccountCostPending) {
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',
})
}
// subject_id 固定为 order_item_id:不再与 manual_expenses.id /
// platform_credit_entries.id 混用,资金流水只放在 metadata 里。
// subject_type 仍为 manual_case。
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,
@@ -540,50 +559,51 @@ export async function confirmManualFulfillment(payload: JsonObject, session: Adm
)
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,
creditOwnerAdminUserId:
platformKey === 'fund_cash'
? null
: Number(payload.creditOwnerAdminUserId || 0) || null,
creditQuantity,
creditUnitPriceFen: unitPriceFen,
costMode: costPlan.costMode,
`,
[
orderItemId,
row.order_id_resolved,
row.work_order_id,
costItemId,
versionId,
row.canonical_product_id,
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',
})
JSON.stringify({
source: 'manual_fulfillment_confirm',
subjectSource,
configId: Number(row.config_id),
platformKey,
platformLabel: PLATFORM_LABELS[platformKey] || platformKey,
creditOwnerAdminUserId:
platformKey === 'fund_cash'
? null
: Number(payload.creditOwnerAdminUserId || 0) || null,
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,
],
)
snapshotId = snapshot.rows[0]?.id ?? null
if (!snapshotId) {
// 订单项唯一索引兜底:任何竞态都会走到这里,抛错回滚本次扣款。
throw createHttpError('该订单项已有人工成本快照,不能重复录入', {
statusCode: 409,
errorCode: 'manual_fulfillment_snapshot_conflict',
})
}
}
if (platformKey === 'on_account') {
@@ -641,30 +661,46 @@ export async function confirmManualFulfillment(payload: JsonObject, session: Adm
reason: platformKey,
})
// 人工缺成本异常立即收口,不等下一轮定时任务。
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],
)
if (onAccountCostPending) {
await upsertAggregatedException({
reason: 'on_account_cost_pending',
scopeKey: `on_account_cost_pending|-|-|${row.internal_sku}|on_account`,
orderItemId,
detail: {
billId: onAccountBillId,
internalSku: row.internal_sku,
platformOrderId: row.platform_order_id,
},
client,
})
} else {
// 人工缺成本异常立即收口,不等下一轮定时任务。
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],
)
}
// v2 聚合异常:删除本条明细,没人再引用的异常头自动关闭。
await client.query(`DELETE FROM cost_exception_items WHERE order_item_id = $1`, [orderItemId])
await client.query(
`
UPDATE cost_exceptions ce
SET status = 'resolved', resolved_at = $1, item_count = 0, last_seen_at = $1
WHERE ce.status <> 'resolved'
AND NOT EXISTS (
SELECT 1 FROM cost_exception_items i WHERE i.exception_id = ce.id
)
`,
[now],
)
if (!onAccountCostPending) {
// v2 聚合异常:成本已经落账后,删除本条明细并自动关闭空异常头。
await client.query(`DELETE FROM cost_exception_items WHERE order_item_id = $1`, [orderItemId])
await client.query(
`
UPDATE cost_exceptions ce
SET status = 'resolved', resolved_at = $1, item_count = 0, last_seen_at = $1
WHERE ce.status <> 'resolved'
AND NOT EXISTS (
SELECT 1 FROM cost_exception_items i WHERE i.exception_id = ce.id
)
`,
[now],
)
}
return {
orderItemId,
@@ -678,6 +714,7 @@ export async function confirmManualFulfillment(payload: JsonObject, session: Adm
creditEntryId,
balanceAfter,
onAccountBillId,
costPending: onAccountCostPending,
}
})
@@ -693,7 +730,7 @@ export async function confirmManualFulfillment(payload: JsonObject, session: Adm
* 事实任务默认只回看最近几天,确认一笔较早的订单时不会自动覆盖,
* 所以这里按该订单自己的业务日期精确重算。
*/
async function refreshFactsForOrderItem(orderItemId: number): Promise<void> {
export async function refreshFactsForOrderItem(orderItemId: number): Promise<void> {
try {
const basis = await query<{ stat_date: string | null }>(
`
@@ -841,7 +878,7 @@ async function matchManualFulfillmentConfigWithClient(client: PoolClient, orderI
return true
}
async function resolveManualCostItemIdWithClient(client: PoolClient) {
export 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`,
)
@@ -855,7 +892,7 @@ async function resolveManualCostItemIdWithClient(client: PoolClient) {
return id
}
async function resolveCostVersionIdWithClient(
export async function resolveCostVersionIdWithClient(
client: PoolClient,
costItemId: number,
row: {