修复:保护平台订单原始事实不被清理和覆盖

This commit is contained in:
yml2213
2026-11-09 13:20:36 +08:00
parent 9ff9eda3b3
commit 4159a435d5
22 changed files with 429 additions and 267 deletions
@@ -13,7 +13,7 @@ type OrderItemSyncPlan = {
item: OrderItemReplaceInput
}>
creates: OrderItemReplaceInput[]
deletes: number[]
surplusExistingIds: number[]
}
type OrderItemIdentityInput = Partial<OrderItemReplaceInput> & Partial<OrderItemRow>
@@ -100,36 +100,6 @@ export async function replaceOrderItemsWithExecutor(
): Promise<OrderItemRow[]> {
const existingItems = await listOrderItemsByOrderIdWithExecutor(executor, orderId)
const plan = resolveOrderItemSyncPlan(existingItems, items)
const existingById = new Map(existingItems.map((item) => [Number(item.id), item]))
for (const update of plan.updates) {
const effectiveItem = preserveAssignedOrderItemState(
existingById.get(Number(update.orderItemId)),
update.item,
)
await executor(
`
UPDATE order_items
SET
sku_code = $1,
sku_name = $2,
quantity = $3,
spec_json = $4::jsonb,
item_snapshot_json = $5::jsonb,
updated_at = $6
WHERE id = $7
`,
[
effectiveItem.skuCode,
effectiveItem.skuName,
update.item.quantity,
safeJsonStringify(effectiveItem.specJson || '{}'),
safeJsonStringify(effectiveItem.itemSnapshotJson || effectiveItem.specJson || '{}'),
effectiveItem.updatedAt,
update.orderItemId,
],
)
}
for (const create of plan.creates) {
await executor(
@@ -158,14 +128,6 @@ export async function replaceOrderItemsWithExecutor(
)
}
if (plan.deletes.length > 0) {
const deletableIds = await listDeletableOrderItemIdsWithExecutor(executor, plan.deletes)
if (deletableIds.length > 0) {
await executor('DELETE FROM order_items WHERE id = ANY($1::bigint[])', [deletableIds])
}
}
return listOrderItemsByOrderIdWithExecutor(executor, orderId)
}
@@ -280,7 +242,9 @@ export function resolveOrderItemSyncPlan(
return {
updates,
creates,
deletes: unmatchedExisting.map((item) => Number(item.id)).filter((value) => value > 0),
surplusExistingIds: unmatchedExisting
.map((item) => Number(item.id))
.filter((value) => value > 0),
}
}
@@ -301,34 +265,6 @@ function buildOrderItemIdentity(item: OrderItemIdentityInput): string {
].join('::')
}
async function listDeletableOrderItemIdsWithExecutor(
executor: QueryExecutor,
orderItemIds: number[],
): Promise<number[]> {
const normalizedIds = Array.isArray(orderItemIds)
? orderItemIds.map((value) => Number(value)).filter((value) => value > 0)
: []
if (normalizedIds.length === 0) {
return []
}
const result = await executor(
`
SELECT oi.id
FROM v_order_item_current oi
LEFT JOIN fulfillment_tasks ft ON ft.order_item_id = oi.id
WHERE oi.id = ANY($1::bigint[])
GROUP BY oi.id
HAVING COUNT(ft.id) = 0
ORDER BY oi.id ASC
`,
[normalizedIds],
)
return result.rows.map((row) => Number(row.id)).filter((value) => value > 0)
}
async function listOrderItemsByOrderIdWithExecutor(
executor: QueryExecutor,
orderId: number | string,