All files / src/lib analytics.ts

69.73% Statements 364/522
94.82% Branches 55/58
66.66% Functions 4/6
69.73% Lines 364/522

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 5231x 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 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 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 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 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 132x 132x 132x 132x 132x 5x 5x 93x 93x 93x 93x 93x 5x 5x 5x 5x 132x 132x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 3x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                       1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 13x 13x 13x 13x 5x 5x 5x 5x 5x 5x 5x 5x 5x 13x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 1x 1x 1x 1x 1x                                        
export const dynamic = "force-dynamic";
/**
 * Analytics System Utilities
 * Provides data aggregation and analysis for admin dashboard
 */
 
import { prisma } from "@/lib/prisma";
import { getLowStockAlerts } from '@/lib/ecommerce';
import { getCached, setCached } from '@/lib/core';
 
export interface DashboardOverview {
  totalRevenue: number;
  totalOrders: number;
  totalCustomers: number;
  totalProducts: number;
  revenueGrowth: number;
  orderGrowth: number;
  customerGrowth: number;
  outOfStockProducts: number;
}
 
export interface OrderMetrics {
  total: number;
  processing: number;
  shipped: number;
  delivered: number;
  cancelled: number;
  averageOrderValue: number;
  totalRevenue: number;
}
 
export interface SalesAnalytics {
  dailySales: Array<{ date: string; orders: number; revenue: number }>;
  weeklySales: Array<{ week: string; orders: number; revenue: number }>;
  monthlySales: Array<{ month: string; orders: number; revenue: number }>;
  salesTrend: "up" | "down" | "stable";
  trendPercentage: number;
}
 
export interface ProductAnalytics {
  bestSellers: Array<{
    id: number;
    title: string;
    sold: number;
    revenue: number;
    rating: number;
  }>;
  topRated: Array<{
    id: number;
    title: string;
    rating: number;
    reviewCount: number;
  }>;
  lowStock: Array<{
    id: number;
    title: string;
    stock: number;
    reorderLevel: number;
  }>;
  newProducts: Array<{
    id: number;
    title: string;
    createdAt: Date;
    price: number;
  }>;
  categoryPerformance: Array<{
    category: string;
    products: number;
    totalSales: number;
    revenue: number;
  }>;
}
 
export interface CustomerAnalytics {
  totalCustomers: number;
  newCustomers: number;
  returningCustomers: number;
  averageLifetimeValue: number;
  customerRetentionRate: number;
  topCustomers: Array<{
    id: string;
    name: string;
    email: string;
    orderCount: number;
    totalSpent: number;
  }>;
  customerSegments: {
    vip: number; // LTV > $1000
    loyal: number; // 5+ orders
    occasional: number; // 2-4 orders
    oneTime: number; // 1 order
  };
  acquisitionTrend: Array<{
    date: string;
    newCustomers: number;
  }>;
}
 
/**
 * Get dashboard overview metrics
 */
export async function getDashboardOverview(
  dateRange: { startDate: Date; endDate: Date }
): Promise<DashboardOverview> {
  // Check cache first
  const cacheKey = `dashboard:overview:${dateRange.startDate.toISOString()}:${dateRange.endDate.toISOString()}`;
  const cached = await getCached<DashboardOverview>(cacheKey);
  if (cached) return cached;
 
  const { startDate, endDate } = dateRange;
  const previousStartDate = new Date(startDate);
  previousStartDate.setDate(previousStartDate.getDate() - (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
 
  // Current period metrics
  const [orders, customers, products, outOfStock, previousOrders, previousRevenue, previousCustomers] =
    await Promise.all([
      prisma.order.findMany({
        where: {
          createdAt: { gte: startDate, lte: endDate }},
        select: { total: true }}),
      prisma.user.count({
        where: {
          createdAt: { gte: startDate, lte: endDate },
          role: "CUSTOMER"}}),
      prisma.product.count(),
      prisma.product.count({
        where: { stock: 0 }}),
      prisma.order.count({
        where: {
          createdAt: {
            gte: previousStartDate,
            lt: startDate}}}),
      prisma.order.aggregate({
        where: {
          createdAt: {
            gte: previousStartDate,
            lt: startDate}},
        _sum: { total: true }}),
      prisma.user.count({
        where: {
          createdAt: {
            gte: previousStartDate,
            lt: startDate},
          role: "CUSTOMER"}}),
    ]);
 
  const totalRevenue = orders.reduce((sum, order) => sum + order.total, 0);
  const totalOrders = orders.length;
  const totalCustomers = customers;
  const previousRevenueVal = previousRevenue._sum.total || 0;
 
  const revenueGrowth =
    previousRevenueVal > 0
      ? Math.round(((totalRevenue - previousRevenueVal) / previousRevenueVal) * 100)
      : 100;
 
  const orderGrowth =
    previousOrders > 0
      ? Math.round(((totalOrders - previousOrders) / previousOrders) * 100)
      : 100;
 
  const customerGrowth =
    previousCustomers > 0
      ? Math.round(((customers - previousCustomers) / previousCustomers) * 100)
      : 100;
 
  const result = {
    totalRevenue: Math.round(totalRevenue * 100) / 100,
    totalOrders,
    totalCustomers,
    totalProducts: products,
    revenueGrowth,
    orderGrowth,
    customerGrowth,
    outOfStockProducts: outOfStock};
 
  // Cache for 10 minutes
  setCached(cacheKey, result, 10 * 60 * 1000);
 
  return result;
}
 
/**
 * Get order status metrics
 */
export async function getOrderMetrics(): Promise<OrderMetrics> {
  const orders = await prisma.order.findMany({
    select: { status: true, total: true }});
 
  const metrics = {
    total: orders.length,
    processing: orders.filter((o) => o.status === "PROCESSING").length,
    shipped: orders.filter((o) => o.status === "SHIPPED").length,
    delivered: orders.filter((o) => o.status === "DELIVERED").length,
    cancelled: orders.filter((o) => o.status === "CANCELLED").length,
    averageOrderValue:
      orders.length > 0
        ? Math.round((orders.reduce((sum, o) => sum + o.total, 0) / orders.length) * 100) / 100
        : 0,
    totalRevenue: Math.round(orders.reduce((sum, o) => sum + o.total, 0) * 100) / 100};
 
  return metrics;
}
 
/**
 * Get sales analytics with trends
 */
export async function getSalesAnalytics(days: number = 30): Promise<SalesAnalytics> {
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - days);
 
  const orders = await prisma.order.findMany({
    where: {
      createdAt: { gte: startDate }},
    select: { createdAt: true, total: true }});
 
  // Build daily sales
  const dailySalesMap = new Map<string, { orders: number; revenue: number }>();
  for (let i = days; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    const dateStr = date.toISOString().split("T")[0];
    dailySalesMap.set(dateStr, { orders: 0, revenue: 0 });
  }
 
  orders.forEach((order) => {
    const dateStr = order.createdAt.toISOString().split("T")[0];
    const existing = dailySalesMap.get(dateStr) || { orders: 0, revenue: 0 };
    existing.orders += 1;
    existing.revenue += order.total;
    dailySalesMap.set(dateStr, existing);
  });
 
  const dailySales = Array.from(dailySalesMap.entries())
    .map(([date, data]) => ({
      date,
      orders: data.orders,
      revenue: Math.round(data.revenue * 100) / 100}));
 
  // Calculate trend
  const midpoint = Math.floor(days / 2);
  const firstHalf = dailySales.slice(0, midpoint);
  const secondHalf = dailySales.slice(midpoint);
 
  const firstHalfRevenue = firstHalf.reduce((sum, d) => sum + d.revenue, 0);
  const secondHalfRevenue = secondHalf.reduce((sum, d) => sum + d.revenue, 0);
 
  const trendPercentage =
    firstHalfRevenue > 0
      ? Math.round(
          ((secondHalfRevenue - firstHalfRevenue) / firstHalfRevenue) * 100
        )
      : 0;
 
  return {
    dailySales,
    weeklySales: [], // Simplified for now
    monthlySales: [], // Simplified for now
    salesTrend: trendPercentage > 5 ? "up" : trendPercentage < -5 ? "down" : "stable",
    trendPercentage: Math.abs(trendPercentage)};
}
 
/**
 * Get product analytics
 */
export async function getProductAnalytics(): Promise<ProductAnalytics> {
  // Check cache first
  const cacheKey = 'analytics:products';
  const cached = await getCached<ProductAnalytics>(cacheKey);
  if (cached) return cached;

  // Best sellers
  const bestSellers = await prisma.orderItem.groupBy({
    by: ["productId"],
    _sum: { quantity: true },
    _count: { orderId: true },
    orderBy: { _sum: { quantity: "desc" } },
    take: 5});

  const bestSellerDetails = await Promise.all(
    bestSellers.map(async (item) => {
      const product = await prisma.product.findUnique({
        where: { id: item.productId },
        select: {
          title: true,
          price: true,
          discountedPrice: true,
          reviews: { select: { rating: true } }}});

      if (!product) return null;

      const orders = await prisma.orderItem.findMany({
        where: { productId: item.productId },
        select: { price: true }});

      const avgRating =
        product.reviews.length > 0
          ? Math.round(
              (product.reviews.reduce((sum, r) => sum + r.rating, 0) /
                product.reviews.length) *
                10
            ) / 10
          : 0;

      return {
        id: item.productId,
        title: product.title,
        sold: item._sum.quantity || 0,
        revenue:
          Math.round(
            (orders.reduce((sum, oi) => sum + oi.price, 0) *
              (item._sum.quantity || 1)) *
              100
          ) / 100,
        rating: avgRating};
    })
  );

  // Top rated
  const topRated = await prisma.product.findMany({
    select: {
      id: true,
      title: true,
      reviews: { select: { rating: true } }},
    take: 5});

  const topRatedDetails = topRated
    .map((product) => {
      const avgRating =
        product.reviews.length > 0
          ? Math.round(
              (product.reviews.reduce((sum, r) => sum + r.rating, 0) /
                product.reviews.length) *
                10
            ) / 10
          : 0;

      return {
        id: product.id,
        title: product.title,
        rating: avgRating,
        reviewCount: product.reviews.length};
    })
    .filter((p) => p.reviewCount > 0)
    .sort((a, b) => b.rating - a.rating);

  // Low stock - use inventory system for accurate reorder levels
  const lowStockAlerts = await getLowStockAlerts();
  const lowStock = lowStockAlerts.slice(0, 5);

  // New products
  const newProducts = await prisma.product.findMany({
    select: { id: true, title: true, createdAt: true, price: true },
    orderBy: { createdAt: "desc" },
    take: 5});

  // Category performance
  const categories = await prisma.category.findMany({
    select: {
      id: true,
      title: true,
      products: {
        select: {
          id: true,
          orderItems: { select: { quantity: true, price: true } }}}}});

  const categoryPerformance = categories.map((cat) => {
    const totalSales = cat.products.reduce(
      (sum, p) => sum + (p.orderItems?.length || 0),
      0
    );
    const revenue =
      Math.round(
        cat.products.reduce(
          (sum, p) =>
            sum +
            (p.orderItems?.reduce((s, oi) => s + oi.price * oi.quantity, 0) ||
              0),
          0
        ) * 100
      ) / 100;

    return {
      category: cat.title,
      products: cat.products.length,
      totalSales,
      revenue};
  });

  const result = {
    bestSellers: bestSellerDetails.filter((item): item is NonNullable<typeof item> => item !== null && item !== undefined),
    topRated: topRatedDetails,
    lowStock: lowStock.map((alert) => ({
      id: alert.productId,
      title: alert.productTitle,
      stock: alert.currentStock,
      reorderLevel: alert.reorderLevel})),
    newProducts,
    categoryPerformance: categoryPerformance.sort((a, b) => b.revenue - a.revenue)};

  // Cache for 15 minutes
  setCached(cacheKey, result, 15 * 60 * 1000);

  return result;
}
 
/**
 * Get customer analytics
 */
export async function getCustomerAnalytics(): Promise<CustomerAnalytics> {
  const customers = await prisma.user.findMany({
    where: { role: "CUSTOMER" },
    select: {
      id: true,
      name: true,
      email: true,
      createdAt: true,
      orders: { select: { total: true, createdAt: true } }}});
 
  const totalCustomers = customers.length;
  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
 
  const newCustomers = customers.filter((c) => c.createdAt >= thirtyDaysAgo).length;
  const returningCustomers = customers.filter((c) => c.orders.length > 1).length;
 
  const customerLTV = customers.map((c) => ({
    id: c.id.toString(),
    name: c.name || "Unknown",
    email: c.email,
    orderCount: c.orders.length,
    totalSpent: Math.round(c.orders.reduce((sum, o) => sum + o.total, 0) * 100) / 100}));
 
  const avgLTV =
    customerLTV.length > 0
      ? customerLTV.reduce((sum, c) => sum + c.totalSpent, 0) / customerLTV.length
      : 0;
 
  // Customer retention (customers with orders 30+ days apart)
  const retentionCount = customers.filter((c) => {
    if (c.orders.length < 2) return false;
    const sortedOrders = c.orders.sort(
      (a, b) => b.createdAt.getTime() - a.createdAt.getTime()
    );
    const daysBetween =
      (sortedOrders[0].createdAt.getTime() -
        sortedOrders[sortedOrders.length - 1].createdAt.getTime()) /
      (1000 * 60 * 60 * 24);
    return daysBetween >= 30;
  }).length;
 
  const retentionRate =
    returningCustomers > 0
      ? Math.round((retentionCount / returningCustomers) * 100)
      : 0;
 
  // Customer segments
  const vip = customerLTV.filter((c) => c.totalSpent > 1000).length;
  const loyal = customerLTV.filter(
    (c) => c.orderCount >= 5 && c.totalSpent <= 1000
  ).length;
  const occasional = customerLTV.filter(
    (c) => c.orderCount >= 2 && c.orderCount < 5
  ).length;
  const oneTime = customerLTV.filter((c) => c.orderCount === 1).length;
 
  // Acquisition trend (last 30 days)
  const acquisitionTrend = [];
  for (let i = 29; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    const dateStr = date.toISOString().split("T")[0];
    const nextDate = new Date(date);
    nextDate.setDate(nextDate.getDate() + 1);
 
    const count = customers.filter(
      (c) => c.createdAt >= date && c.createdAt < nextDate
    ).length;
 
    acquisitionTrend.push({
      date: dateStr,
      newCustomers: count});
  }
 
  return {
    totalCustomers,
    newCustomers,
    returningCustomers,
    averageLifetimeValue: Math.round(avgLTV * 100) / 100,
    customerRetentionRate: retentionRate,
    topCustomers: customerLTV.sort((a, b) => b.totalSpent - a.totalSpent).slice(0, 10),
    customerSegments: {
      vip,
      loyal,
      occasional,
      oneTime},
    acquisitionTrend};
}
 
/**
 * Generate analytics summary report
 */
export async function getAnalyticsSummary() {
  const dateRange = {
    startDate: new Date(new Date().setDate(new Date().getDate() - 30)),
    endDate: new Date()};

  const [overview, orders, sales, products, customers] = await Promise.all([
    getDashboardOverview(dateRange),
    getOrderMetrics(),
    getSalesAnalytics(30),
    getProductAnalytics(),
    getCustomerAnalytics(),
  ]);

  return {
    overview,
    orders,
    sales,
    products,
    customers};
}