158 lines
4.4 KiB
TypeScript
158 lines
4.4 KiB
TypeScript
import { createSbServiceRole } from '@/lib/supabaseServer';
|
|
import crypto from 'crypto';
|
|
import { sendUniversalEmailV2 } from '@/lib/emailTemplateService';
|
|
|
|
interface GenerateTokenOptions {
|
|
salarie_id: string;
|
|
send_email?: boolean;
|
|
}
|
|
|
|
interface GenerateTokenResult {
|
|
success: boolean;
|
|
token?: string;
|
|
messageId?: string;
|
|
email_sent?: boolean;
|
|
error?: string;
|
|
}
|
|
|
|
/**
|
|
* Génère un token d'auto-déclaration pour un salarié et optionnellement envoie l'email d'invitation
|
|
*/
|
|
export async function generateAutoDeclarationToken(
|
|
options: GenerateTokenOptions
|
|
): Promise<GenerateTokenResult> {
|
|
const { salarie_id, send_email = true } = options;
|
|
|
|
try {
|
|
const supabase = createSbServiceRole();
|
|
|
|
// Récupérer les informations du salarié
|
|
const { data: salarie, error: salarieError } = await supabase
|
|
.from('salaries')
|
|
.select('id, nom, prenom, adresse_mail, code_salarie, civilite, employer_id')
|
|
.eq('id', salarie_id)
|
|
.single();
|
|
|
|
if (salarieError || !salarie) {
|
|
console.error('Erreur récupération salarié:', salarieError);
|
|
return {
|
|
success: false,
|
|
error: 'Salarié non trouvé'
|
|
};
|
|
}
|
|
|
|
// Récupérer les informations de l'employeur séparément
|
|
let organizationName = 'votre employeur';
|
|
if (salarie.employer_id) {
|
|
const { data: organization, error: orgError } = await supabase
|
|
.from('organizations')
|
|
.select('name')
|
|
.eq('id', salarie.employer_id)
|
|
.single();
|
|
|
|
console.log('🏢 [TOKEN] Organization query result:', { organization, orgError, employer_id: salarie.employer_id });
|
|
|
|
if (organization?.name) {
|
|
organizationName = organization.name;
|
|
console.log('✅ [TOKEN] Organization name found:', organizationName);
|
|
} else {
|
|
console.log('⚠️ [TOKEN] No organization name found, using default');
|
|
}
|
|
} else {
|
|
console.log('⚠️ [TOKEN] No employer_id found for salarie');
|
|
}
|
|
|
|
if (!salarie.adresse_mail) {
|
|
return {
|
|
success: false,
|
|
error: 'Email du salarié requis'
|
|
};
|
|
}
|
|
|
|
// Supprimer d'éventuels tokens existants
|
|
await supabase
|
|
.from('auto_declaration_tokens')
|
|
.delete()
|
|
.eq('salarie_id', salarie_id);
|
|
|
|
// Générer un nouveau token sécurisé
|
|
const token = crypto.randomBytes(32).toString('hex');
|
|
|
|
// Créer le token en base avec expiration dans 7 jours
|
|
const expiresAt = new Date();
|
|
expiresAt.setDate(expiresAt.getDate() + 7);
|
|
|
|
const { error: tokenError } = await supabase
|
|
.from('auto_declaration_tokens')
|
|
.insert({
|
|
token,
|
|
salarie_id: salarie_id,
|
|
expires_at: expiresAt.toISOString(),
|
|
used: false
|
|
});
|
|
|
|
if (tokenError) {
|
|
console.error('Erreur création token:', tokenError);
|
|
return {
|
|
success: false,
|
|
error: 'Erreur lors de la génération du token'
|
|
};
|
|
}
|
|
|
|
// Si on ne doit pas envoyer d'email, on s'arrête là
|
|
if (!send_email) {
|
|
return {
|
|
success: true,
|
|
token,
|
|
email_sent: false
|
|
};
|
|
}
|
|
|
|
// Préparer l'URL sécurisée pour l'auto-déclaration
|
|
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';
|
|
const autoDeclarationUrl = `${baseUrl}/auto-declaration?token=${token}`;
|
|
|
|
// Envoyer l'email d'invitation
|
|
try {
|
|
const emailResult = await sendUniversalEmailV2({
|
|
type: 'auto-declaration-invitation',
|
|
toEmail: salarie.adresse_mail,
|
|
data: {
|
|
firstName: salarie.prenom || 'Cher collaborateur',
|
|
organizationName: organizationName,
|
|
matricule: salarie.code_salarie || 'Non défini',
|
|
ctaUrl: autoDeclarationUrl
|
|
}
|
|
});
|
|
|
|
// Mettre à jour la colonne last_notif_justifs
|
|
await supabase
|
|
.from('salaries')
|
|
.update({ last_notif_justifs: new Date().toISOString() })
|
|
.eq('id', salarie_id);
|
|
|
|
return {
|
|
success: true,
|
|
token,
|
|
email_sent: true,
|
|
messageId: emailResult
|
|
};
|
|
|
|
} catch (emailError) {
|
|
console.error('Erreur envoi email invitation:', emailError);
|
|
return {
|
|
success: true,
|
|
token,
|
|
email_sent: false,
|
|
error: 'Token créé mais erreur lors de l\'envoi de l\'email'
|
|
};
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('Erreur génération token:', error);
|
|
return {
|
|
success: false,
|
|
error: 'Erreur serveur'
|
|
};
|
|
}
|
|
}
|