All files / src/lib/database batch.ts

63.7% Statements 158/248
83.33% Branches 20/24
50% Functions 3/6
63.7% Lines 158/248

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 2491x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 152x 152x 4x 4x 4x             4x 4x 4x 4x 4x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                           1x 1x 1x 1x 1x                                                                             1x 1x 1x 1x 1x                                                                    
/**
 * Batch Operation Utilities
 *
 * Provides efficient batch operations for database updates,
 * deletes, and upserts to minimize the number of database roundtrips.
 */
 
import { prisma } from '@/lib/prisma';
import { Prisma } from '@prisma/client';
 
export interface BatchResult {
  success: boolean;
  count: number;
  errors?: string[];
}
 
/**
 * Batch update multiple records efficiently
 *
 * @example
 * await batchUpdate(
 *   prisma.product,
 *   [1, 2, 3],
 *   { status: 'INACTIVE' }
 * );
 */
export async function batchUpdate<T>(
  model: {
    updateMany: (args: { where: { id: { in: number[] } }; data: T }) => Promise<{ count: number }>;
  },
  ids: number[],
  data: T
): Promise<BatchResult> {
  if (ids.length === 0) {
    return { success: true, count: 0 };
  }
 
  try {
    const result = await model.updateMany({
      where: { id: { in: ids } },
      data});
 
    return {
      success: true,
      count: result.count};
  } catch (error) {
    return {
      success: false,
      count: 0,
      errors: [error instanceof Error ? error.message : 'Unknown error']};
  }
}
 
/**
 * Batch delete multiple records efficiently
 *
 * @example
 * await batchDelete(prisma.review, [1, 2, 3]);
 */
export async function batchDelete(
  model: {
    deleteMany: (args: { where: { id: { in: number[] } } }) => Promise<{ count: number }>;
  },
  ids: number[]
): Promise<BatchResult> {
  if (ids.length === 0) {
    return { success: true, count: 0 };
  }
 
  try {
    const result = await model.deleteMany({
      where: { id: { in: ids } }});
 
    return {
      success: true,
      count: result.count};
  } catch (error) {
    return {
      success: false,
      count: 0,
      errors: [error instanceof Error ? error.message : 'Unknown error']};
  }
}
 
/**
 * Batch upsert operations using a transaction
 *
 * @example
 * await batchUpsert(prisma.product, items, 'sku');
 */
export async function batchUpsert<
  CreateInput,
  UpdateInput,
  WhereUniqueInput
>(
  model: {
    upsert: (args: {
      where: WhereUniqueInput;
      create: CreateInput;
      update: UpdateInput;
    }) => Promise<unknown>;
  },
  items: Array<{
    where: WhereUniqueInput;
    create: CreateInput;
    update: UpdateInput;
  }>,
  options?: { batchSize?: number }
): Promise<BatchResult> {
  if (items.length === 0) {
    return { success: true, count: 0 };
  }
 
  const batchSize = options?.batchSize ?? 100;
  const errors: string[] = [];
  let totalCount = 0;
 
  // Process in batches to avoid transaction size limits
  for (let i = 0; i < items.length; i += batchSize) {
    const batch = items.slice(i, i + batchSize);
 
    try {
      // Use sequential processing within transaction to avoid type issues
      await prisma.$transaction(async () => {
        for (const item of batch) {
          await model.upsert(item);
        }
      });
      totalCount += batch.length;
    } catch (error) {
      errors.push(
        `Batch ${Math.floor(i / batchSize) + 1} failed: ${
          error instanceof Error ? error.message : 'Unknown error'
        }`
      );
    }
  }
 
  return {
    success: errors.length === 0,
    count: totalCount,
    errors: errors.length > 0 ? errors : undefined};
}
 
/**
 * Execute multiple related operations in a transaction
 *
 * @example
 * await transactionalBatch([
 *   prisma.product.update({ where: { id: 1 }, data: { stock: 0 } }),
 *   prisma.stockMovement.create({ data: { productId: 1, quantity: -10, type: 'SALE' } }),
 * ]);
 */
export async function transactionalBatch<T extends Prisma.PrismaPromise<unknown>[]>(
  operations: [...T]
): Promise<{ success: boolean; results?: Prisma.Overwrite<T, unknown[]>; error?: string }> {
  try {
    const results = await prisma.$transaction(operations);
    return {
      success: true,
      results: results as Prisma.Overwrite<T, unknown[]>};
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error'};
  }
}
 
/**
 * Soft delete products by marking them as inactive and logging the action
 */
export async function softDeleteProducts(
  productIds: number[],
  deletedById?: number,
  reason?: string
): Promise<BatchResult> {
  if (productIds.length === 0) {
    return { success: true, count: 0 };
  }

  try {
    // Use a transaction to update products and create stock movements
    const result = await prisma.$transaction(async (tx) => {
      // Update products to 0 stock (soft delete equivalent for products)
      const updated = await tx.product.updateMany({
        where: { id: { in: productIds } },
        data: { stock: 0 }});

      // Create stock movement records for audit trail
      await tx.stockMovement.createMany({
        data: productIds.map(productId => ({
          productId,
          quantity: 0,
          type: 'ADJUSTMENT',
          reason: reason || 'Product soft deleted',
          createdBy: deletedById?.toString()}))});

      return updated.count;
    });

    return {
      success: true,
      count: result};
  } catch (error) {
    return {
      success: false,
      count: 0,
      errors: [error instanceof Error ? error.message : 'Unknown error']};
  }
}
 
/**
 * Bulk update product prices with percentage discount
 */
export async function bulkPriceUpdate(
  productIds: number[],
  discountPercentage: number
): Promise<BatchResult> {
  if (productIds.length === 0) {
    return { success: true, count: 0 };
  }

  try {
    // Fetch current prices
    const products = await prisma.product.findMany({
      where: { id: { in: productIds } },
      select: { id: true, price: true }});

    // Calculate and update discounted prices
    const result = await prisma.$transaction(
      products.map(product =>
        prisma.product.update({
          where: { id: product.id },
          data: {
            discountedPrice: product.price * (1 - discountPercentage / 100)}})
      )
    );

    return {
      success: true,
      count: result.length};
  } catch (error) {
    return {
      success: false,
      count: 0,
      errors: [error instanceof Error ? error.message : 'Unknown error']};
  }
}