Checkpoint: Implémentation complète de la fonctionnalité QR code formateur :

- Procédure generateQRCodeFormateur dans routers.ts
- Fonction validerPresenceFormateur dans presenceDb.ts
- Bouton "QR Code Formateur" dans FormateurEmargement.tsx
- Page EmargementFormateurScan.tsx pour le scan du QR code
- Route /emargement-formateur/{token}
- Gestion automatique de la date du jour
- Stockage de la signature sur S3
- Champ qrCodeFormateurToken dans le schéma sequences

Prêt pour déploiement et tests sur le VPS.
This commit is contained in:
Manus
2026-02-03 11:04:37 -05:00
parent 70f9055073
commit 98c3b21ec1
9 changed files with 2868 additions and 8 deletions

View File

@@ -185,3 +185,76 @@ export async function supprimerPresence(presenceId: number) {
return { success: true };
}
/**
* Valider la présence d'un formateur (par QR code ou manuellement)
*/
export async function validerPresenceFormateur(params: {
formateurId: number;
sequenceId: number;
dateFormationId: number;
periode: "matin" | "apres_midi";
modeValidation: "qrcode" | "manuel";
commentaire?: string;
signatureUrl?: string;
signatureS3Key?: string;
}) {
const db = await getDb();
if (!db) throw new Error("Database not available");
// Récupérer la date de formation
const dateFormation = await db
.select()
.from(datesFormation)
.where(eq(datesFormation.id, params.dateFormationId))
.limit(1);
if (dateFormation.length === 0) {
throw new Error("Date de formation introuvable");
}
// Vérifier que la date actuelle est le jour de la formation ou après
const now = new Date();
const dateDebut = new Date(dateFormation[0].dateDebut);
// Réinitialiser les heures pour comparer uniquement les dates
now.setHours(0, 0, 0, 0);
dateDebut.setHours(0, 0, 0, 0);
if (now < dateDebut) {
throw new Error("Vous ne pouvez pas émarger avant la date de formation");
}
// Vérifier si la présence existe déjà pour cette période
const presenceExistante = await db
.select()
.from(presences)
.where(
and(
eq(presences.formateurId, params.formateurId),
eq(presences.dateFormationId, params.dateFormationId),
eq(presences.periode, params.periode),
eq(presences.typeUtilisateur, 'formateur')
)
);
if (presenceExistante.length > 0) {
throw new Error(`Présence déjà validée pour ${params.periode === 'matin' ? 'le matin' : 'l\'après-midi'}`);
}
// Créer la présence formateur
await db.insert(presences).values({
formateurId: params.formateurId,
dateFormationId: params.dateFormationId,
periode: params.periode,
typeUtilisateur: 'formateur',
heurePresence: new Date(),
modeValidation: params.modeValidation,
commentaire: params.commentaire,
signatureUrl: params.signatureUrl,
signatureS3Key: params.signatureS3Key,
dateSigned: params.signatureUrl ? new Date() : undefined,
});
return { success: true };
}

View File

@@ -2509,17 +2509,69 @@ export const appRouter = router({
};
}),
// Générer un QR code pour le formateur
generateQRCodeFormateur: protectedProcedure
.input(z.object({
sequenceId: z.number(),
}))
.mutation(async ({ input, ctx }) => {
const { generateQRToken } = await import("./qrCodeGenerator");
const { getDb } = await import("./db");
const { sequences } = await import("../drizzle/schema");
const { eq } = await import("drizzle-orm");
const QRCode = (await import("qrcode")).default;
const { getParametres } = await import("./parametresDb");
const db = await getDb();
if (!db) throw new Error("Database not available");
// Vérifier que la séquence existe
const sequence = await db.select().from(sequences).where(eq(sequences.id, input.sequenceId)).limit(1);
if (sequence.length === 0) {
throw new Error("Séquence introuvable");
}
// Générer un nouveau token pour le formateur
let token = sequence[0].qrCodeFormateurToken;
if (!token) {
token = generateQRToken();
await db.update(sequences).set({ qrCodeFormateurToken: token }).where(eq(sequences.id, input.sequenceId));
}
// Générer le QR code avec URL spécifique formateur
const parametres = await getParametres();
const url = `${parametres.urlPublique}/emargement-formateur/${token}`;
const qrCodeDataURL = await QRCode.toDataURL(url, {
errorCorrectionLevel: "H",
type: "image/png",
width: 400,
margin: 2,
color: {
dark: "#000000",
light: "#FFFFFF",
},
});
return {
token,
qrCodeDataURL,
};
}),
// Valider une présence (scan QR code ou manuel)
valider: publicProcedure
.input(z.object({
token: z.string().optional(),
inscriptionId: z.number(),
dateFormationId: z.number(),
inscriptionId: z.number().optional(),
dateFormationId: z.number().optional(),
periode: z.enum(["matin", "apres_midi"]),
modeValidation: z.enum(["qrcode", "manuel"]),
validateurId: z.number().optional(),
commentaire: z.string().optional(),
signatureDataUrl: z.string().optional(),
email: z.string().optional(),
typeUtilisateur: z.enum(["apprenant", "formateur"]).optional(),
}))
.mutation(async ({ input }) => {
const { validerPresence } = await import("./presenceDb");
@@ -2530,10 +2582,91 @@ export const appRouter = router({
const db = await getDb();
if (!db) throw new Error("Database not available");
// Cas formateur : logique spécifique
if (input.typeUtilisateur === "formateur") {
const { formateurs, datesFormation } = await import("../drizzle/schema");
const { and, sql } = await import("drizzle-orm");
const { storagePut } = await import("./storage");
const crypto = await import("crypto");
// Vérifier le token formateur
if (input.modeValidation === "qrcode" && input.token) {
const sequence = await db.select().from(sequences).where(eq(sequences.qrCodeFormateurToken, input.token)).limit(1);
if (sequence.length === 0) {
throw new Error("QR code formateur invalide");
}
}
// Récupérer le formateur par email
if (!input.email) throw new Error("Email formateur requis");
const formateurData = await db.select().from(formateurs).where(eq(formateurs.email, input.email)).limit(1);
if (formateurData.length === 0) {
throw new Error("Formateur introuvable avec cet email");
}
// Trouver la séquence associée au token
const sequenceData = await db.select().from(sequences).where(eq(sequences.qrCodeFormateurToken, input.token || "")).limit(1);
if (sequenceData.length === 0) {
throw new Error("Séquence introuvable");
}
const finalSequenceId = sequenceData[0].id;
// Trouver automatiquement la date du jour
const today = new Date();
today.setHours(0, 0, 0, 0);
const datesToday = await db
.select()
.from(datesFormation)
.where(
and(
eq(datesFormation.sequenceId, finalSequenceId),
sql`DATE(${datesFormation.dateDebut}) <= CURDATE()`,
sql`DATE(${datesFormation.dateFin}) >= CURDATE()`
)
)
.limit(1);
if (datesToday.length === 0) {
throw new Error("Aucune date de formation ne correspond à aujourd'hui");
}
const dateFormId = datesToday[0].id;
// Stocker la signature sur S3
let signatureUrl: string | undefined;
let signatureS3Key: string | undefined;
if (input.signatureDataUrl) {
const formationId = sequenceData[0].formationId;
const sequenceId = sequenceData[0].id;
const randomSuffix = crypto.randomBytes(8).toString("hex");
const fileName = `signature-formateur-${formateurData[0].id}-${dateFormId}-${randomSuffix}.png`;
const signatureS3Key = `signatures/${formationId}-${sequenceId}/${fileName}`;
const base64Data = input.signatureDataUrl.split(",")[1];
const buffer = Buffer.from(base64Data, "base64");
const { url } = await storagePut(signatureS3Key, buffer, "image/png");
signatureUrl = url;
}
// Valider la présence formateur
const { validerPresenceFormateur } = await import("./presenceDb");
const result = await validerPresenceFormateur({
formateurId: formateurData[0].id,
sequenceId: finalSequenceId,
dateFormationId: dateFormId,
periode: input.periode,
modeValidation: input.modeValidation,
commentaire: input.commentaire,
signatureUrl,
signatureS3Key,
});
return { success: true, presence: result };
}
// Cas apprenant : logique existante
// Si mode QR code, vérifier le token
if (input.modeValidation === "qrcode" && input.token) {
// Récupérer l'inscription pour vérifier la séquence
if (!input.inscriptionId) throw new Error("Inscription requise pour un apprenant");
const inscription = await db.select().from(inscriptions).where(eq(inscriptions.id, input.inscriptionId)).limit(1);
if (inscription.length === 0) {
throw new Error("Inscription introuvable");
@@ -2546,6 +2679,10 @@ export const appRouter = router({
}
}
// Vérifier que inscriptionId et dateFormationId sont fournis pour un apprenant
if (!input.inscriptionId) throw new Error("Inscription requise pour un apprenant");
if (!input.dateFormationId) throw new Error("Date de formation requise pour un apprenant");
// Stocker la signature localement si fournie
let signatureUrl: string | undefined;
let signatureS3Key: string | undefined;