Checkpoint: Système d'attestations de formation implémenté
✅ Infrastructure backend : - Tables attestations et configAttestation en base de données - Service de génération PDF avec PDFKit (attestationService.ts) - Génération automatique de PDF avec template personnalisable - Upload automatique vers S3 avec URLs publiques - Procédures tRPC pour générer, récupérer et configurer ✅ Interface utilisateur : - Page de configuration des attestations (/admin/attestations) - Personnalisation du texte avec variables dynamiques (nomComplet, nomFormation, dateDebut, dateFin) - Configuration du signataire (nom et fonction) - Bouton "Générer" dans la page de validation des présences formateur - Génération automatique avec ouverture du PDF dans un nouvel onglet ✅ Fonctionnalités : - Vérification des doublons (une seule attestation par apprenant/séquence) - Génération uniquement pour les apprenants marqués comme présents - PDF professionnel avec détails de la formation et dates - Stockage permanent sur S3 📋 Améliorations futures possibles : - Upload de logo et signature personnalisés - Envoi automatique par email aux apprenants - Espace apprenant pour télécharger les attestations
This commit is contained in:
269
server/attestationService.ts
Normal file
269
server/attestationService.ts
Normal file
@@ -0,0 +1,269 @@
|
||||
import { getDb } from "./db";
|
||||
import { attestations, configAttestation, inscriptions, apprenants, sequences, formations, datesFormation } from "../drizzle/schema";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { storagePut } from "./storage";
|
||||
import PDFDocument from "pdfkit";
|
||||
import { format } from "date-fns";
|
||||
import { fr } from "date-fns/locale";
|
||||
import crypto from "crypto";
|
||||
|
||||
/**
|
||||
* Génère une attestation de formation en PDF
|
||||
*/
|
||||
export async function genererAttestationPDF(inscriptionId: number): Promise<{ s3Key: string; pdfUrl: string }> {
|
||||
const db = await getDb();
|
||||
if (!db) {
|
||||
throw new Error("Base de données non disponible");
|
||||
}
|
||||
|
||||
// Récupérer les données de l'inscription
|
||||
const [inscriptionData] = await db
|
||||
.select({
|
||||
inscription: inscriptions,
|
||||
apprenant: apprenants,
|
||||
sequence: sequences,
|
||||
formation: formations,
|
||||
})
|
||||
.from(inscriptions)
|
||||
.innerJoin(apprenants, eq(inscriptions.apprenantId, apprenants.id))
|
||||
.innerJoin(sequences, eq(inscriptions.sequenceId, sequences.id))
|
||||
.innerJoin(formations, eq(sequences.formationId, formations.id))
|
||||
.where(eq(inscriptions.id, inscriptionId))
|
||||
.limit(1);
|
||||
|
||||
if (!inscriptionData) {
|
||||
throw new Error("Inscription introuvable");
|
||||
}
|
||||
|
||||
const { inscription, apprenant, sequence, formation } = inscriptionData;
|
||||
|
||||
// Récupérer les dates de la séquence
|
||||
const dates = await db
|
||||
.select()
|
||||
.from(datesFormation)
|
||||
.where(eq(datesFormation.sequenceId, sequence.id));
|
||||
|
||||
// Récupérer la configuration de l'attestation
|
||||
const [config] = await db
|
||||
.select()
|
||||
.from(configAttestation)
|
||||
.limit(1);
|
||||
|
||||
// Créer le PDF
|
||||
const doc = new PDFDocument({
|
||||
size: "A4",
|
||||
margins: { top: 50, bottom: 50, left: 50, right: 50 },
|
||||
});
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
doc.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
doc.on("end", async () => {
|
||||
try {
|
||||
const pdfBuffer = Buffer.concat(chunks);
|
||||
|
||||
// Générer une clé S3 unique
|
||||
const randomSuffix = crypto.randomBytes(8).toString("hex");
|
||||
const s3Key = `attestations/${apprenant.id}-${sequence.id}-${randomSuffix}.pdf`;
|
||||
|
||||
// Upload vers S3
|
||||
const { url } = await storagePut(s3Key, pdfBuffer, "application/pdf");
|
||||
|
||||
resolve({ s3Key, pdfUrl: url });
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
|
||||
doc.on("error", reject);
|
||||
|
||||
// Construction du PDF
|
||||
try {
|
||||
// Titre
|
||||
doc.fontSize(24).font("Helvetica-Bold").text("ATTESTATION DE FORMATION", { align: "center" });
|
||||
doc.moveDown(2);
|
||||
|
||||
// Texte personnalisable ou texte par défaut
|
||||
const texteAttestation = config?.texteAttestation ||
|
||||
"Nous attestons que {{nomComplet}} a suivi avec assiduité la formation \"{{nomFormation}}\" organisée du {{dateDebut}} au {{dateFin}}.";
|
||||
|
||||
// Remplacer les variables
|
||||
const nomComplet = `${apprenant.prenom} ${apprenant.nom}`;
|
||||
const dateDebut = dates.length > 0 ? format(new Date(dates[0].dateDebut), "dd MMMM yyyy", { locale: fr }) : "";
|
||||
const dateFin = dates.length > 0 ? format(new Date(dates[dates.length - 1].dateFin), "dd MMMM yyyy", { locale: fr }) : "";
|
||||
|
||||
const texteRempli = texteAttestation
|
||||
.replace(/\{\{nomComplet\}\}/g, nomComplet)
|
||||
.replace(/\{\{nomFormation\}\}/g, formation.nom)
|
||||
.replace(/\{\{dateDebut\}\}/g, dateDebut)
|
||||
.replace(/\{\{dateFin\}\}/g, dateFin);
|
||||
|
||||
doc.fontSize(12).font("Helvetica").text(texteRempli, { align: "justify" });
|
||||
doc.moveDown(2);
|
||||
|
||||
// Détails de la formation
|
||||
doc.fontSize(10).font("Helvetica-Bold").text("Détails de la formation :", { underline: true });
|
||||
doc.moveDown(0.5);
|
||||
doc.font("Helvetica");
|
||||
doc.text(`Formation : ${formation.nom}`);
|
||||
doc.text(`Séquence : ${sequence.nom}`);
|
||||
doc.text(`Lieu : ${sequence.lieu}`);
|
||||
doc.moveDown(0.5);
|
||||
doc.text("Dates :");
|
||||
dates.forEach((date) => {
|
||||
const dateStr = format(new Date(date.dateDebut), "dd/MM/yyyy", { locale: fr });
|
||||
const heureDebut = format(new Date(date.dateDebut), "HH:mm");
|
||||
const heureFin = format(new Date(date.dateFin), "HH:mm");
|
||||
doc.text(` • ${dateStr} de ${heureDebut} à ${heureFin}`);
|
||||
});
|
||||
|
||||
doc.moveDown(3);
|
||||
|
||||
// Signature
|
||||
doc.fontSize(10);
|
||||
doc.text(`Fait le ${format(new Date(), "dd MMMM yyyy", { locale: fr })}`, { align: "right" });
|
||||
doc.moveDown(3);
|
||||
|
||||
if (config?.nomSignataire) {
|
||||
doc.text(config.nomSignataire, { align: "right" });
|
||||
}
|
||||
if (config?.fonctionSignataire) {
|
||||
doc.text(config.fonctionSignataire, { align: "right" });
|
||||
}
|
||||
|
||||
doc.end();
|
||||
} catch (error) {
|
||||
doc.end();
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Enregistre une attestation dans la base de données
|
||||
*/
|
||||
export async function enregistrerAttestation(
|
||||
inscriptionId: number,
|
||||
apprenantId: number,
|
||||
sequenceId: number,
|
||||
s3Key: string,
|
||||
pdfUrl: string
|
||||
): Promise<number> {
|
||||
const db = await getDb();
|
||||
if (!db) {
|
||||
throw new Error("Base de données non disponible");
|
||||
}
|
||||
|
||||
const [result] = await db.insert(attestations).values({
|
||||
inscriptionId,
|
||||
apprenantId,
|
||||
sequenceId,
|
||||
s3Key,
|
||||
pdfUrl,
|
||||
emailEnvoye: false,
|
||||
});
|
||||
|
||||
return result.insertId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère l'attestation d'un apprenant pour une séquence
|
||||
*/
|
||||
export async function getAttestation(apprenantId: number, sequenceId: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return null;
|
||||
|
||||
const [attestation] = await db
|
||||
.select()
|
||||
.from(attestations)
|
||||
.where(
|
||||
and(
|
||||
eq(attestations.apprenantId, apprenantId),
|
||||
eq(attestations.sequenceId, sequenceId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
return attestation || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère toutes les attestations d'un apprenant
|
||||
*/
|
||||
export async function getAttestationsApprenant(apprenantId: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return [];
|
||||
|
||||
return db
|
||||
.select({
|
||||
attestation: attestations,
|
||||
sequence: sequences,
|
||||
formation: formations,
|
||||
})
|
||||
.from(attestations)
|
||||
.innerJoin(sequences, eq(attestations.sequenceId, sequences.id))
|
||||
.innerJoin(formations, eq(sequences.formationId, formations.id))
|
||||
.where(eq(attestations.apprenantId, apprenantId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Marque une attestation comme envoyée par email
|
||||
*/
|
||||
export async function marquerAttestationEnvoyee(attestationId: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return;
|
||||
|
||||
await db
|
||||
.update(attestations)
|
||||
.set({
|
||||
emailEnvoye: true,
|
||||
dateEnvoiEmail: new Date(),
|
||||
})
|
||||
.where(eq(attestations.id, attestationId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère ou crée la configuration des attestations
|
||||
*/
|
||||
export async function getOrCreateConfigAttestation() {
|
||||
const db = await getDb();
|
||||
if (!db) return null;
|
||||
|
||||
let [config] = await db.select().from(configAttestation).limit(1);
|
||||
|
||||
if (!config) {
|
||||
// Créer une configuration par défaut
|
||||
await db.insert(configAttestation).values({
|
||||
texteAttestation: "Nous attestons que {{nomComplet}} a suivi avec assiduité la formation \"{{nomFormation}}\" organisée du {{dateDebut}} au {{dateFin}}.",
|
||||
});
|
||||
|
||||
[config] = await db.select().from(configAttestation).limit(1);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour la configuration des attestations
|
||||
*/
|
||||
export async function updateConfigAttestation(data: {
|
||||
logoS3Key?: string;
|
||||
logoUrl?: string;
|
||||
signatureS3Key?: string;
|
||||
signatureUrl?: string;
|
||||
nomSignataire?: string;
|
||||
fonctionSignataire?: string;
|
||||
texteAttestation?: string;
|
||||
}) {
|
||||
const db = await getDb();
|
||||
if (!db) return;
|
||||
|
||||
const [existing] = await db.select().from(configAttestation).limit(1);
|
||||
|
||||
if (existing) {
|
||||
await db.update(configAttestation).set(data).where(eq(configAttestation.id, existing.id));
|
||||
} else {
|
||||
await db.insert(configAttestation).values(data);
|
||||
}
|
||||
}
|
||||
@@ -1736,6 +1736,98 @@ export const appRouter = router({
|
||||
});
|
||||
}),
|
||||
}),
|
||||
|
||||
// Attestations de formation
|
||||
attestations: router({
|
||||
// Générer une attestation pour une inscription
|
||||
generer: adminProcedure
|
||||
.input(z.object({
|
||||
inscriptionId: z.number(),
|
||||
}))
|
||||
.mutation(async ({ input }) => {
|
||||
const { genererAttestationPDF, enregistrerAttestation, getAttestation } = await import("./attestationService");
|
||||
const db = await import("./db").then(m => m.getDb());
|
||||
if (!db) throw new Error("Base de données non disponible");
|
||||
|
||||
// Vérifier si l'attestation existe déjà
|
||||
const { inscriptions } = await import("../drizzle/schema");
|
||||
const { eq } = await import("drizzle-orm");
|
||||
const [inscription] = await db.select().from(inscriptions).where(eq(inscriptions.id, input.inscriptionId)).limit(1);
|
||||
if (!inscription) {
|
||||
throw new Error("Inscription introuvable");
|
||||
}
|
||||
|
||||
const attestationExistante = await getAttestation(inscription.apprenantId, inscription.sequenceId);
|
||||
if (attestationExistante) {
|
||||
return {
|
||||
success: true,
|
||||
attestation: attestationExistante,
|
||||
message: "Attestation déjà générée",
|
||||
};
|
||||
}
|
||||
|
||||
// Générer le PDF
|
||||
const { s3Key, pdfUrl } = await genererAttestationPDF(input.inscriptionId);
|
||||
|
||||
// Enregistrer dans la base
|
||||
const attestationId = await enregistrerAttestation(
|
||||
input.inscriptionId,
|
||||
inscription.apprenantId,
|
||||
inscription.sequenceId,
|
||||
s3Key,
|
||||
pdfUrl
|
||||
);
|
||||
|
||||
const attestation = await getAttestation(inscription.apprenantId, inscription.sequenceId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
attestation,
|
||||
message: "Attestation générée avec succès",
|
||||
};
|
||||
}),
|
||||
|
||||
// Récupérer l'attestation d'un apprenant pour une séquence
|
||||
get: publicProcedure
|
||||
.input(z.object({
|
||||
apprenantId: z.number(),
|
||||
sequenceId: z.number(),
|
||||
}))
|
||||
.query(async ({ input }) => {
|
||||
const { getAttestation } = await import("./attestationService");
|
||||
return getAttestation(input.apprenantId, input.sequenceId);
|
||||
}),
|
||||
|
||||
// Récupérer toutes les attestations d'un apprenant
|
||||
listApprenant: publicProcedure
|
||||
.input(z.object({
|
||||
apprenantId: z.number(),
|
||||
}))
|
||||
.query(async ({ input }) => {
|
||||
const { getAttestationsApprenant } = await import("./attestationService");
|
||||
return getAttestationsApprenant(input.apprenantId);
|
||||
}),
|
||||
|
||||
// Récupérer la configuration des attestations
|
||||
getConfig: adminProcedure
|
||||
.query(async () => {
|
||||
const { getOrCreateConfigAttestation } = await import("./attestationService");
|
||||
return getOrCreateConfigAttestation();
|
||||
}),
|
||||
|
||||
// Mettre à jour la configuration des attestations
|
||||
updateConfig: adminProcedure
|
||||
.input(z.object({
|
||||
nomSignataire: z.string().optional(),
|
||||
fonctionSignataire: z.string().optional(),
|
||||
texteAttestation: z.string().optional(),
|
||||
}))
|
||||
.mutation(async ({ input }) => {
|
||||
const { updateConfigAttestation } = await import("./attestationService");
|
||||
await updateConfigAttestation(input);
|
||||
return { success: true };
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
|
||||
Reference in New Issue
Block a user