import { NextRequest, NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { getCurrentUser } from '@/lib/auth'; import { getParticipationStoragePath } from '@/lib/participation-pdf'; import fs from 'fs'; // POST - Envoyer la participation par email export async function POST( request: NextRequest, { params }: { params: { id: string } } ) { try { const user = await getCurrentUser(); if (!user) { return NextResponse.json({ error: 'Non autorisé' }, { status: 401 }); } const participation = await prisma.participationFinanciere.findUnique({ where: { id: params.id }, include: { adherent: { select: { prenom: true, nom: true, email: true, facturation: true, prescripteur: true }, }, trajet: { select: { date: true, universProId: true, universPro: { select: { email: true, prenom: true, nom: true, nomEntreprise: true } } }, }, }, }); if (!participation) { return NextResponse.json({ error: 'Participation non trouvée' }, { status: 404 }); } // Déterminer l'email selon la facturation de l'adhérent const facturation = (participation.adherent.facturation || '').trim(); const isAdherent = !facturation || /^adh[eé]rent$/i.test(facturation); let destinataireEmail: string; let destinataireNom: string; if (isAdherent) { destinataireEmail = participation.adherent.email; destinataireNom = `${participation.adherent.prenom} ${participation.adherent.nom}`; } else if (participation.trajet?.universProId && participation.trajet?.universPro) { destinataireEmail = participation.trajet.universPro.email; destinataireNom = `${participation.trajet.universPro.prenom} ${participation.trajet.universPro.nom} - ${participation.trajet.universPro.nomEntreprise}`; } else { const universPro = await prisma.universPro.findFirst({ where: { nomEntreprise: facturation }, }); if (universPro) { destinataireEmail = universPro.email; destinataireNom = `${universPro.prenom} ${universPro.nom} - ${universPro.nomEntreprise}`; } else { return NextResponse.json( { error: `Aucune fiche Univers Pro trouvée pour "${facturation}". Créez un contact avec ce nom d'entreprise ou vérifiez la facturation de l'adhérent.` }, { status: 400 } ); } } const filePath = getParticipationStoragePath(participation.id); if (!fs.existsSync(filePath)) { return NextResponse.json( { error: 'Le document PDF n\'a pas été généré' }, { status: 400 } ); } // Vérifier la configuration email const smtpHost = process.env.SMTP_HOST; const smtpUser = process.env.SMTP_USER; const smtpPass = process.env.SMTP_PASS; if (!smtpHost || !smtpUser || !smtpPass) { return NextResponse.json( { error: "L'envoi par email n'est pas configuré. Configurez SMTP_HOST, SMTP_USER et SMTP_PASS dans les variables d'environnement.", }, { status: 503 } ); } const nodemailer = await import('nodemailer'); const transporter = nodemailer.default.createTransport({ host: smtpHost, port: parseInt(process.env.SMTP_PORT || '587'), secure: process.env.SMTP_SECURE === 'true', auth: { user: smtpUser, pass: smtpPass, }, }); const pdfBuffer = fs.readFileSync(filePath); const dateTrajet = participation.trajet?.date ? new Date(participation.trajet.date).toLocaleDateString('fr-FR', { day: '2-digit', month: 'long', year: 'numeric', }) : ''; await transporter.sendMail({ from: process.env.SMTP_FROM || smtpUser, to: destinataireEmail, subject: `Participation financière - ${participation.adherent.prenom} ${participation.adherent.nom} - ${dateTrajet}`, text: `Bonjour,\n\nVeuillez trouver ci-joint la participation financière concernant le trajet du ${dateTrajet} pour ${participation.adherent.prenom} ${participation.adherent.nom}.\n\nCordialement`, html: `
Bonjour,
Veuillez trouver ci-joint la participation financière concernant le trajet du ${dateTrajet} pour ${participation.adherent.prenom} ${participation.adherent.nom}.
Cordialement
`, attachments: [ { filename: `participation-financiere-${params.id}.pdf`, content: pdfBuffer, }, ], }); // Mettre à jour le statut en "envoyé" et le destinataire (au cas où il aurait changé) await prisma.participationFinanciere.update({ where: { id: params.id }, data: { statut: 'envoye', destinataireEmail, destinataireNom, destinataireType: isAdherent ? 'adherent' : 'univers_pro', }, }); return NextResponse.json({ message: `Participation envoyée à ${destinataireEmail}. Le budget du prescripteur a été décrementé.`, }); } catch (error) { console.error('Erreur lors de l\'envoi de l\'email:', error); return NextResponse.json( { error: error instanceof Error ? error.message : 'Erreur lors de l\'envoi de l\'email', }, { status: 500 } ); } }