All files / src/lib/analytics/services report.service.ts

100% Statements 397/397
77.77% Branches 14/18
100% Functions 6/6
100% Lines 397/397

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 3981x 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 1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 3x 3x 3x 3x 3x 3x 3x 3x 3x  
/**
 * Report Generation Service
 *
 * Generates analytics reports in various formats:
 * - JSON for API consumption
 * - CSV for spreadsheet export
 * - HTML for email digests
 */
 
import { logger } from "@/lib/logging";
import { format } from "date-fns";
import { getRevenueMetrics, getRevenueTrend, getRevenueByCategory, getTopProductsByRevenue } from "./revenue.service";
import { getCohortAnalysis, getCustomerSegments } from "./cohort.service";
 
export interface ReportData {
  generatedAt: string;
  period: {
    start: string;
    end: string;
  };
  revenue: {
    today: number;
    yesterday: number;
    thisWeek: number;
    lastWeek: number;
    thisMonth: number;
    lastMonth: number;
    trend: number;
    averageOrderValue: number;
    totalOrders: number;
  };
  revenueTrend: Array<{
    date: string;
    revenue: number;
    orders: number;
    averageOrderValue: number;
  }>;
  categoryRevenue: Array<{
    categoryId: string;
    categoryName: string;
    revenue: number;
    orders: number;
    percentage: number;
  }>;
  topProducts: Array<{
    productId: string;
    productName: string;
    revenue: number;
    unitsSold: number;
    percentage: number;
  }>;
  customerSegments: {
    high: { count: number; revenue: number; avgOrderValue: number };
    medium: { count: number; revenue: number; avgOrderValue: number };
    low: { count: number; revenue: number; avgOrderValue: number };
    dormant: { count: number; lastOrderDaysAgo: number };
  };
  cohortSummary: {
    totalUsers: number;
    averageCLV: number;
    averageRetention: number[];
  };
}
 
export type ReportFormat = "json" | "csv" | "html";
 
/**
 * Generate comprehensive analytics report
 *
 * @param startDate - Report start date
 * @param endDate - Report end date
 * @param outputFormat - Output format
 */
export async function generateAnalyticsReport(
  startDate: Date,
  endDate: Date,
  outputFormat: ReportFormat = "json"
): Promise<string | ReportData> {
  logger.info(`Generating ${outputFormat} report from ${startDate.toISOString()} to ${endDate.toISOString()}`, { category: "ANALYTICS", outputFormat, startDate: startDate.toISOString(), endDate: endDate.toISOString() });
 
  const daysDiff = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
 
  // Fetch all data in parallel
  const [
    revenueMetrics,
    revenueTrend,
    categoryRevenue,
    topProducts,
    customerSegments,
    cohortAnalysis,
  ] = await Promise.all([
    getRevenueMetrics(),
    getRevenueTrend(daysDiff),
    getRevenueByCategory(daysDiff),
    getTopProductsByRevenue(daysDiff),
    getCustomerSegments(),
    getCohortAnalysis(6),
  ]);
 
  const reportData: ReportData = {
    generatedAt: new Date().toISOString(),
    period: {
      start: startDate.toISOString(),
      end: endDate.toISOString(),
    },
    revenue: revenueMetrics,
    revenueTrend,
    categoryRevenue,
    topProducts,
    customerSegments,
    cohortSummary: {
      totalUsers: cohortAnalysis.totalUsers,
      averageCLV: cohortAnalysis.averageCLV,
      averageRetention: cohortAnalysis.averageRetention,
    },
  };
 
  switch (outputFormat) {
    case "csv":
      return convertToCSV(reportData);
    case "html":
      return convertToHTML(reportData);
    default:
      return reportData;
  }
}
 
/**
 * Convert report data to CSV format
 */
function convertToCSV(data: ReportData): string {
  const lines: string[] = [];
 
  // Header
  lines.push("Analytics Report");
  lines.push(`Generated: ${data.generatedAt}`);
  lines.push(`Period: ${data.period.start} to ${data.period.end}`);
  lines.push("");
 
  // Revenue Summary
  lines.push("=== Revenue Summary ===");
  lines.push("Metric,Value");
  lines.push(`Today,$${data.revenue.today}`);
  lines.push(`Yesterday,$${data.revenue.yesterday}`);
  lines.push(`This Week,$${data.revenue.thisWeek}`);
  lines.push(`Last Week,$${data.revenue.lastWeek}`);
  lines.push(`This Month,$${data.revenue.thisMonth}`);
  lines.push(`Last Month,$${data.revenue.lastMonth}`);
  lines.push(`Week-over-Week Trend,${data.revenue.trend}%`);
  lines.push(`Average Order Value,$${data.revenue.averageOrderValue}`);
  lines.push(`Total Orders,${data.revenue.totalOrders}`);
  lines.push("");
 
  // Revenue Trend
  lines.push("=== Daily Revenue Trend ===");
  lines.push("Date,Revenue,Orders,AOV");
  for (const day of data.revenueTrend) {
    lines.push(`${day.date},$${day.revenue},${day.orders},$${day.averageOrderValue}`);
  }
  lines.push("");
 
  // Category Revenue
  lines.push("=== Revenue by Category ===");
  lines.push("Category,Revenue,Orders,% of Total");
  for (const cat of data.categoryRevenue) {
    lines.push(`${cat.categoryName},$${cat.revenue},${cat.orders},${cat.percentage}%`);
  }
  lines.push("");
 
  // Top Products
  lines.push("=== Top Products ===");
  lines.push("Product,Revenue,Units Sold,% of Total");
  for (const prod of data.topProducts) {
    lines.push(`"${prod.productName}",$${prod.revenue},${prod.unitsSold},${prod.percentage}%`);
  }
  lines.push("");
 
  // Customer Segments
  lines.push("=== Customer Segments ===");
  lines.push("Segment,Count,Total Revenue,Avg Order Value");
  lines.push(`High Value,${data.customerSegments.high.count},$${data.customerSegments.high.revenue},$${data.customerSegments.high.avgOrderValue}`);
  lines.push(`Medium Value,${data.customerSegments.medium.count},$${data.customerSegments.medium.revenue},$${data.customerSegments.medium.avgOrderValue}`);
  lines.push(`Low Value,${data.customerSegments.low.count},$${data.customerSegments.low.revenue},$${data.customerSegments.low.avgOrderValue}`);
  lines.push(`Dormant (${data.customerSegments.dormant.lastOrderDaysAgo}+ days),${data.customerSegments.dormant.count},-,-`);
  lines.push("");
 
  // Cohort Summary
  lines.push("=== Cohort Summary ===");
  lines.push(`Total Users,${data.cohortSummary.totalUsers}`);
  lines.push(`Average CLV,$${data.cohortSummary.averageCLV}`);
  if (data.cohortSummary.averageRetention.length > 0) {
    lines.push(`Month 1 Retention,${data.cohortSummary.averageRetention[0]}%`);
  }
 
  return lines.join("\n");
}
 
/**
 * Convert report data to HTML format for email digests
 */
function convertToHTML(data: ReportData): string {
  const formatCurrency = (value: number) => `$${value.toFixed(2)}`;
  const formatDate = (dateStr: string) => format(new Date(dateStr), "MMM d, yyyy");
 
  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Analytics Report</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
    .container { max-width: 800px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
    .header { background: #1e3a8a; color: white; padding: 24px; }
    .header h1 { margin: 0 0 8px 0; font-size: 24px; }
    .header p { margin: 0; opacity: 0.8; font-size: 14px; }
    .content { padding: 24px; }
    .section { margin-bottom: 32px; }
    .section h2 { font-size: 18px; color: #1e3a8a; margin: 0 0 16px 0; padding-bottom: 8px; border-bottom: 2px solid #e5e7eb; }
    .metrics-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
    .metric-card { background: #f9fafb; padding: 16px; border-radius: 8px; text-align: center; }
    .metric-value { font-size: 24px; font-weight: bold; color: #1e3a8a; }
    .metric-label { font-size: 12px; color: #6b7280; margin-top: 4px; }
    .metric-change { font-size: 12px; margin-top: 4px; }
    .metric-change.positive { color: #10b981; }
    .metric-change.negative { color: #ef4444; }
    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 12px; text-align: left; border-bottom: 1px solid #e5e7eb; }
    th { background: #f9fafb; font-weight: 600; color: #374151; font-size: 12px; text-transform: uppercase; }
    td { font-size: 14px; color: #4b5563; }
    .text-right { text-align: right; }
    .footer { background: #f9fafb; padding: 16px 24px; text-align: center; font-size: 12px; color: #6b7280; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>📊 Analytics Report</h1>
      <p>Generated on ${formatDate(data.generatedAt)} | Period: ${formatDate(data.period.start)} - ${formatDate(data.period.end)}</p>
    </div>
 
    <div class="content">
      <div class="section">
        <h2>💰 Revenue Overview</h2>
        <div class="metrics-grid">
          <div class="metric-card">
            <div class="metric-value">${formatCurrency(data.revenue.today)}</div>
            <div class="metric-label">Today</div>
          </div>
          <div class="metric-card">
            <div class="metric-value">${formatCurrency(data.revenue.thisWeek)}</div>
            <div class="metric-label">This Week</div>
            <div class="metric-change ${data.revenue.trend >= 0 ? "positive" : "negative"}">
              ${data.revenue.trend >= 0 ? "↑" : "↓"} ${Math.abs(data.revenue.trend)}% vs last week
            </div>
          </div>
          <div class="metric-card">
            <div class="metric-value">${formatCurrency(data.revenue.thisMonth)}</div>
            <div class="metric-label">This Month</div>
          </div>
        </div>
        <div class="metrics-grid" style="margin-top: 16px;">
          <div class="metric-card">
            <div class="metric-value">${data.revenue.totalOrders}</div>
            <div class="metric-label">Total Orders</div>
          </div>
          <div class="metric-card">
            <div class="metric-value">${formatCurrency(data.revenue.averageOrderValue)}</div>
            <div class="metric-label">Avg Order Value</div>
          </div>
          <div class="metric-card">
            <div class="metric-value">${data.cohortSummary.totalUsers}</div>
            <div class="metric-label">Total Customers</div>
          </div>
        </div>
      </div>
 
      <div class="section">
        <h2>📦 Top Categories</h2>
        <table>
          <thead>
            <tr>
              <th>Category</th>
              <th class="text-right">Revenue</th>
              <th class="text-right">Orders</th>
              <th class="text-right">% of Total</th>
            </tr>
          </thead>
          <tbody>
            ${data.categoryRevenue.slice(0, 5).map((cat) => `
              <tr>
                <td>${cat.categoryName}</td>
                <td class="text-right">${formatCurrency(cat.revenue)}</td>
                <td class="text-right">${cat.orders}</td>
                <td class="text-right">${cat.percentage}%</td>
              </tr>
            `).join("")}
          </tbody>
        </table>
      </div>
 
      <div class="section">
        <h2>⭐ Top Products</h2>
        <table>
          <thead>
            <tr>
              <th>Product</th>
              <th class="text-right">Revenue</th>
              <th class="text-right">Units Sold</th>
              <th class="text-right">% of Total</th>
            </tr>
          </thead>
          <tbody>
            ${data.topProducts.slice(0, 5).map((prod) => `
              <tr>
                <td>${prod.productName}</td>
                <td class="text-right">${formatCurrency(prod.revenue)}</td>
                <td class="text-right">${prod.unitsSold}</td>
                <td class="text-right">${prod.percentage}%</td>
              </tr>
            `).join("")}
          </tbody>
        </table>
      </div>
 
      <div class="section">
        <h2>👥 Customer Segments</h2>
        <div class="metrics-grid">
          <div class="metric-card">
            <div class="metric-value">${data.customerSegments.high.count}</div>
            <div class="metric-label">High Value</div>
            <div style="font-size: 12px; color: #10b981; margin-top: 4px;">
              ${formatCurrency(data.customerSegments.high.revenue)} total
            </div>
          </div>
          <div class="metric-card">
            <div class="metric-value">${data.customerSegments.medium.count}</div>
            <div class="metric-label">Medium Value</div>
            <div style="font-size: 12px; color: #3b82f6; margin-top: 4px;">
              ${formatCurrency(data.customerSegments.medium.revenue)} total
            </div>
          </div>
          <div class="metric-card">
            <div class="metric-value">${data.customerSegments.low.count}</div>
            <div class="metric-label">Low Value</div>
            <div style="font-size: 12px; color: #6b7280; margin-top: 4px;">
              ${formatCurrency(data.customerSegments.low.revenue)} total
            </div>
          </div>
        </div>
        ${data.customerSegments.dormant.count > 0 ? `
          <p style="margin-top: 16px; padding: 12px; background: #fef3c7; border-radius: 8px; font-size: 14px; color: #92400e;">
            ⚠️ <strong>${data.customerSegments.dormant.count} dormant customers</strong>
            haven't ordered in ${data.customerSegments.dormant.lastOrderDaysAgo}+ days on average.
            Consider a re-engagement campaign!
          </p>
        ` : ""}
      </div>
    </div>
 
    <div class="footer">
      <p>This report was automatically generated. View the full dashboard for more insights.</p>
    </div>
  </div>
</body>
</html>
  `.trim();
}
 
/**
 * Schedule weekly report email
 *
 * This would be called by a cron job
 */
export async function scheduleWeeklyReport(adminEmails: string[]): Promise<void> {
  logger.info(`Scheduling weekly report for ${adminEmails.length} admins`, { category: "ANALYTICS", recipientCount: adminEmails.length });
 
  const now = new Date();
  const lastWeek = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
 
  const htmlReport = await generateAnalyticsReport(lastWeek, now, "html");
 
  // In a real implementation, this would use the email service
  logger.info("Weekly report generated", {
    category: "ANALYTICS",
    recipients: adminEmails.length,
    reportSize: typeof htmlReport === "string" ? htmlReport.length : 0,
  });
 
  // TODO: Integrate with email service (Plan 61)
  // await sendEmail({
  //   to: adminEmails,
  //   subject: `Weekly Analytics Report - ${format(now, 'MMM d, yyyy')}`,
  //   html: htmlReport as string,
  // });
}