feat(admin): analytics dashboard
Sprint 27. New features/admin/analytics/ module + net-new /:lang/backoffice/analytics route + Dashboard Quick Action. - revenue/orders/avg-order-value/sales-over-time/top-products computed by composing AdminOrdersLocalGateway (Sprint 23's seeded mock orders) - real aggregation over mock data, not a separate fabricated dataset - products/categories counts from AdminProductsLocalGateway/ AdminCategoriesLocalGateway - visitors/funnels/heatmaps render pending-backend badges (no analytics pipeline exists anywhere in this system) rather than fabricated numbers, same convention as the Sprint 19 dashboard's pre-Sprint-23 Orders/Revenue cards - plain div-bar chart (no charting library), 7/30/90-day range toggle, CSV export docs/ADMIN.md + docs/BACKEND.md (new item 16) updated. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
import { Injectable, computed, inject, signal } from '@angular/core';
|
||||
import { take } from 'rxjs/operators';
|
||||
import { AdminAnalyticsDateRange, AdminAnalyticsSeriesPoint, AdminAnalyticsSummary, AdminAnalyticsTopProduct } from '../models/admin-analytics.model';
|
||||
import { AdminOrdersLocalGateway } from '../../orders/services/admin-orders-local.gateway';
|
||||
import { AdminProductsLocalGateway } from '../../products/services/admin-products-local.gateway';
|
||||
import { AdminCategoriesLocalGateway } from '../../categories/services/admin-categories-local.gateway';
|
||||
import { AdminOrder } from '../../orders/models/admin-order.model';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AdminAnalyticsFacade {
|
||||
private readonly ordersGateway = inject(AdminOrdersLocalGateway);
|
||||
private readonly productsGateway = inject(AdminProductsLocalGateway);
|
||||
private readonly categoriesGateway = inject(AdminCategoriesLocalGateway);
|
||||
|
||||
readonly dateRange = signal<AdminAnalyticsDateRange>(30);
|
||||
readonly loading = signal(false);
|
||||
readonly summary = signal<AdminAnalyticsSummary | null>(null);
|
||||
readonly salesSeries = signal<AdminAnalyticsSeriesPoint[]>([]);
|
||||
readonly topProducts = signal<AdminAnalyticsTopProduct[]>([]);
|
||||
|
||||
readonly maxSeriesValue = computed(() => Math.max(1, ...this.salesSeries().map(point => point.value)));
|
||||
|
||||
load(): void {
|
||||
this.loading.set(true);
|
||||
this.ordersGateway.loadOrders({ search: '', status: 'all', page: 1, pageSize: 1000 }).pipe(take(1)).subscribe(orderResult => {
|
||||
const cutoff = Date.now() - this.dateRange() * 24 * 60 * 60 * 1000;
|
||||
const inRange = orderResult.items.filter(order => new Date(order.createdAt).getTime() >= cutoff);
|
||||
|
||||
this.salesSeries.set(this.buildSeries(inRange, this.dateRange()));
|
||||
this.topProducts.set(this.buildTopProducts(inRange));
|
||||
|
||||
const revenueTotal = inRange.reduce((sum, order) => sum + order.total, 0);
|
||||
const ordersCount = inRange.length;
|
||||
|
||||
this.productsGateway.loadProducts({ search: '', categoryId: null, visibility: 'all', stock: 'all', includeArchived: true, sort: 'title', page: 1, pageSize: 1 }).pipe(take(1)).subscribe(productResult => {
|
||||
this.categoriesGateway.loadCategories({ search: '', visibility: 'all', includeDeleted: true }).pipe(take(1)).subscribe(categories => {
|
||||
this.summary.set({
|
||||
revenueTotal,
|
||||
currency: inRange[0]?.currency ?? 'RUB',
|
||||
ordersCount,
|
||||
avgOrderValue: ordersCount > 0 ? Math.round(revenueTotal / ordersCount) : 0,
|
||||
productsCount: productResult.total,
|
||||
categoriesCount: categories.length,
|
||||
});
|
||||
this.loading.set(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
setDateRange(range: AdminAnalyticsDateRange): void {
|
||||
this.dateRange.set(range);
|
||||
this.load();
|
||||
}
|
||||
|
||||
exportCsv(): string {
|
||||
const header = 'Date,Revenue';
|
||||
const rows = this.salesSeries().map(point => `${point.date},${point.value}`);
|
||||
return [header, ...rows].join('\n');
|
||||
}
|
||||
|
||||
private buildSeries(orders: AdminOrder[], days: number): AdminAnalyticsSeriesPoint[] {
|
||||
const buckets = new Map<string, number>();
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
const date = new Date(Date.now() - i * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
|
||||
buckets.set(date, 0);
|
||||
}
|
||||
for (const order of orders) {
|
||||
const date = order.createdAt.slice(0, 10);
|
||||
if (buckets.has(date)) {
|
||||
buckets.set(date, (buckets.get(date) ?? 0) + order.total);
|
||||
}
|
||||
}
|
||||
return [...buckets.entries()].map(([date, value]) => ({ date, value }));
|
||||
}
|
||||
|
||||
private buildTopProducts(orders: AdminOrder[]): AdminAnalyticsTopProduct[] {
|
||||
const map = new Map<string, AdminAnalyticsTopProduct>();
|
||||
for (const order of orders) {
|
||||
for (const item of order.items) {
|
||||
const existing = map.get(item.productId) ?? { productId: item.productId, name: item.name, quantity: 0, revenue: 0 };
|
||||
existing.quantity += item.quantity;
|
||||
existing.revenue += item.price * item.quantity;
|
||||
map.set(item.productId, existing);
|
||||
}
|
||||
}
|
||||
return [...map.values()].sort((left, right) => right.revenue - left.revenue).slice(0, 5);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export type AdminAnalyticsDateRange = 7 | 30 | 90;
|
||||
|
||||
export interface AdminAnalyticsSummary {
|
||||
revenueTotal: number;
|
||||
currency: string;
|
||||
ordersCount: number;
|
||||
avgOrderValue: number;
|
||||
productsCount: number;
|
||||
categoriesCount: number;
|
||||
}
|
||||
|
||||
export interface AdminAnalyticsSeriesPoint {
|
||||
date: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface AdminAnalyticsTopProduct {
|
||||
productId: string;
|
||||
name: string;
|
||||
quantity: number;
|
||||
revenue: number;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<section class="admin-analytics-page">
|
||||
<div class="toolbar">
|
||||
<div class="ranges">
|
||||
@for (range of ranges; track range) {
|
||||
<app-button [variant]="facade.dateRange() === range ? 'primary' : 'secondary'" size="sm" (click)="facade.setDateRange(range)">{{ range }}d</app-button>
|
||||
}
|
||||
</div>
|
||||
<app-button variant="secondary" (click)="exportCsv()">{{ 'adminOrders.export' | translate }}</app-button>
|
||||
</div>
|
||||
|
||||
@if (facade.summary(); as summary) {
|
||||
<div class="summary-grid">
|
||||
<div class="summary-card"><span>{{ 'adminAnalytics.revenue' | translate }}</span><strong>{{ summary.revenueTotal }} {{ summary.currency }}</strong></div>
|
||||
<div class="summary-card"><span>{{ 'adminAnalytics.orders' | translate }}</span><strong>{{ summary.ordersCount }}</strong></div>
|
||||
<div class="summary-card"><span>{{ 'adminAnalytics.avgOrderValue' | translate }}</span><strong>{{ summary.avgOrderValue }} {{ summary.currency }}</strong></div>
|
||||
<div class="summary-card"><span>{{ 'adminAnalytics.products' | translate }}</span><strong>{{ summary.productsCount }}</strong></div>
|
||||
<div class="summary-card"><span>{{ 'adminAnalytics.categories' | translate }}</span><strong>{{ summary.categoriesCount }}</strong></div>
|
||||
<div class="summary-card pending"><span>{{ 'adminAnalytics.visitors' | translate }}</span><app-badge variant="neutral">{{ 'adminAnalytics.pendingBackend' | translate }}</app-badge></div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="card">
|
||||
<h2>{{ 'adminAnalytics.salesChart' | translate }}</h2>
|
||||
<div class="chart">
|
||||
@for (point of facade.salesSeries(); track point.date) {
|
||||
<div class="bar" [style.height.%]="barHeight(point.value)" [title]="point.date + ': ' + point.value"></div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>{{ 'adminAnalytics.topProducts' | translate }}</h2>
|
||||
<app-table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ 'adminProducts.name' | translate }}</th>
|
||||
<th>{{ 'adminAnalytics.quantitySold' | translate }}</th>
|
||||
<th>{{ 'adminAnalytics.revenue' | translate }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (product of facade.topProducts(); track product.productId) {
|
||||
<tr>
|
||||
<td>{{ product.name }}</td>
|
||||
<td>{{ product.quantity }}</td>
|
||||
<td>{{ product.revenue }}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</app-table>
|
||||
</div>
|
||||
|
||||
<div class="card pending-section">
|
||||
<h2>{{ 'adminAnalytics.funnelsHeatmaps' | translate }}</h2>
|
||||
<p><app-badge variant="neutral">{{ 'adminAnalytics.pendingBackend' | translate }}</app-badge> {{ 'adminAnalytics.pendingBackendHint' | translate }}</p>
|
||||
</div>
|
||||
</section>
|
||||
@@ -0,0 +1,13 @@
|
||||
.admin-analytics-page { display: grid; gap: 16px; padding: 16px; max-width: 1100px; margin: 0 auto; }
|
||||
.toolbar { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
|
||||
.ranges { display: flex; gap: 6px; }
|
||||
.summary-grid { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 10px; }
|
||||
.summary-card { border: 1px solid var(--border-color, #d3dad9); border-radius: 12px; padding: 12px; display: grid; gap: 4px; background: #fff; }
|
||||
.summary-card span { font-size: 0.75rem; color: var(--text-secondary, #6b7280); }
|
||||
.summary-card strong { font-size: 1.1rem; }
|
||||
.card { display: grid; gap: 12px; padding: 16px; border: 1px solid var(--border-color, #d3dad9); border-radius: 16px; background: #fff; }
|
||||
.card h2 { margin: 0; font-size: 1.1rem; }
|
||||
.chart { display: flex; align-items: flex-end; gap: 3px; height: 140px; }
|
||||
.chart .bar { flex: 1; background: var(--color-primary, #2f8f5b); border-radius: 3px 3px 0 0; min-height: 2px; }
|
||||
.pending-section p { display: flex; align-items: center; gap: 8px; margin: 0; color: var(--text-secondary, #6b7280); }
|
||||
@media (max-width: 900px) { .summary-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@@ -0,0 +1,41 @@
|
||||
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { AdminAnalyticsFacade } from '../facade/admin-analytics.facade';
|
||||
import { AdminAnalyticsDateRange } from '../models/admin-analytics.model';
|
||||
import { TranslatePipe } from '../../../../i18n/translate.pipe';
|
||||
import { ButtonComponent } from '../../../../shared/ui/button/button.component';
|
||||
import { BadgeComponent } from '../../../../shared/ui/badge/badge.component';
|
||||
import { TableComponent } from '../../../../shared/ui/table/table.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-admin-analytics-page',
|
||||
standalone: true,
|
||||
imports: [CommonModule, TranslatePipe, ButtonComponent, BadgeComponent, TableComponent],
|
||||
templateUrl: './admin-analytics-page.component.html',
|
||||
styleUrls: ['./admin-analytics-page.component.scss'],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
})
|
||||
export class AdminAnalyticsPageComponent {
|
||||
readonly facade = inject(AdminAnalyticsFacade);
|
||||
|
||||
readonly ranges: AdminAnalyticsDateRange[] = [7, 30, 90];
|
||||
|
||||
constructor() {
|
||||
this.facade.load();
|
||||
}
|
||||
|
||||
barHeight(value: number): number {
|
||||
return Math.max(2, Math.round((value / this.facade.maxSeriesValue()) * 100));
|
||||
}
|
||||
|
||||
exportCsv(): void {
|
||||
const csv = this.facade.exportCsv();
|
||||
const blob = new Blob([csv], { type: 'text/csv' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = 'sales.csv';
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user