All files / src/lib search.ts

99.63% Statements 540/542
87.23% Branches 82/94
100% Functions 12/12
99.63% Lines 540/542

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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 5431x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 12x 1x 1x 1x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 4x 4x 35x 35x 35x 35x 12x 12x 12x 12x 12x 12x 12x 12x 35x 35x 35x 35x 35x 35x 140x 87x 87x 53x 35x 35x 35x 35x 35x     35x 35x 35x 35x 35x 35x 2x 2x 35x 1x 1x 35x 1x 1x 1x 35x 1x 1x 1x 35x 35x 30x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 33x 33x 33x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 33x 33x 33x 35x 2x 2x 33x 33x 35x 1x 1x 33x 33x 35x 12x 12x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 35x 2x 2x 2x 35x 1x 1x 1x 1x 1x 6x 6x 6x 6x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 6x 1x 1x 1x 6x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 2x 2x 3x 3x 3x 3x 1x 1x 1x 3x 1x 1x 1x 1x 13x 13x 13x 13x 13x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 3x 1x 1x 1x 3x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 3x 1x 1x 1x 3x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 3x 1x 1x 1x 3x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 4x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 2x 2x 2x 3x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 2x 2x 3x 1x 1x 1x 3x  
export const dynamic = "force-dynamic";
/**
 * Advanced Search & Filtering Utilities
 * Handles full-text search, filtering, and sorting of products
 */
 
import { prisma } from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import { logger } from '@/lib/logging';
 
export interface SearchParams {
  query?: string;
  categories?: number[];
  minPrice?: number;
  maxPrice?: number;
  minRating?: number;
  sortBy?: "price_asc" | "price_desc" | "rating" | "newest" | "popularity";
  page?: number;
  limit?: number;
  inStock?: boolean;
}
 
export interface SearchResult {
  id: number;
  title: string;
  description: string | null;
  price: number;
  discountedPrice: number;
  stock: number;
  rating: number;
  reviewCount: number;
  images: Array<{
    url: string;
    thumbnailUrl: string;
  }>;
}
 
export interface PaginationMeta {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
  hasNextPage: boolean;
  hasPreviousPage: boolean;
}
 
/**
 * Track a search term for analytics
 */
async function trackSearchTerm(term: string, resultsCount: number): Promise<void> {
  if (!term || term.trim().length === 0) return;
 
  const normalizedTerm = term.toLowerCase().trim();
 
  try {
    await prisma.searchTerm.upsert({
      where: { term: normalizedTerm },
      update: {
        count: { increment: 1 },
        lastUsed: new Date(),
        resultsCount},
      create: {
        term: normalizedTerm,
        count: 1,
        resultsCount}});
  } catch (error) {
    // Silently fail - search tracking shouldn't break the search
    logger.error('Failed to track search term', error instanceof Error ? error : new Error(String(error)), { category: 'SEARCH' });
  }
}
 
/**
 * Search for products with advanced filtering and sorting
 */
export async function searchProducts(
  params: SearchParams
): Promise<{
  results: SearchResult[];
  meta: PaginationMeta;
  suggestions?: string[];
}> {
  const {
    query = "",
    categories = [],
    minPrice = 0,
    maxPrice = Infinity,
    minRating = 0,
    sortBy = "newest",
    page = 1,
    limit = 20,
    inStock = false} = params;
 
  // Calculate pagination
  const skip = (page - 1) * limit;
 
  // Build where conditions
  const where: Prisma.ProductWhereInput = {
    AND: [
      // Price range filter
      {
        price: {
          gte: minPrice,
          ...(maxPrice !== Infinity ? { lte: maxPrice } : {})}},
      // Stock filter
      inStock ? { stock: { gt: 0 } } : {},
      // Category filter
      categories.length > 0
        ? {
            categoryId: {
              in: categories}}
        : {},
      // Search query
      query
        ? {
            OR: [
              {
                title: {
                  contains: query}},
              {
                description: {
                  contains: query}},
            ]}
        : {},
    ]};
 
  // Remove empty AND conditions
  if (Array.isArray(where.AND)) {
    where.AND = where.AND.filter((condition) => {
      if (typeof condition === "object" && condition !== null && Object.keys(condition).length === 0) {
        return false;
      }
      return true;
    });
  }
 
  // If AND array is empty, remove it
  if (where.AND && Array.isArray(where.AND) && where.AND.length === 0) {
    delete where.AND;
  }
 
  // Determine sorting
  let orderBy: Prisma.ProductOrderByWithRelationInput = { createdAt: "desc" }; // Default: newest
 
  switch (sortBy) {
    case "price_asc":
      orderBy = { discountedPrice: "asc" };
      break;
    case "price_desc":
      orderBy = { discountedPrice: "desc" };
      break;
    case "rating":
      // Sort by newest first (we'll filter by rating in-memory)
      orderBy = { createdAt: "desc" };
      break;
    case "popularity":
      // Sort by stock (assuming popular items sell more)
      orderBy = { stock: "desc" };
      break;
    case "newest":
    default:
      orderBy = { createdAt: "desc" };
  }
 
  try {
    // Get total count for pagination
    const total = await prisma.product.count({ where });
 
    // Get products
    const products = await prisma.product.findMany({
      where,
      select: {
        id: true,
        title: true,
        description: true,
        price: true,
        discountedPrice: true,
        stock: true,
        images: {
          select: {
            url: true,
            thumbnailUrl: true}},
        reviews: {
          select: {
            rating: true}}},
      orderBy,
      skip,
      take: limit});
 
    // Transform results with calculated fields
    let results: SearchResult[] = products.map((product) => {
      const ratings = product.reviews.map((r) => r.rating);
      const averageRating =
        ratings.length > 0
          ? ratings.reduce((a, b) => a + b, 0) / ratings.length
          : 0;
 
      return {
        id: product.id,
        title: product.title,
        description: product.description,
        price: product.price,
        discountedPrice: product.discountedPrice,
        stock: product.stock,
        rating: Math.round(averageRating * 10) / 10,
        reviewCount: product.reviews.length,
        images: product.images};
    });
 
    // Apply rating filter if specified
    if (minRating > 0) {
      results = results.filter(p => p.rating >= minRating);
    }
 
    // Sort by rating if requested (after filtering)
    if (sortBy === "rating") {
      results.sort((a, b) => b.rating - a.rating);
    }
 
    // Track search term
    if (query) {
      void trackSearchTerm(query, results.length);
    }
 
    // Calculate pagination metadata
    const totalPages = Math.ceil(total / limit);
    const meta: PaginationMeta = {
      page,
      limit,
      total,
      totalPages,
      hasNextPage: page < totalPages,
      hasPreviousPage: page > 1};
 
    return {
      results,
      meta};
  } catch (error) {
    logger.error("Search failed", error instanceof Error ? error : new Error(String(error)), { category: "SEARCH" });
    throw new Error("Search failed");
  }
}
 
/**
 * Get search suggestions based on query
 */
export async function getSearchSuggestions(
  query: string,
  limit: number = 10
): Promise<string[]> {
  if (!query || query.length < 2) {
    return [];
  }
 
  try {
    // Get products that match the query
    const products = await prisma.product.findMany({
      where: {
        OR: [
          {
            title: {
              contains: query}},
          {
            description: {
              contains: query}},
        ]},
      select: {
        title: true},
      take: limit});
 
    // Extract unique titles as suggestions
    const suggestions = [...new Set(products.map((p) => p.title))];
 
    return suggestions;
  } catch (error) {
    logger.error("Suggestions error", error instanceof Error ? error : new Error(String(error)), { category: "SEARCH" });
    return [];
  }
}
 
/**
 * Get available filter options
 */
export async function getFilterOptions(): Promise<{
  categories: Array<{ id: number; title: string; count: number }>;
  priceRange: { min: number; max: number };
  ratings: number[];
}> {
  try {
    // Get categories with product count
    const categories = await prisma.category.findMany({
      select: {
        id: true,
        title: true,
        _count: {
          select: { products: true }}}});
 
    // Get price range
    const priceStats = await prisma.product.aggregate({
      _min: { discountedPrice: true },
      _max: { discountedPrice: true }});
 
    return {
      categories: categories.map((cat) => ({
        id: cat.id,
        title: cat.title,
        count: cat._count.products})),
      priceRange: {
        min: priceStats._min.discountedPrice || 0,
        max: priceStats._max.discountedPrice || 0},
      ratings: [5, 4, 3, 2, 1]};
  } catch (error) {
    logger.error("Filter options error", error instanceof Error ? error : new Error(String(error)), { category: "SEARCH" });
    throw new Error("Failed to fetch filter options");
  }
}
 
/**
 * Calculate average rating for a product
 */
export function calculateAverageRating(reviews: Array<{ rating: number }>): {
  average: number;
  total: number;
} {
  if (reviews.length === 0) {
    return { average: 0, total: 0 };
  }
 
  const sum = reviews.reduce((acc, review) => acc + review.rating, 0);
  const average = Math.round((sum / reviews.length) * 10) / 10;
 
  return {
    average,
    total: reviews.length};
}
 
/**
 * Get popular search terms
 */
export async function getPopularSearchTerms(limit: number = 10): Promise<Array<{
  term: string;
  count: number;
}>> {
  try {
    const searchTerms = await prisma.searchTerm.findMany({
      select: {
        term: true,
        count: true},
      orderBy: {
        count: 'desc'},
      take: limit});
 
    return searchTerms;
  } catch (error) {
    logger.error('Popular search terms error', error instanceof Error ? error : new Error(String(error)), { category: 'SEARCH' });
    return [];
  }
}
 
/**
 * Get trending search terms (recent popular searches)
 */
export async function getTrendingSearchTerms(limit: number = 10): Promise<Array<{
  term: string;
  count: number;
}>> {
  try {
    // Get searches from the last 7 days
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
 
    const searchTerms = await prisma.searchTerm.findMany({
      where: {
        lastUsed: {
          gte: sevenDaysAgo}},
      select: {
        term: true,
        count: true},
      orderBy: {
        count: 'desc'},
      take: limit});
 
    return searchTerms;
  } catch (error) {
    logger.error('Trending search terms error', error instanceof Error ? error : new Error(String(error)), { category: 'SEARCH' });
    return [];
  }
}
 
/**
 * Get search analytics
 */
export async function getSearchAnalytics(): Promise<{
  totalSearches: number;
  uniqueTerms: number;
  avgResultsPerSearch: number;
  topTerms: Array<{ term: string; count: number }>;
  zeroResultTerms: Array<{ term: string; count: number }>;
}> {
  try {
    const [allTerms, topTerms, zeroResultTerms] = await Promise.all([
      prisma.searchTerm.findMany({
        select: {
          count: true,
          resultsCount: true}}),
      prisma.searchTerm.findMany({
        select: {
          term: true,
          count: true},
        orderBy: {
          count: 'desc'},
        take: 10}),
      prisma.searchTerm.findMany({
        where: {
          resultsCount: 0},
        select: {
          term: true,
          count: true},
        orderBy: {
          count: 'desc'},
        take: 10}),
    ]);
 
    const totalSearches = allTerms.reduce((sum, term) => sum + term.count, 0);
    const totalResults = allTerms.reduce((sum, term) => sum + term.resultsCount, 0);
 
    return {
      totalSearches,
      uniqueTerms: allTerms.length,
      avgResultsPerSearch: totalSearches > 0 ? Math.round(totalResults / totalSearches) : 0,
      topTerms,
      zeroResultTerms};
  } catch (error) {
    logger.error('Search analytics error', error instanceof Error ? error : new Error(String(error)), { category: 'SEARCH' });
    return {
      totalSearches: 0,
      uniqueTerms: 0,
      avgResultsPerSearch: 0,
      topTerms: [],
      zeroResultTerms: []};
  }
}
 
/**
 * Clear old search terms (cleanup utility)
 */
export async function clearOldSearchTerms(daysOld: number = 90): Promise<{ deleted: number }> {
  try {
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - daysOld);
 
    const result = await prisma.searchTerm.deleteMany({
      where: {
        lastUsed: {
          lt: cutoffDate},
        count: {
          lt: 5, // Only delete terms with low search count
        }}});
 
    return { deleted: result.count };
  } catch (error) {
    logger.error('Clear search terms error', error instanceof Error ? error : new Error(String(error)), { category: 'SEARCH' });
    return { deleted: 0 };
  }
}
 
/**
 * Search products by category
 */
export async function searchByCategory(
  categoryId: number,
  params: Omit<SearchParams, 'categories'> = {}
): Promise<{
  results: SearchResult[];
  meta: PaginationMeta;
}> {
  return searchProducts({
    ...params,
    categories: [categoryId]});
}
 
/**
 * Get related search terms
 */
export async function getRelatedSearchTerms(query: string, limit: number = 5): Promise<string[]> {
  if (!query || query.length < 2) {
    return [];
  }
 
  try {
    const terms = await prisma.searchTerm.findMany({
      where: {
        term: {
          contains: query.toLowerCase()}},
      select: {
        term: true},
      orderBy: {
        count: 'desc'},
      take: limit});
 
    return terms.map(t => t.term);
  } catch (error) {
    logger.error('Related search terms error', error instanceof Error ? error : new Error(String(error)), { category: 'SEARCH' });
    return [];
  }
}
 
/**
 * Check zero-result searches and update if products now match
 * Returns the number of search terms that now have results
 */
export async function checkZeroResultSearches(): Promise<{ updated: number }> {
  try {
    // Get searches with zero results
    const zeroResultSearches = await prisma.searchTerm.findMany({
      where: { resultsCount: 0 },
      select: { term: true }});
 
    let updated = 0;
 
    for (const search of zeroResultSearches) {
      const { results } = await searchProducts({ query: search.term, limit: 1 });
 
      if (results.length > 0) {
        // Update search term with new result count
        const fullResults = await searchProducts({ query: search.term, limit: 100 });
 
        await prisma.searchTerm.update({
          where: { term: search.term },
          data: { resultsCount: fullResults.results.length }});
 
        // TODO: Optionally notify users who searched for this term
        // Requires tracking user-search associations
        updated++;
      }
    }
 
    return { updated };
  } catch (error) {
    logger.error('Check zero-result searches error', error instanceof Error ? error : new Error(String(error)), { category: 'SEARCH' });
    return { updated: 0 };
  }
}