import { Body, Controller, HttpCode, Logger, Module, Post, ServiceUnavailableException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Throttle } from '@nestjs/throttler'; import { Transform } from 'class-transformer'; import { Equals, IsEmail, IsIn, IsOptional, IsString, Length, MaxLength } from 'class-validator'; import { MailService } from '../mail/mail.service'; import { emailLayout, esc } from '../mail/email-layout'; const trim = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.trim() : value); export const STORE_TYPES = [ 'Boulangerie, pâtisserie', 'Café, bar, restaurant', 'Coiffeur, barbier', 'Fleuriste', 'Boutique', 'Autre', ]; class ContactDto { @Transform(trim) @IsString() @Length(1, 120) storeName!: string; @IsIn(STORE_TYPES) storeType!: string; @Transform(trim) @IsString() @Length(1, 120) city!: string; @Transform(trim) @IsString() @Length(1, 60) firstName!: string; @Transform(trim) @IsString() @Length(1, 60) lastName!: string; @Transform(trim) @IsEmail() @MaxLength(200) email!: string; @IsOptional() @Transform(trim) @IsString() @MaxLength(4000) message?: string; @Equals(true) consent!: boolean; /** Champ piège invisible : rempli uniquement par les robots. */ @IsOptional() @IsString() @MaxLength(200) website?: string; } /** Formulaire de contact du site vitrine. */ @Controller('public/contact') export class ContactController { private readonly logger = new Logger(ContactController.name); constructor( private mail: MailService, private config: ConfigService, ) {} @Post() @HttpCode(200) @Throttle({ default: { limit: 3, ttl: 10 * 60_000 } }) async send(@Body() dto: ContactDto) { // Robot : on répond comme si tout allait bien, sans rien envoyer. if (dto.website) return { ok: true }; const to: string = this.config.get('mail.contactTo')!; const lines = [ ['Commerce', dto.storeName], ['Type', dto.storeType], ['Ville', dto.city], ['Contact', `${dto.firstName} ${dto.lastName}`], ['E-mail', dto.email], ]; const text = `${lines.map(([k, v]) => `${k} : ${v}`).join('\n')}\n\n${dto.message || '(pas de message)'}`; const html = emailLayout({ webUrl: this.config.get('webUrl')!, preheader: `${dto.firstName} ${dto.lastName} — ${dto.storeName}, ${dto.city}`, eyebrow: 'Message du site', title: `${dto.storeName} (${dto.city})`, paragraphs: [ dto.message ? esc(dto.message).replace(/\n/g, '
') : 'Pas de message.', 'Répondez directement à cet e-mail pour écrire au commerçant.', ], details: lines.map(([k, v]) => [k, esc(v)] as [string, string]), }); try { await this.mail.send(to, `Message du site — ${dto.storeName} (${dto.city})`, text, html, dto.email); } catch (e) { this.logger.error(`Message du site non transmis : ${(e as Error).message}`); throw new ServiceUnavailableException('Envoi impossible pour le moment'); } return { ok: true }; } } @Module({ controllers: [ContactController] }) export class ContactModule {}