fix(orders): 订单项替换统一分摊收入

This commit is contained in:
yml2213
2026-11-06 17:27:19 +08:00
parent df7f651542
commit 91e0bc8c9a
2 changed files with 33 additions and 3 deletions
@@ -1,5 +1,6 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import {
preserveAssignedOrderItemState,
@@ -202,3 +203,19 @@ test('已分配订单重推写库时不会用平台新 SKU 覆盖冻结值', asy
assert.equal(updateParams[0]?.[0], 'lucky_coin_x2')
assert.equal(updateParams[0]?.[1], '幸运币2个')
})
test('所有替换订单项入口都在同一事务内分摊订单收入', async () => {
const source = await readFile(new URL('./order-item-repo.ts', import.meta.url), 'utf8')
const replaceSource = source.slice(
source.indexOf('export async function replaceOrderItems('),
source.indexOf('export async function applyOrderItemRevenueAllocationWithExecutor('),
)
assert.ok(replaceSource.includes('withTransaction'))
assert.ok(replaceSource.includes('applyOrderItemRevenueAllocationWithExecutor'))
assert.ok(replaceSource.includes('SELECT total_amount FROM orders'))
assert.ok(
replaceSource.indexOf('replaceOrderItemsWithExecutor') <
replaceSource.indexOf('applyOrderItemRevenueAllocationWithExecutor'),
)
})
@@ -42,9 +42,22 @@ export async function replaceOrderItems(
orderId: number | string,
items: OrderItemReplaceInput[],
): Promise<OrderItemRow[]> {
return withTransaction((client: PoolClient) =>
replaceOrderItemsWithExecutor(client.query.bind(client), orderId, items),
)
return withTransaction(async (client: PoolClient) => {
const executor = client.query.bind(client)
await replaceOrderItemsWithExecutor(executor, orderId, items)
const order = await client.query<{ total_amount: string | number }>(
`SELECT total_amount FROM orders WHERE id = $1`,
[orderId],
)
if (order.rows[0]) {
await applyOrderItemRevenueAllocationWithExecutor(
executor,
orderId,
Number(order.rows[0].total_amount) || 0,
)
}
return listOrderItemsByOrderIdWithExecutor(executor, orderId)
})
}
export async function applyOrderItemRevenueAllocationWithExecutor(