From 9096e799f45b2ff45f6a743b169a141104f4d514 Mon Sep 17 00:00:00 2001 From: Tony AVERTY Date: Wed, 7 Oct 2026 10:47:48 +0200 Subject: [PATCH] =?UTF-8?q?Statistiques=20avanc=C3=A9es=20et=20export=20CS?= =?UTF-8?q?V=20(formule=20Pro)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Indicateurs sur 30 j / 3 mois / 12 mois : passages et nouvelles cartes (vs période précédente), clients actifs et fidèles, achats et panier moyen, récompenses, adoption Apple Wallet - Courbe de fréquentation, heures d'affluence (jour × heure, heure de Paris), meilleurs clients - Exports CSV clients et opérations (format Excel FR, formules neutralisées) - Admin : onglet Statistiques avec téléchargement ; app Pro : écran gérant, export envoyé par e-mail Co-Authored-By: Claude Opus 5.5 --- admin/src/pages/StatsTab.tsx | 219 ++++++++++++++++++++++++++ admin/src/pages/StorePage.tsx | 3 + backend/src/app.module.ts | 2 + backend/src/stats/export.service.ts | 117 ++++++++++++++ backend/src/stats/stats.controller.ts | 109 +++++++++++++ backend/src/stats/stats.service.ts | 148 +++++++++++++++++ pro/app/_layout.tsx | 1 + pro/app/index.tsx | 1 + pro/app/stats.tsx | 173 ++++++++++++++++++++ site-src/pricing.js | 2 +- site/tarif/index.html | 2 +- 11 files changed, 775 insertions(+), 2 deletions(-) create mode 100644 admin/src/pages/StatsTab.tsx create mode 100644 backend/src/stats/export.service.ts create mode 100644 backend/src/stats/stats.controller.ts create mode 100644 backend/src/stats/stats.service.ts create mode 100644 pro/app/stats.tsx diff --git a/admin/src/pages/StatsTab.tsx b/admin/src/pages/StatsTab.tsx new file mode 100644 index 0000000..2bf1c79 --- /dev/null +++ b/admin/src/pages/StatsTab.tsx @@ -0,0 +1,219 @@ +import { useEffect, useState } from 'react'; +import { api, downloadFile } from '../api'; + +interface Stats { + allowed: boolean; + days: number; + pointsMode: 'AMOUNT' | 'STAMP'; + kpis: { + cardsTotal: number; + newCards: number; + newCardsChange: number | null; + visits: number; + visitsChange: number | null; + activeCustomers: number; + returningRate: number | null; + visitsPerCustomer: number; + revenueCents: number; + averageBasketCents: number | null; + pointsGiven: number; + rewardsRedeemed: number; + appleWalletRate: number | null; + }; + series: { label: string; visits: number; newCards: number }[]; + heatmap: { weekdays: string[]; values: number[][] }; + busiest: string | null; + top: { firstName: string; visits: number; amountCents: number; balance: number }[]; +} + +const PERIODS: [number, string][] = [[30, '30 jours'], [90, '3 mois'], [365, '12 mois']]; +const euros = (c: number) => (c / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR', maximumFractionDigits: c >= 100000 ? 0 : 2 }); +const nf = (n: number) => n.toLocaleString('fr-FR'); + +function Change({ value }: { value: number | null }) { + if (value === null) return null; + const up = value >= 0; + return ( + + {up ? '▲' : '▼'} {Math.abs(value).toLocaleString('fr-FR')} % + + ); +} + +function Kpi({ label, value, hint, change }: { label: string; value: string; hint?: string; change?: number | null }) { + return ( +
+ {label} + {value} + + {change !== undefined && } + {hint && {hint}} + +
+ ); +} + +/** Barres : passages (plein) et nouvelles cartes (clair). */ +function Bars({ series }: { series: Stats['series'] }) { + const max = Math.max(1, ...series.map((s) => Math.max(s.visits, s.newCards))); + const w = 100 / series.length; + const every = Math.ceil(series.length / 8); + return ( + + {series.map((s, i) => ( + + {`${s.label} : ${s.visits} passage(s), ${s.newCards} nouvelle(s) carte(s)`} + + + {i % every === 0 && ( + {s.label} + )} + + ))} + + + ); +} + +function Heatmap({ heat }: { heat: Stats['heatmap'] }) { + const hours = Array.from({ length: 15 }, (_, i) => i + 7); // 7 h – 21 h + const max = Math.max(1, ...heat.values.flat()); + return ( +
+ + + + )} + + + + {heat.weekdays.map((d, i) => ( + + + {hours.map((h) => { + const n = heat.values[i][h]; + return ( + + ))} + +
+ {hours.map((h) => {h}h
{d} + ); + })} +
+
+ ); +} + +export function StatsTab({ storeId, storeSlug }: { storeId: string; storeSlug: string }) { + const [days, setDays] = useState(30); + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(null); + + useEffect(() => { + setError(null); + api.get(`/api/admin/stores/${storeId}/stats?days=${days}`).then(setData).catch((e) => setError(e.message)); + }, [storeId, days]); + + async function download(kind: 'customers' | 'transactions') { + setBusy(kind); + try { + const date = new Date().toISOString().slice(0, 10); + if (kind === 'customers') await downloadFile(`/api/admin/stores/${storeId}/export/customers`, `clients-${storeSlug}-${date}.csv`); + else await downloadFile(`/api/admin/stores/${storeId}/export/transactions?days=${days}`, `operations-${storeSlug}-${days}j-${date}.csv`); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(null); + } + } + + const k = data?.kpis; + const unit = data?.pointsMode === 'STAMP' ? 'tampons' : 'points'; + + return ( + <> +
+
+ {PERIODS.map(([d, label]) => ( + + ))} +
+
+ + +
+
+ {error &&
{error}
} + {data && !data.allowed &&
Ce magasin n'a pas la formule Pro : il ne voit pas ces statistiques dans son app (vous, si).
} + {!data || !k ? ( + !error &&

Chargement…

+ ) : ( + <> +
+ + + + + {data.pointsMode === 'AMOUNT' && ( + + )} + + +
+ +
+

Fréquentation

+

+ Passages +    + Nouvelles cartes +

+ +
+ +
+

Heures d'affluence

+

{data.busiest ? `Créneau le plus fréquenté : ${data.busiest}.` : 'Pas encore de passage sur la période.'}

+ +
+ +
+

Meilleurs clients

+ {data.top.length === 0 ? ( +

Pas encore de passage sur la période.

+ ) : ( +
+ + + + + + {data.pointsMode === 'AMOUNT' && } + + + + + {data.top.map((t, i) => ( + + + + {data.pointsMode === 'AMOUNT' && } + + + ))} + +
ClientPassagesAchatsSolde
{t.firstName}{t.visits}{euros(t.amountCents)}{t.balance}
+
+ )} +
+ + )} + + ); +} diff --git a/admin/src/pages/StorePage.tsx b/admin/src/pages/StorePage.tsx index e900195..7fcb433 100644 --- a/admin/src/pages/StorePage.tsx +++ b/admin/src/pages/StorePage.tsx @@ -7,12 +7,14 @@ import { CardWizard } from './CardWizard'; import { StaffTab } from './StaffTab'; import { BillingTab } from './BillingTab'; import { CampaignsTab } from './CampaignsTab'; +import { StatsTab } from './StatsTab'; const TABS = [ ['infos', 'Infos'], ['carte', 'Carte de fidélité'], ['employes', 'Employés'], ['campagnes', 'Fidélisation'], + ['statistiques', 'Statistiques'], ['facturation', 'Facturation'], ] as const; @@ -112,6 +114,7 @@ export function StorePage() { } /> } /> } /> + } /> } /> diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts index 470acbb..ee50a30 100644 --- a/backend/src/app.module.ts +++ b/backend/src/app.module.ts @@ -19,6 +19,7 @@ import { BirthdaysModule } from './birthdays/birthdays.controller'; import { ReviewsModule } from './reviews/reviews.controller'; import { ReferralsModule } from './referrals/referrals.controller'; import { ReferralsCoreModule } from './referrals/referrals.service'; +import { StatsModule } from './stats/stats.controller'; import { HealthController } from './health.controller'; @Module({ @@ -41,6 +42,7 @@ import { HealthController } from './health.controller'; ReviewsModule, ReferralsCoreModule, ReferralsModule, + StatsModule, ], controllers: [HealthController], providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }], diff --git a/backend/src/stats/export.service.ts b/backend/src/stats/export.service.ts new file mode 100644 index 0000000..6112584 --- /dev/null +++ b/backend/src/stats/export.service.ts @@ -0,0 +1,117 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; + +const TYPE_LABEL = { CREDIT: 'Crédit', REDEEM: 'Récompense', ADJUST: 'Ajustement', REJECTED: 'Refusé' } as const; +const REJECT_LABEL = { AMOUNT_OVER_LIMIT: 'Montant au-dessus du plafond', TOO_SOON: 'Trop rapproché', INSUFFICIENT_BALANCE: 'Solde insuffisant' } as const; + +/** + * Cellule CSV : guillemets doublés, et neutralisation des formules + * (une cellule qui commence par = + - @ serait exécutée par Excel). + */ +export function cell(value: unknown): string { + if (value === null || value === undefined) return ''; + let s = value instanceof Date ? formatDate(value) : String(value); + if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`; + return /[";\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +} + +/** CSV au format Excel français : séparateur « ; », BOM UTF-8, fins de ligne CRLF. */ +export function toCsv(header: string[], rows: unknown[][]) { + const lines = [header, ...rows].map((r) => r.map(cell).join(';')); + return Buffer.from(`${lines.join('\r\n')}\r\n`, 'utf8'); +} + +function formatDate(d: Date) { + return d.toLocaleString('fr-FR', { timeZone: 'Europe/Paris', dateStyle: 'short', timeStyle: 'short' }); +} +const euros = (cents: number | null | undefined) => (cents === null || cents === undefined ? '' : (cents / 100).toFixed(2).replace('.', ',')); + +@Injectable() +export class ExportService { + constructor(private prisma: PrismaService) {} + + private async storeOf(storeId: string) { + const store = await this.prisma.store.findUnique({ where: { id: storeId }, select: { slug: true } }); + if (!store) throw new NotFoundException('Magasin introuvable'); + return store; + } + + /** Fichier clients : une ligne par carte. */ + async customers(storeId: string) { + const store = await this.storeOf(storeId); + const cards = await this.prisma.loyaltyCard.findMany({ + where: { storeId }, + orderBy: { createdAt: 'asc' }, + include: { + customer: true, + referredBy: { select: { customer: { select: { firstName: true } } } }, + devices: { select: { deviceId: true }, take: 1 }, + }, + }); + const totals = await this.prisma.transaction.groupBy({ + by: ['cardId'], + where: { storeId, type: 'CREDIT' }, + _count: { _all: true }, + _sum: { amountCents: true }, + }); + const byCard = new Map(totals.map((t) => [t.cardId, t])); + const rows = cards.map((c) => { + const t = byCard.get(c.id); + const birthday = c.customer.birthMonth && c.customer.birthDay ? `${String(c.customer.birthDay).padStart(2, '0')}/${String(c.customer.birthMonth).padStart(2, '0')}` : ''; + return [ + c.customer.firstName, + c.customer.email, + birthday, + c.balance, + t?._count._all ?? 0, + euros(t?._sum.amountCents ?? null), + c.createdAt, + c.lastCreditAt, + c.devices.length ? 'Oui' : 'Non', + c.referredBy?.customer.firstName ?? '', + c.serial, + ]; + }); + return { + filename: `clients-${store.slug}-${new Date().toISOString().slice(0, 10)}.csv`, + content: toCsv( + ['Prénom', 'E-mail', 'Anniversaire', 'Solde', 'Passages', 'Total dépensé (€)', 'Inscrit le', 'Dernier passage', 'Apple Wallet', 'Parrainé par', 'N° de carte'], + rows, + ), + count: rows.length, + }; + } + + /** Fichier des opérations de la période (jours). */ + async transactions(storeId: string, days: number) { + const store = await this.storeOf(storeId); + const from = new Date(Date.now() - days * 24 * 3600_000); + const txs = await this.prisma.transaction.findMany({ + where: { storeId, createdAt: { gte: from } }, + orderBy: { createdAt: 'asc' }, + include: { + staff: { select: { displayName: true } }, + reward: { select: { label: true } }, + card: { select: { serial: true, customer: { select: { firstName: true, email: true } } } }, + }, + }); + const rows = txs.map((t) => [ + t.createdAt, + TYPE_LABEL[t.type], + t.card.customer.firstName, + t.card.customer.email, + euros(t.amountCents), + t.points, + t.balanceAfter, + t.reward?.label ?? '', + t.rejectReason ? REJECT_LABEL[t.rejectReason] : '', + t.staff.displayName, + t.card.serial, + ]); + return { + filename: `operations-${store.slug}-${days}j-${new Date().toISOString().slice(0, 10)}.csv`, + content: toCsv(['Date', 'Type', 'Client', 'E-mail', 'Montant (€)', 'Points', 'Solde après', 'Récompense', 'Motif du refus', 'Employé', 'N° de carte'], rows), + count: rows.length, + }; + } +} diff --git a/backend/src/stats/stats.controller.ts b/backend/src/stats/stats.controller.ts new file mode 100644 index 0000000..b52dead --- /dev/null +++ b/backend/src/stats/stats.controller.ts @@ -0,0 +1,109 @@ +import { Body, Controller, Get, HttpCode, Module, Param, ParseIntPipe, Post, Query, Res, UseGuards } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { Throttle } from '@nestjs/throttler'; +import { IsIn } from 'class-validator'; +import type { Response } from 'express'; +import { EntitlementsService } from '../billing/entitlements.service'; +import { JwtPayload } from '../common/auth.types'; +import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards'; +import { emailLayout, esc } from '../mail/email-layout'; +import { MailService } from '../mail/mail.service'; +import { PrismaService } from '../prisma/prisma.service'; +import { ExportService } from './export.service'; +import { PERIODS, StatsService } from './stats.service'; + +const period = (days: number) => (PERIODS.includes(days) ? days : 30); + +function sendCsv(res: Response, file: { filename: string; content: Buffer }) { + res + .status(200) + .type('text/csv; charset=utf-8') + .setHeader('Content-Disposition', `attachment; filename="${file.filename}"`) + .setHeader('Cache-Control', 'no-store') + .send(file.content); +} + +class ExportDto { + @IsIn(['customers', 'transactions']) + kind!: 'customers' | 'transactions'; + + @IsIn(PERIODS) + days!: number; +} + +@Controller('admin/stores/:id') +@UseGuards(JwtAuthGuard, AdminGuard) +export class AdminStatsController { + constructor(private stats: StatsService, private exports: ExportService, private entitlements: EntitlementsService) {} + + @Get('stats') + async get(@Param('id') id: string, @Query('days', new ParseIntPipe({ optional: true })) days = 30) { + const [data, allowed] = await Promise.all([this.stats.compute(id, period(days)), this.entitlements.can(id, 'advancedStats')]); + return { ...data, allowed }; + } + + @Get('export/customers') + async customers(@Param('id') id: string, @Res() res: Response) { + sendCsv(res, await this.exports.customers(id)); + } + + @Get('export/transactions') + async transactions(@Param('id') id: string, @Query('days', new ParseIntPipe({ optional: true })) days = 30, @Res() res: Response) { + sendCsv(res, await this.exports.transactions(id, period(days))); + } +} + +/** App Pro : statistiques et exports pour les gérants (formule Pro). */ +@Controller('staff') +@UseGuards(JwtAuthGuard, StaffGuard) +@StaffRoles('MANAGER') +export class StaffStatsController { + constructor( + private stats: StatsService, + private exports: ExportService, + private entitlements: EntitlementsService, + private prisma: PrismaService, + private mail: MailService, + private config: ConfigService, + ) {} + + @Get('stats') + async get(@CurrentUser() user: JwtPayload, @Query('days', new ParseIntPipe({ optional: true })) days = 30) { + if (user.kind !== 'staff') throw new Error('StaffGuard manquant'); + await this.entitlements.require(user.storeId, 'advancedStats'); + return this.stats.compute(user.storeId, period(days)); + } + + /** Le fichier part par e-mail au gérant : rien à stocker sur le téléphone. */ + @Post('export') + @HttpCode(200) + @Throttle({ default: { limit: 5, ttl: 10 * 60_000 } }) + async export(@CurrentUser() user: JwtPayload, @Body() dto: ExportDto) { + if (user.kind !== 'staff') throw new Error('StaffGuard manquant'); + await this.entitlements.require(user.storeId, 'csvExport'); + const staff = await this.prisma.staffUser.findUniqueOrThrow({ where: { id: user.sub }, include: { store: { select: { name: true } } } }); + const file = dto.kind === 'customers' ? await this.exports.customers(user.storeId) : await this.exports.transactions(user.storeId, dto.days); + const what = dto.kind === 'customers' ? 'Fichier clients' : `Opérations des ${dto.days} derniers jours`; + const subject = `${what} — ${staff.store.name}`; + const text = `Bonjour ${staff.displayName},\n\nVoici votre export « ${what} » (${file.count} lignes), en pièce jointe au format CSV (ouvrable avec Excel).\n\nCe fichier contient des données personnelles de vos clients : conservez-le en lieu sûr et ne le partagez pas.\n\nMonEspacePro`; + const html = emailLayout({ + webUrl: this.config.get('webUrl')!, + preheader: `${what} : ${file.count} lignes en pièce jointe.`, + eyebrow: 'Export', + title: what, + paragraphs: [ + `Bonjour ${esc(staff.displayName)},`, + `Voici votre export pour ${esc(staff.store.name)} : ${file.count} lignes, en pièce jointe au format CSV (ouvrable avec Excel).`, + 'Ce fichier contient des données personnelles de vos clients : conservez-le en lieu sûr et ne le partagez pas.', + ], + }); + await this.mail.sendWithAttachment(staff.email, subject, text, html, { filename: file.filename, content: file.content }); + return { sentTo: staff.email, count: file.count }; + } +} + +@Module({ + controllers: [AdminStatsController, StaffStatsController], + providers: [StatsService, ExportService], +}) +export class StatsModule {} diff --git a/backend/src/stats/stats.service.ts b/backend/src/stats/stats.service.ts new file mode 100644 index 0000000..435d62d --- /dev/null +++ b/backend/src/stats/stats.service.ts @@ -0,0 +1,148 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; + +export const PERIODS = [30, 90, 365]; +const DAY = 24 * 3600_000; +const WEEKDAYS = ['lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.', 'dim.']; +const MONTHS = ['janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.']; + +const PARIS = new Intl.DateTimeFormat('en-GB', { + timeZone: 'Europe/Paris', + year: 'numeric', + month: 'numeric', + day: 'numeric', + hour: 'numeric', + weekday: 'short', + hour12: false, +}); + +/** Date locale de Paris : année, mois, jour, heure (0-23), jour de semaine (0 = lundi). */ +export function paris(d: Date) { + const p = Object.fromEntries(PARIS.formatToParts(d).map((x) => [x.type, x.value])); + return { + year: +p.year, + month: +p.month, + day: +p.day, + hour: +p.hour % 24, + weekday: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].indexOf(p.weekday), + }; +} + +const pad = (n: number) => String(n).padStart(2, '0'); + +/** Regroupement de la courbe : jour (30 j), semaine (90 j), mois (365 j). */ +function bucket(d: Date, days: number) { + const p = paris(d); + if (days <= 30) return { key: `${p.year}-${pad(p.month)}-${pad(p.day)}`, label: `${p.day} ${MONTHS[p.month - 1]}` }; + if (days <= 90) { + // Lundi de la semaine (date de Paris). + const monday = new Date(Date.UTC(p.year, p.month - 1, p.day - p.weekday)); + return { key: monday.toISOString().slice(0, 10), label: `sem. du ${monday.getUTCDate()} ${MONTHS[monday.getUTCMonth()]}` }; + } + return { key: `${p.year}-${pad(p.month)}`, label: `${MONTHS[p.month - 1]} ${String(p.year).slice(2)}` }; +} + +const pct = (a: number, b: number) => (b ? Math.round((a / b) * 1000) / 10 : null); + +/** + * Statistiques avancées d'un magasin sur une période : fréquentation, fidélité, + * chiffre déclaré, récompenses, heures d'affluence, meilleurs clients. + */ +@Injectable() +export class StatsService { + constructor(private prisma: PrismaService) {} + + async compute(storeId: string, days: number, now = new Date()) { + const store = await this.prisma.store.findUnique({ where: { id: storeId }, include: { cardDesign: { select: { pointsMode: true } } } }); + if (!store) throw new NotFoundException('Magasin introuvable'); + const from = new Date(now.getTime() - days * DAY); + const prevFrom = new Date(from.getTime() - days * DAY); + + const [txs, cardsTotal, newCards, prevNewCards, prevVisits, appleCards, cardsCreated] = await Promise.all([ + this.prisma.transaction.findMany({ + where: { storeId, createdAt: { gte: from }, type: { in: ['CREDIT', 'REDEEM'] } }, + select: { cardId: true, type: true, amountCents: true, points: true, createdAt: true }, + }), + this.prisma.loyaltyCard.count({ where: { storeId } }), + this.prisma.loyaltyCard.count({ where: { storeId, createdAt: { gte: from } } }), + this.prisma.loyaltyCard.count({ where: { storeId, createdAt: { gte: prevFrom, lt: from } } }), + this.prisma.transaction.count({ where: { storeId, type: 'CREDIT', createdAt: { gte: prevFrom, lt: from } } }), + this.prisma.loyaltyCard.count({ where: { storeId, devices: { some: {} } } }), + this.prisma.loyaltyCard.findMany({ where: { storeId, createdAt: { gte: from } }, select: { createdAt: true } }), + ]); + + const credits = txs.filter((t) => t.type === 'CREDIT'); + const redeems = txs.filter((t) => t.type === 'REDEEM'); + const visitsByCard = new Map(); + for (const t of credits) { + const v = visitsByCard.get(t.cardId) ?? { visits: 0, cents: 0 }; + v.visits++; + v.cents += t.amountCents ?? 0; + visitsByCard.set(t.cardId, v); + } + const active = visitsByCard.size; + const returning = [...visitsByCard.values()].filter((v) => v.visits >= 2).length; + const revenueCents = credits.reduce((s, t) => s + (t.amountCents ?? 0), 0); + const withAmount = credits.filter((t) => t.amountCents !== null).length; + + // Courbe : passages et nouvelles cartes, toutes les cases de la période (même vides). + const series = new Map(); + for (let t = from.getTime(); t <= now.getTime(); t += DAY) { + const b = bucket(new Date(t), days); + if (!series.has(b.key)) series.set(b.key, { label: b.label, visits: 0, newCards: 0 }); + } + const add = (d: Date, field: 'visits' | 'newCards') => { + const b = bucket(d, days); + const s = series.get(b.key) ?? { label: b.label, visits: 0, newCards: 0 }; + s[field]++; + series.set(b.key, s); + }; + credits.forEach((t) => add(t.createdAt, 'visits')); + cardsCreated.forEach((c) => add(c.createdAt, 'newCards')); + + // Affluence : jour de semaine × heure. + const heat = Array.from({ length: 7 }, () => Array(24).fill(0)); + for (const t of credits) { + const p = paris(t.createdAt); + heat[p.weekday][p.hour]++; + } + const busiest = heat + .flatMap((row, d) => row.map((n, h) => ({ n, d, h }))) + .sort((a, b) => b.n - a.n)[0]; + + // Meilleurs clients de la période. + const topIds = [...visitsByCard.entries()].sort((a, b) => b[1].visits - a[1].visits || b[1].cents - a[1].cents).slice(0, 10); + const topCards = await this.prisma.loyaltyCard.findMany({ + where: { id: { in: topIds.map(([id]) => id) } }, + select: { id: true, balance: true, customer: { select: { firstName: true } } }, + }); + const top = topIds.map(([id, v]) => { + const c = topCards.find((x) => x.id === id); + return { firstName: c?.customer.firstName ?? '—', visits: v.visits, amountCents: v.cents, balance: c?.balance ?? 0 }; + }); + + return { + days, + pointsMode: store.cardDesign?.pointsMode ?? 'AMOUNT', + kpis: { + cardsTotal, + newCards, + newCardsChange: pct(newCards - prevNewCards, prevNewCards), + visits: credits.length, + visitsChange: pct(credits.length - prevVisits, prevVisits), + activeCustomers: active, + returningRate: pct(returning, active), + visitsPerCustomer: active ? Math.round((credits.length / active) * 10) / 10 : 0, + revenueCents, + averageBasketCents: withAmount ? Math.round(revenueCents / withAmount) : null, + pointsGiven: credits.reduce((s, t) => s + t.points, 0), + rewardsRedeemed: redeems.length, + appleWalletRate: pct(appleCards, cardsTotal), + }, + series: [...series.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, v]) => v), + heatmap: { weekdays: WEEKDAYS, values: heat }, + busiest: busiest && busiest.n > 0 ? `${WEEKDAYS[busiest.d]} ${busiest.h} h–${busiest.h + 1} h` : null, + top, + }; + } +} diff --git a/pro/app/_layout.tsx b/pro/app/_layout.tsx index 88c0ad9..be080fe 100644 --- a/pro/app/_layout.tsx +++ b/pro/app/_layout.tsx @@ -53,6 +53,7 @@ function Navigator() { + diff --git a/pro/app/index.tsx b/pro/app/index.tsx index 65409fd..2a21b86 100644 --- a/pro/app/index.tsx +++ b/pro/app/index.tsx @@ -113,6 +113,7 @@ export default function Home() { {isManager &&