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 | 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 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x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 3x 5x 5x 5x 5x 5x 3x 3x 3x 3x 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 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 3x 3x 3x 3x 3x 3x 23x 23x 23x 23x 23x 3x 3x 3x 3x 3x 3x | /**
* Revenue Analytics Service
*
* Provides revenue metrics, trends, and forecasting:
* - Daily/weekly/monthly revenue
* - Revenue comparison with previous periods
* - Simple forecasting based on trends
* - Revenue by category/product
*/
import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import {
startOfDay,
startOfWeek,
startOfMonth,
subDays,
subWeeks,
subMonths,
format,
eachDayOfInterval,
eachWeekOfInterval,
eachMonthOfInterval,
} from "date-fns";
export interface RevenueMetrics {
today: number;
yesterday: number;
thisWeek: number;
lastWeek: number;
thisMonth: number;
lastMonth: number;
trend: number; // Percentage change vs previous period
averageOrderValue: number;
totalOrders: number;
}
export interface RevenueTrendPoint {
date: string;
revenue: number;
orders: number;
averageOrderValue: number;
}
export interface RevenueForecast {
predictions: Array<{ date: string; predicted: number; lower: number; upper: number }>;
confidence: number;
growthRate: number;
}
export interface RevenueByCategory {
categoryId: string;
categoryName: string;
revenue: number;
orders: number;
percentage: number;
}
export interface RevenueByProduct {
productId: string;
productName: string;
revenue: number;
unitsSold: number;
percentage: number;
}
/**
* Get comprehensive revenue metrics
*/
export async function getRevenueMetrics(): Promise<RevenueMetrics> {
logger.info("Calculating revenue metrics", { category: "ANALYTICS" });
const now = new Date();
const today = startOfDay(now);
const yesterday = startOfDay(subDays(now, 1));
const thisWeekStart = startOfWeek(now, { weekStartsOn: 0 });
const lastWeekStart = subWeeks(thisWeekStart, 1);
const thisMonthStart = startOfMonth(now);
const lastMonthStart = subMonths(thisMonthStart, 1);
const [
todayRevenue,
yesterdayRevenue,
thisWeekRevenue,
lastWeekRevenue,
thisMonthRevenue,
lastMonthRevenue,
orderStats,
] = await Promise.all([
// Today's revenue
prisma.order.aggregate({
where: {
createdAt: { gte: today },
status: { not: "CANCELLED" },
},
_sum: { total: true },
_count: true,
}),
// Yesterday's revenue
prisma.order.aggregate({
where: {
createdAt: { gte: yesterday, lt: today },
status: { not: "CANCELLED" },
},
_sum: { total: true },
}),
// This week's revenue
prisma.order.aggregate({
where: {
createdAt: { gte: thisWeekStart },
status: { not: "CANCELLED" },
},
_sum: { total: true },
}),
// Last week's revenue
prisma.order.aggregate({
where: {
createdAt: { gte: lastWeekStart, lt: thisWeekStart },
status: { not: "CANCELLED" },
},
_sum: { total: true },
}),
// This month's revenue
prisma.order.aggregate({
where: {
createdAt: { gte: thisMonthStart },
status: { not: "CANCELLED" },
},
_sum: { total: true },
}),
// Last month's revenue
prisma.order.aggregate({
where: {
createdAt: { gte: lastMonthStart, lt: thisMonthStart },
status: { not: "CANCELLED" },
},
_sum: { total: true },
}),
// Overall order stats for AOV
prisma.order.aggregate({
where: {
createdAt: { gte: thisMonthStart },
status: { not: "CANCELLED" },
},
_avg: { total: true },
_count: true,
}),
]);
const currentWeekTotal = Number(thisWeekRevenue._sum.total) || 0;
const previousWeekTotal = Number(lastWeekRevenue._sum.total) || 0;
const trend =
previousWeekTotal > 0
? Math.round(((currentWeekTotal - previousWeekTotal) / previousWeekTotal) * 100 * 10) / 10
: 0;
return {
today: Number(todayRevenue._sum.total) || 0,
yesterday: Number(yesterdayRevenue._sum.total) || 0,
thisWeek: currentWeekTotal,
lastWeek: previousWeekTotal,
thisMonth: Number(thisMonthRevenue._sum.total) || 0,
lastMonth: Number(lastMonthRevenue._sum.total) || 0,
trend,
averageOrderValue: Math.round((Number(orderStats._avg.total) || 0) * 100) / 100,
totalOrders: orderStats._count,
};
}
/**
* Get revenue trend data for charting
*
* @param days - Number of days to include (default: 30)
* @param granularity - 'day' | 'week' | 'month'
*/
export async function getRevenueTrend(
days: number = 30,
granularity: "day" | "week" | "month" = "day"
): Promise<RevenueTrendPoint[]> {
logger.info(`Getting revenue trend for ${days} days with ${granularity} granularity`, { category: "ANALYTICS", days, granularity });
const now = new Date();
const startDate = subDays(startOfDay(now), days);
// Get all orders in the period
const orders = await prisma.order.findMany({
where: {
createdAt: { gte: startDate },
status: { not: "CANCELLED" },
},
select: {
createdAt: true,
total: true,
},
orderBy: { createdAt: "asc" },
});
// Generate date intervals based on granularity
let intervals: Date[];
let formatString: string;
switch (granularity) {
case "week":
intervals = eachWeekOfInterval({ start: startDate, end: now }, { weekStartsOn: 0 });
formatString = "yyyy-'W'ww";
break;
case "month":
intervals = eachMonthOfInterval({ start: startDate, end: now });
formatString = "yyyy-MM";
break;
default:
intervals = eachDayOfInterval({ start: startDate, end: now });
formatString = "yyyy-MM-dd";
}
// Aggregate orders by interval
const aggregated = new Map<string, { revenue: number; orders: number }>();
for (const interval of intervals) {
aggregated.set(format(interval, formatString), { revenue: 0, orders: 0 });
}
for (const order of orders) {
let key: string;
switch (granularity) {
case "week":
key = format(startOfWeek(order.createdAt, { weekStartsOn: 0 }), formatString);
break;
case "month":
key = format(startOfMonth(order.createdAt), formatString);
break;
default:
key = format(order.createdAt, formatString);
}
const existing = aggregated.get(key) || { revenue: 0, orders: 0 };
aggregated.set(key, {
revenue: existing.revenue + Number(order.total),
orders: existing.orders + 1,
});
}
// Convert to array
return Array.from(aggregated.entries()).map(([date, data]) => ({
date,
revenue: Math.round(data.revenue * 100) / 100,
orders: data.orders,
averageOrderValue: data.orders > 0 ? Math.round((data.revenue / data.orders) * 100) / 100 : 0,
}));
}
/**
* Generate simple revenue forecast
*
* Uses linear regression on recent data to predict future revenue
*
* @param daysAhead - Number of days to forecast
* @param historicalDays - Days of historical data to use
*/
export async function getRevenueForecast(
daysAhead: number = 7,
historicalDays: number = 30
): Promise<RevenueForecast> {
logger.info(`Generating ${daysAhead}-day forecast based on ${historicalDays} days of data`, { category: "ANALYTICS", daysAhead, historicalDays });
// Get historical trend data
const historicalData = await getRevenueTrend(historicalDays, "day");
if (historicalData.length < 7) {
// Not enough data for meaningful forecast
return {
predictions: [],
confidence: 0,
growthRate: 0,
};
}
// Calculate linear regression
const n = historicalData.length;
const x = historicalData.map((_, i) => i);
const y = historicalData.map((d) => d.revenue);
const sumX = x.reduce((a, b) => a + b, 0);
const sumY = y.reduce((a, b) => a + b, 0);
const sumXY = x.reduce((sum, xi, i) => sum + xi * y[i], 0);
const sumXX = x.reduce((sum, xi) => sum + xi * xi, 0);
const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
const intercept = (sumY - slope * sumX) / n;
// Calculate standard error for confidence intervals
const predicted = x.map((xi) => slope * xi + intercept);
const residuals = y.map((yi, i) => yi - predicted[i]);
const sse = residuals.reduce((sum, r) => sum + r * r, 0);
const mse = sse / (n - 2);
const standardError = Math.sqrt(mse);
// Calculate R-squared for confidence
const meanY = sumY / n;
const ssTot = y.reduce((sum, yi) => sum + (yi - meanY) ** 2, 0);
const rSquared = 1 - sse / ssTot;
// Generate predictions
const predictions: RevenueForecast["predictions"] = [];
const now = new Date();
for (let i = 1; i <= daysAhead; i++) {
const dayIndex = n + i - 1;
const predictedValue = Math.max(0, slope * dayIndex + intercept);
const margin = 1.96 * standardError; // 95% confidence interval
predictions.push({
date: format(subDays(now, -i), "yyyy-MM-dd"),
predicted: Math.round(predictedValue * 100) / 100,
lower: Math.round(Math.max(0, predictedValue - margin) * 100) / 100,
upper: Math.round((predictedValue + margin) * 100) / 100,
});
}
// Calculate daily growth rate
const avgDaily = sumY / n;
const growthRate = avgDaily > 0 ? (slope / avgDaily) * 100 : 0;
return {
predictions,
confidence: Math.round(Math.max(0, rSquared) * 100),
growthRate: Math.round(growthRate * 10) / 10,
};
}
/**
* Get revenue breakdown by category
*/
export async function getRevenueByCategory(
days: number = 30
): Promise<RevenueByCategory[]> {
logger.info(`Getting revenue by category for ${days} days`, { category: "ANALYTICS", days });
const startDate = subDays(startOfDay(new Date()), days);
// Get order items with category info
const orderItems = await prisma.orderItem.findMany({
where: {
order: {
createdAt: { gte: startDate },
status: { not: "CANCELLED" },
},
},
include: {
product: {
include: {
category: true,
},
},
},
});
// Aggregate by category
const categoryMap = new Map<string, { name: string; revenue: number; orders: number }>();
for (const item of orderItems) {
const categoryId = item.product.category?.id?.toString() || "uncategorized";
const categoryName = item.product.category?.title || "Uncategorized";
const itemRevenue = Number(item.price) * item.quantity;
const existing = categoryMap.get(categoryId) || { name: categoryName, revenue: 0, orders: 0 };
categoryMap.set(categoryId, {
name: categoryName,
revenue: existing.revenue + itemRevenue,
orders: existing.orders + 1,
});
}
// Calculate totals and percentages
const totalRevenue = Array.from(categoryMap.values()).reduce((sum, c) => sum + c.revenue, 0);
const results: RevenueByCategory[] = Array.from(categoryMap.entries())
.map(([id, data]) => ({
categoryId: id,
categoryName: data.name,
revenue: Math.round(data.revenue * 100) / 100,
orders: data.orders,
percentage: totalRevenue > 0 ? Math.round((data.revenue / totalRevenue) * 100 * 10) / 10 : 0,
}))
.sort((a, b) => b.revenue - a.revenue);
return results;
}
/**
* Get top products by revenue
*/
export async function getTopProductsByRevenue(
days: number = 30,
limit: number = 10
): Promise<RevenueByProduct[]> {
logger.info(`Getting top ${limit} products by revenue for ${days} days`, { category: "ANALYTICS", days, limit });
const startDate = subDays(startOfDay(new Date()), days);
// Get order items with product info
const orderItems = await prisma.orderItem.findMany({
where: {
order: {
createdAt: { gte: startDate },
status: { not: "CANCELLED" },
},
},
include: {
product: {
select: {
id: true,
title: true,
},
},
},
});
// Aggregate by product
const productMap = new Map<string, { name: string; revenue: number; unitsSold: number }>();
for (const item of orderItems) {
const productId = item.product.id.toString();
const productName = item.product.title;
const itemRevenue = Number(item.price) * item.quantity;
const existing = productMap.get(productId) || { name: productName, revenue: 0, unitsSold: 0 };
productMap.set(productId, {
name: productName,
revenue: existing.revenue + itemRevenue,
unitsSold: existing.unitsSold + item.quantity,
});
}
// Calculate totals and percentages
const totalRevenue = Array.from(productMap.values()).reduce((sum, p) => sum + p.revenue, 0);
const results: RevenueByProduct[] = Array.from(productMap.entries())
.map(([id, data]) => ({
productId: id,
productName: data.name,
revenue: Math.round(data.revenue * 100) / 100,
unitsSold: data.unitsSold,
percentage: totalRevenue > 0 ? Math.round((data.revenue / totalRevenue) * 100 * 10) / 10 : 0,
}))
.sort((a, b) => b.revenue - a.revenue)
.slice(0, limit);
return results;
}
|