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', ...{ cancelledBy: { is: null } } }, _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, }; } }