import type { PoolClient, QueryResult } from 'pg' import { query, withTransaction } from '../db/client.js' import type { OrderItemReplaceInput } from '../types/repository/inputs.js' import type { OrderItemRow } from '../types/repository/rows.js' import { safeJsonStringify } from '../utils/json.js' export type QueryExecutor = (text: string, params?: unknown[]) => Promise> type OrderItemSyncPlan = { updates: Array<{ orderItemId: number item: OrderItemReplaceInput }> creates: OrderItemReplaceInput[] deletes: number[] } type OrderItemIdentityInput = Partial & Partial export async function listOrderItemsByOrderId(orderId: number | string): Promise { return listOrderItemsByOrderIdWithExecutor(query, orderId) } export async function listOrderItemsByOrderIds(orderIds: number[]): Promise { const normalizedIds = orderIds.map(Number).filter((value) => value > 0) if (normalizedIds.length === 0) return [] const result = await query( ` SELECT * FROM order_items WHERE order_id = ANY($1::bigint[]) ORDER BY order_id ASC, id ASC `, [normalizedIds], ) return result.rows } export async function replaceOrderItems( orderId: number | string, items: OrderItemReplaceInput[], ): Promise { 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( executor: QueryExecutor, orderId: number | string, totalAmountFen: number, ): Promise { const revenue = Math.max(0, Math.trunc(Number(totalAmountFen) || 0)) const result = await executor( ` WITH ranked AS ( SELECT id, ROW_NUMBER() OVER (ORDER BY id ASC) AS item_rank, (SELECT COUNT(*) FROM order_items WHERE order_id = $1) AS item_count FROM order_items WHERE order_id = $1 ) UPDATE order_items oi SET revenue_amount_fen = CASE WHEN r.item_count = 1 THEN $2::bigint ELSE ($2::bigint / r.item_count) + CASE WHEN r.item_rank = r.item_count THEN ($2::bigint % r.item_count) ELSE 0 END END, revenue_basis = CASE WHEN r.item_count = 1 THEN 'order_total' ELSE 'equal_split' END, updated_at = $3 FROM ranked r WHERE oi.id = r.id `, [orderId, revenue, new Date().toISOString()], ) return result.rowCount || 0 } export async function replaceOrderItemsWithExecutor( executor: QueryExecutor, orderId: number | string, items: OrderItemReplaceInput[], ): Promise { 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( ` INSERT INTO order_items ( order_id, sku_code, sku_name, quantity, spec_json, item_snapshot_json, created_at, updated_at ) VALUES ($1, $2, $3, $4, $5::jsonb, $6::jsonb, $7, $8) `, [ Number(orderId), create.skuCode, create.skuName, create.quantity, safeJsonStringify(create.specJson || '{}'), safeJsonStringify(create.itemSnapshotJson || create.specJson || '{}'), create.createdAt, create.updatedAt, ], ) } 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) } const FROZEN_FULFILLMENT_SNAPSHOT_KEYS = [ 'fulfillmentRoute', 'affiliateDash', 'classification', 'internalSku', 'internalSkuSource', 'internalSkuMappingId', 'internalSkuChannel', 'internalSkuChannelSource', 'internalSkuChannelReason', 'isConfigured', ] as const export function preserveAssignedOrderItemState( existing: OrderItemRow | undefined, incoming: OrderItemReplaceInput, ): OrderItemReplaceInput { if ( !existing || (existing.fulfillment_status !== 'assigned' && existing.fulfillment_status !== 'archived') ) { return incoming } const existingSnapshot = parseJsonObject(existing.item_snapshot_json) const incomingSnapshot = parseJsonObject(incoming.itemSnapshotJson) const frozenSnapshot: Record = {} for (const key of FROZEN_FULFILLMENT_SNAPSHOT_KEYS) { if (Object.prototype.hasOwnProperty.call(existingSnapshot, key)) { frozenSnapshot[key] = existingSnapshot[key] } } const existingSpec = parseJsonObject(existing.spec_json) const incomingSpec = parseJsonObject(incoming.specJson) const frozenInternalSku = String( existingSpec.skuNick || existingSnapshot.internalSku || incomingSpec.skuNick || '', ).trim() return { ...incoming, skuCode: existing.sku_code, skuName: existing.sku_name, specJson: { ...incomingSpec, ...(frozenInternalSku ? { skuNick: frozenInternalSku } : {}), }, itemSnapshotJson: { ...incomingSnapshot, ...frozenSnapshot, }, } } function parseJsonObject(value: unknown): Record { if (value && typeof value === 'object' && !Array.isArray(value)) { return value as Record } try { const parsed = JSON.parse(String(value || '{}')) return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record) : {} } catch { return {} } } export function resolveOrderItemSyncPlan( existingItems: OrderItemRow[], nextItems: OrderItemReplaceInput[], ): OrderItemSyncPlan { const normalizedExisting = Array.isArray(existingItems) ? existingItems : [] const normalizedNext = Array.isArray(nextItems) ? nextItems : [] const unmatchedExisting = [...normalizedExisting] const updates: OrderItemSyncPlan['updates'] = [] const creates: OrderItemReplaceInput[] = [] for (const item of normalizedNext) { const matchedIndex = findMatchingExistingOrderItemIndex(unmatchedExisting, item) if (matchedIndex >= 0) { const matched = unmatchedExisting.splice(matchedIndex, 1)[0] if (!matched) { creates.push(item) continue } updates.push({ orderItemId: matched.id, item, }) continue } if (unmatchedExisting.length > 0) { const matched = unmatchedExisting.shift() if (matched) { updates.push({ orderItemId: matched.id, item, }) } continue } creates.push(item) } return { updates, creates, deletes: unmatchedExisting.map((item) => Number(item.id)).filter((value) => value > 0), } } function findMatchingExistingOrderItemIndex( existingItems: OrderItemRow[], nextItem: OrderItemReplaceInput, ): number { const nextIdentity = buildOrderItemIdentity(nextItem) return existingItems.findIndex((item) => buildOrderItemIdentity(item) === nextIdentity) } function buildOrderItemIdentity(item: OrderItemIdentityInput): string { return [ String(item.skuCode ?? item.sku_code ?? '').trim(), String(item.skuName ?? item.sku_name ?? '').trim(), String(Math.max(1, Number(item.quantity || 1))), ].join('::') } async function listDeletableOrderItemIdsWithExecutor( executor: QueryExecutor, orderItemIds: number[], ): Promise { 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 order_items 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, ): Promise { const result = await executor( ` SELECT * FROM order_items WHERE order_id = $1 ORDER BY id ASC `, [Number(orderId)], ) return result.rows } export async function getOrderItemById(orderItemId: number | string): Promise { const result = await query('SELECT * FROM order_items WHERE id = $1 LIMIT 1', [ Number(orderItemId), ]) return result.rows[0] || null } export async function updateOrderItemSourceSnapshot( orderItemId: number | string, input: { skuName: string; itemSnapshotJson: string; updatedAt: string; specJson?: string }, ): Promise { return withTransaction(async (client) => { const selected = await client.query( `SELECT * FROM order_items WHERE id = $1 FOR UPDATE`, [Number(orderItemId)], ) const existing = selected.rows[0] if (!existing) return null const effectiveItem = preserveAssignedOrderItemState(existing, { skuCode: existing.sku_code, skuName: input.skuName, quantity: existing.quantity, specJson: input.specJson || existing.spec_json || '{}', itemSnapshotJson: input.itemSnapshotJson, createdAt: String(existing.created_at || input.updatedAt), updatedAt: input.updatedAt, }) const specClause = input.specJson ? ', spec_json = $5::jsonb' : '' const params: unknown[] = [ effectiveItem.skuName, effectiveItem.itemSnapshotJson, effectiveItem.updatedAt, Number(orderItemId), ] if (input.specJson) { params.push(safeJsonStringify(effectiveItem.specJson || '{}')) } const result = await client.query( ` UPDATE order_items SET sku_name = $1, item_snapshot_json = $2::jsonb, updated_at = $3 ${specClause} WHERE id = $4 RETURNING * `, params, ) return result.rows[0] || null }) }