import { Body, Controller, ForbiddenException, 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 { ModulesService } from '../modules/modules.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 modules: ModulesService) {}
@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.modules.active(id, 'stats')]);
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 dirigeants (formule Pro). */
@Controller('staff')
@UseGuards(JwtAuthGuard, StaffGuard)
@StaffRoles('MANAGER')
export class StaffStatsController {
constructor(
private stats: StatsService,
private exports: ExportService,
private modules: ModulesService,
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.modules.require(user.storeId, 'stats');
return this.stats.compute(user.storeId, period(days));
}
/** Le fichier part par e-mail au dirigeant : 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');
const config = await this.modules.require(user.storeId, 'stats');
if (!config.csvExport) throw new ForbiddenException({ statusCode: 403, code: 'MODULE_DISABLED', message: 'L’export CSV est désactivé dans les réglages du module Statistiques.' });
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 {}