41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
import { db } from '../db/db_index'
|
|
import { orders, orderItems, orderStatus, payments, refunds, couponUsage, complaints } from '../db/schema'
|
|
import { inArray } from 'drizzle-orm'
|
|
import { runBatched } from './run-batched'
|
|
|
|
/**
|
|
* Delete orders and all their related records
|
|
* @param orderIds Array of order IDs to delete
|
|
* @returns Promise<void>
|
|
* @throws Error if deletion fails
|
|
*/
|
|
export async function deleteOrdersWithRelations(orderIds: number[]): Promise<void> {
|
|
if (orderIds.length === 0) {
|
|
return
|
|
}
|
|
|
|
await runBatched(db, orderIds, 10, async (tx, chunk) => {
|
|
// Delete child records first (in correct order to avoid FK constraint errors)
|
|
|
|
// 1. Delete coupon usage records
|
|
await tx.delete(couponUsage).where(inArray(couponUsage.orderId, chunk))
|
|
|
|
// 2. Delete complaints related to these orders
|
|
await tx.delete(complaints).where(inArray(complaints.orderId, chunk))
|
|
|
|
// 3. Delete refunds
|
|
await tx.delete(refunds).where(inArray(refunds.orderId, chunk))
|
|
|
|
// 4. Delete payments
|
|
await tx.delete(payments).where(inArray(payments.orderId, chunk))
|
|
|
|
// 5. Delete order status records
|
|
await tx.delete(orderStatus).where(inArray(orderStatus.orderId, chunk))
|
|
|
|
// 6. Delete order items
|
|
await tx.delete(orderItems).where(inArray(orderItems.orderId, chunk))
|
|
|
|
// 7. Finally delete the orders themselves
|
|
await tx.delete(orders).where(inArray(orders.id, chunk))
|
|
})
|
|
}
|