All files / src/lib/ecommerce comparison.ts

40.86% Statements 76/186
100% Branches 8/8
42.85% Functions 3/7
40.86% Lines 76/186

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 1871x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 7x 7x 7x 7x 7x 7x 13x 20x 11x 11x 2x 2x 2x 1x 1x 1x 1x 9x 9x 9x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x 1x                                                                                               1x 1x 1x 1x 1x                                                       1x 1x 1x 1x 1x                           1x 1x 1x 1x 1x                                                
/**
 * Product Comparison Utilities
 * Manages product comparison feature
 */
 
import { prisma } from "@/lib/prisma";
 
export interface ComparisonProduct {
  id: number;
  title: string;
  price: number;
  discountedPrice: number;
  description: string | null;
  stock: number;
  rating: number;
  reviewCount: number;
  category: string;
  images: Array<{ url: string }>;
}
 
/**
 * Add products to comparison (max 5)
 */
export function addToComparison(
  current: number[],
  productId: number,
  maxProducts: number = 5
): number[] {
  if (current.length >= maxProducts) {
    // Replace the oldest (first) one
    const updated = [...current];
    updated.shift();
    updated.push(productId);
    return updated;
  }
 
  if (!current.includes(productId)) {
    return [...current, productId];
  }
 
  return current;
}
 
/**
 * Remove product from comparison
 */
export function removeFromComparison(current: number[], productId: number): number[] {
  return current.filter((id) => id !== productId);
}
 
/**
 * Clear all comparisons
 */
export function clearComparison(): number[] {
  return [];
}
 
/**
 * Get products for comparison
 */
export async function getComparisonProducts(
  productIds: number[]
): Promise<ComparisonProduct[]> {
  if (!productIds || productIds.length === 0) {
    return [];
  }

  const products = await prisma.product.findMany({
    where: {
      id: {
        in: productIds}},
    include: {
      category: {
        select: { title: true }},
      images: {
        select: { url: true },
        take: 1},
      reviews: {
        select: { rating: true }}}});

  // Map and add calculated fields
  const mapped: ComparisonProduct[] = products.map((product) => {
    const ratings = product.reviews.map((r) => r.rating);
    const avgRating =
      ratings.length > 0
        ? Math.round((ratings.reduce((a, b) => a + b) / ratings.length) * 10) / 10
        : 0;

    return {
      id: product.id,
      title: product.title,
      price: product.price,
      discountedPrice: product.discountedPrice,
      description: product.description,
      stock: product.stock,
      rating: avgRating,
      reviewCount: ratings.length,
      category: product.category.title,
      images: product.images};
  });

  // Maintain order from input
  const ordered = productIds
    .map((id) => mapped.find((p) => p.id === id))
    .filter((p) => p !== undefined) as ComparisonProduct[];

  return ordered;
}
 
/**
 * Get comparison attributes
 */
export async function getComparisonAttributes(productIds: number[]) {
  const products = await getComparisonProducts(productIds);

  if (products.length === 0) {
    return null;
  }

  // Find min/max for price
  const prices = products.map((p) => p.discountedPrice);
  const minPrice = Math.min(...prices);
  const maxPrice = Math.max(...prices);

  const attributes = {
    price: {
      min: minPrice,
      max: maxPrice,
      range: maxPrice - minPrice},
    categories: [...new Set(products.map((p) => p.category))],
    avgRating: {
      min: Math.min(...products.map((p) => p.rating)),
      max: Math.max(...products.map((p) => p.rating))},
    inStock: products.filter((p) => p.stock > 0).length,
    outOfStock: products.filter((p) => p.stock === 0).length};

  return {
    products,
    attributes};
}
 
/**
 * Check if products can be compared (same category)
 */
export async function canCompareProducts(productIds: number[]): Promise<boolean> {
  if (productIds.length < 2) {
    return false;
  }

  const products = await prisma.product.findMany({
    where: {
      id: { in: productIds }},
    select: { categoryId: true }});

  // Check if all products are in the same category
  const categories = new Set(products.map((p) => p.categoryId));
  return categories.size === 1;
}
 
/**
 * Get related products for comparison
 */
export async function getRelatedComparableProducts(
  productId: number,
  limit: number = 5
) {
  const product = await prisma.product.findUnique({
    where: { id: productId },
    select: { categoryId: true }});

  if (!product) {
    return [];
  }

  const related = await prisma.product.findMany({
    where: {
      categoryId: product.categoryId,
      id: { not: productId }},
    select: {
      id: true,
      title: true,
      discountedPrice: true},
    take: limit});

  return related;
}