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:
@@ -391,6 +391,31 @@ routes at all, this is a net-new admin section.
|
||||
audit and Sprint 25's per-user audit. No consolidation attempted - they
|
||||
track different things.
|
||||
|
||||
## Sprint 27 - Analytics
|
||||
|
||||
`features/admin/analytics/`, net-new `/:lang/backoffice/analytics` route
|
||||
+ Dashboard Quick Action.
|
||||
|
||||
- **Real, derived data**: revenue/orders/avg-order-value/sales-over-time
|
||||
chart/top-products are computed by composing the existing
|
||||
`AdminOrdersLocalGateway` (Sprint 23's seeded mock orders) - not a
|
||||
separate fabricated dataset. Products/Categories counts come from
|
||||
`AdminProductsLocalGateway`/`AdminCategoriesLocalGateway`. All of this is
|
||||
still ultimately backed by mock order/product/category data (per those
|
||||
sprints), but the *aggregation* is real arithmetic over that data, not
|
||||
invented numbers.
|
||||
- **Visitors, funnels, heatmaps**: no analytics/tracking pipeline exists
|
||||
anywhere in this codebase, so these render an explicit
|
||||
"Awaiting backend integration" (`pending-backend`) badge, same convention
|
||||
as the Sprint 19 dashboard's Orders/Revenue cards before Sprint 23 -
|
||||
not fabricated numbers, not a generic empty state.
|
||||
- **Chart**: a plain inline `<div>`-bar chart driven by `[style.height.%]`,
|
||||
no charting library pulled in - reasonable for one sales-over-time series
|
||||
at this scale; revisit if more chart types are actually needed.
|
||||
- **Date ranges**: 7/30/90-day toggle filters orders by `createdAt`.
|
||||
- **Export**: CSV of the sales series (client-side `Blob` download, same
|
||||
pattern as Orders/Transactions).
|
||||
|
||||
## Known gaps / backend needs
|
||||
|
||||
- **Dashboard metrics endpoint.** Categories/Products counts are computed
|
||||
|
||||
@@ -168,6 +168,14 @@ Plus, if authenticated history/wishlist/compare/saved-searches sync is wanted: `
|
||||
|
||||
**Frontend files:** implement `AdminMonitoringApiGateway`-equivalent methods against a to-be-defined `AdminMonitoringGateway` interface (`AdminMonitoringLocalGateway` currently has no interface extracted — add one when a real implementation is built, mirroring the pattern used everywhere else in `admin/*`).
|
||||
|
||||
## 16. Analytics - visitors/funnels/heatmaps (Sprint 27, no backend at all)
|
||||
|
||||
**Current behavior:** `features/admin/analytics/` computes real revenue/orders/top-products aggregations from the existing mock order data (see item 7), but visitor traffic, conversion funnels, and heatmaps have zero data source anywhere in this system (no analytics/tracking pipeline, no event collection) — these render `pending-backend` badges rather than fabricated numbers.
|
||||
|
||||
**Needed:** a traffic/event tracking pipeline (page views, sessions, conversion events) and a funnel/heatmap aggregation service, before this section of the Analytics page can show anything real.
|
||||
|
||||
**Frontend files:** `features/admin/analytics/pages/admin-analytics-page.component.html` currently renders the pending-backend badge inline (no gateway method exists for this yet, unlike every other mocked domain in this doc).
|
||||
|
||||
## Known reliability issues
|
||||
|
||||
### Production 502/504 Bad Gateway on refresh / back-navigation
|
||||
|
||||
@@ -64,8 +64,9 @@ Notify user: **from Sprint 20 (Categories) once product↔category link + admin
|
||||
- [x] `docs/ADMIN.md` (new Sprint 26 section), `docs/BACKEND.md` item 15 added
|
||||
- Commit: `feat(admin): monitoring center`
|
||||
|
||||
## Sprint 27 — Analytics
|
||||
- [ ] Dashboard extensions: sales/revenue/orders/visitors/products/categories charts, date ranges, export
|
||||
## Sprint 27 — Analytics ✅ done
|
||||
- [x] Sales/revenue/orders/products/categories (real aggregation over mock order data), visitors/funnels/heatmaps (pending-backend badges, no fabricated data), sales-over-time bar chart, 7/30/90-day ranges, CSV export
|
||||
- [x] `docs/ADMIN.md` (new Sprint 27 section), `docs/BACKEND.md` item 16 added
|
||||
- Commit: `feat(admin): analytics dashboard`
|
||||
|
||||
## Sprint 28 — Marketplace Polish
|
||||
|
||||
@@ -116,6 +116,10 @@ const coreRoutes: Routes = [
|
||||
path: 'monitoring',
|
||||
loadComponent: () => import('./features/admin/monitoring/pages/admin-monitoring-page.component').then(m => m.AdminMonitoringPageComponent)
|
||||
},
|
||||
{
|
||||
path: 'analytics',
|
||||
loadComponent: () => import('./features/admin/analytics/pages/admin-analytics-page.component').then(m => m.AdminAnalyticsPageComponent)
|
||||
},
|
||||
{ path: '**', redirectTo: 'dashboard' }
|
||||
]
|
||||
},
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ const QUICK_ACTIONS: AdminDashboardQuickAction[] = [
|
||||
{ id: 'media-library', labelKey: 'dashboard.actionMediaLibrary', route: ['backoffice', 'media'] },
|
||||
{ id: 'users', labelKey: 'dashboard.actionUsers', route: ['backoffice', 'users'] },
|
||||
{ id: 'monitoring', labelKey: 'dashboard.actionMonitoring', route: ['backoffice', 'monitoring'] },
|
||||
{ id: 'analytics', labelKey: 'dashboard.actionAnalytics', route: ['backoffice', 'analytics'] },
|
||||
{ id: 'preview-marketplace', labelKey: 'dashboard.actionPreviewMarketplace', route: [''] },
|
||||
];
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ export type AdminDashboardQuickActionId =
|
||||
| 'media-library'
|
||||
| 'users'
|
||||
| 'monitoring'
|
||||
| 'analytics'
|
||||
| 'preview-marketplace';
|
||||
|
||||
export interface AdminDashboardQuickAction {
|
||||
|
||||
Reference in New Issue
Block a user