fix: Enregistrer notes lors de l'édition de contrat client

- Récupérer org_id depuis le contrat pour créer la note correctement
- Fonctionne maintenant pour staff (org.id null) et clients
- Ajouter envoi d'email de notification à paie@odentas.fr
- Alignement avec la logique de POST /api/contrats/[id]/notes
This commit is contained in:
odentas 2025-12-16 21:16:03 +01:00
parent f5be6a5b24
commit 5131552e18

View file

@ -449,25 +449,75 @@ export async function PATCH(req: NextRequest, { params }: { params: { id: string
try {
const rawNote = typeof requestBody.notes === 'string' ? requestBody.notes.trim() : '';
if (rawNote) {
const notePayload = {
contract_id: contractId,
organization_id: org.id,
content: rawNote,
source: 'Client',
};
let noteInsertResult;
// Récupérer le contrat pour avoir l'org_id et contract_number
let contractForNote;
if (org.isStaff) {
const admin = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL || "", process.env.SUPABASE_SERVICE_ROLE_KEY || "");
noteInsertResult = await admin.from('notes').insert([notePayload]);
const { data } = await admin.from('cddu_contracts').select('org_id, contract_number').eq('id', contractId).single();
contractForNote = data;
} else {
noteInsertResult = await supabase.from('notes').insert([notePayload]);
const { data } = await supabase.from('cddu_contracts').select('org_id, contract_number').eq('id', contractId).single();
contractForNote = data;
}
if (contractForNote?.org_id) {
const notePayload = {
contract_id: contractId,
organization_id: contractForNote.org_id,
content: rawNote,
source: 'Client',
author: requestBody.author || undefined,
};
let noteInsertResult;
if (org.isStaff) {
const admin = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL || "", process.env.SUPABASE_SERVICE_ROLE_KEY || "");
noteInsertResult = await admin.from('notes').insert([notePayload]);
} else {
noteInsertResult = await supabase.from('notes').insert([notePayload]);
}
if (noteInsertResult.error) {
console.warn('⚠️ Erreur insertion note lors de la modification:', noteInsertResult.error);
if (noteInsertResult.error) {
console.warn('⚠️ Erreur insertion note lors de la modification:', noteInsertResult.error);
} else {
console.log('✅ Note créée avec succès lors de la modification:', { contractId, noteLength: rawNote.length, requestId });
// Envoyer email de notification pour la note
try {
const { sendUniversalEmailV2 } = await import('@/lib/emailTemplateService');
// Récupérer les informations de l'organisation
const { data: organization } = await supabase
.from('organizations')
.select('name, structure_api')
.eq('id', contractForNote.org_id)
.single();
if (organization) {
const userName = requestBody.author || org.name || 'Utilisateur inconnu';
await sendUniversalEmailV2({
type: 'contract-note-added',
toEmail: 'paie@odentas.fr',
data: {
organizationName: organization.name,
employerCode: organization.structure_api,
contractNumber: contractForNote.contract_number || contractId,
userName: userName,
noteContent: rawNote,
contractId: contractId,
ctaUrl: `https://espace-paie.odentas.fr/staff/contrats/${contractId}`,
},
});
console.log('✅ Email de notification envoyé pour la note ajoutée au contrat:', contractId);
}
} catch (emailError) {
console.error('❌ Erreur lors de l\'envoi de l\'email de notification de note:', emailError);
}
}
} else {
console.log('✅ Note créée avec succès lors de la modification:', { contractId, noteLength: rawNote.length, requestId });
console.warn('⚠️ Impossible de récupérer org_id du contrat pour créer la note');
}
}
} catch (noteCatchErr) {