109 lines
No EOL
3.8 KiB
TypeScript
109 lines
No EOL
3.8 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
|
|
import { createClient } from "@supabase/supabase-js";
|
|
import { cookies } from "next/headers";
|
|
import { v4 as uuidv4 } from "uuid";
|
|
|
|
type NoteInsert = {
|
|
contract_id: string;
|
|
organization_id: string;
|
|
content: string;
|
|
source: string;
|
|
};
|
|
|
|
function generateContractReference(): string {
|
|
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
const digits = "0123456789";
|
|
const chars = letters + digits;
|
|
return "RG" + Array.from({ length: 6 }, () => chars[Math.floor(Math.random() * chars.length)]).join("");
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
const supabase = createRouteHandlerClient({ cookies });
|
|
const { data: { user } } = await supabase.auth.getUser();
|
|
if (!user) return NextResponse.json({ error: "Non authentifié." }, { status: 401 });
|
|
|
|
try {
|
|
const body = await request.json();
|
|
|
|
console.log("Body reçu pour création contrat RG:", body);
|
|
|
|
// Générer un identifiant unique pour le contrat
|
|
const contractId = uuidv4();
|
|
const providedReference = typeof body.reference === "string" ? body.reference.trim().toUpperCase() : "";
|
|
const contractNumber = providedReference || generateContractReference();
|
|
|
|
// Détecter si l'utilisateur est staff
|
|
let isStaff = false;
|
|
console.log('🔍 [DEBUG RG] Début détection staff pour user:', user.id);
|
|
|
|
try {
|
|
const { data: staffRow } = await supabase
|
|
.from('staff_users')
|
|
.select('is_staff')
|
|
.eq('user_id', user.id)
|
|
.maybeSingle();
|
|
console.log('🔍 [DEBUG RG] Résultat query staff_users:', staffRow);
|
|
isStaff = !!staffRow?.is_staff;
|
|
console.log('🔍 [DEBUG RG] isStaff depuis DB:', isStaff);
|
|
} catch (err) {
|
|
console.log('🔍 [DEBUG RG] Erreur query staff_users, fallback metadata:', err);
|
|
const userMeta = user.user_metadata || {};
|
|
const appMeta = user.app_metadata || {};
|
|
isStaff = Boolean(
|
|
userMeta.is_staff === true ||
|
|
userMeta.role === 'staff' ||
|
|
(Array.isArray(appMeta?.roles) && appMeta.roles.includes('staff'))
|
|
);
|
|
console.log('🔍 [DEBUG RG] isStaff depuis metadata:', isStaff);
|
|
}
|
|
|
|
// Appeler l'endpoint CDDU existant avec les données adaptées pour RG
|
|
const adaptedData = {
|
|
...body,
|
|
// Propager la préférence d'envoi d'e-mail si fournie
|
|
send_email_confirmation: body.send_email_confirmation !== false,
|
|
// Marquer explicitement que c'est un contrat RG
|
|
regime: "RG",
|
|
// Les champs production ne sont pas utilisés en RG
|
|
spectacle: "N/A - Régime Général",
|
|
production_id: null,
|
|
numero_objet: null,
|
|
// Pas de multi-mois en RG
|
|
multi_mois: false,
|
|
// Pas de champs spécifiques CDDU
|
|
nb_representations: null,
|
|
nb_services_repetition: null,
|
|
dates_representations: null,
|
|
dates_repetitions: null,
|
|
heures_total: null,
|
|
minutes_total: null,
|
|
jours_travail: null,
|
|
};
|
|
|
|
// Pour contourner le problème de l'appel HTTP externe qui perd la session,
|
|
// on fait l'appel direct à l'API CDDU en interne
|
|
const apiUrl = new URL('/api/cddu-contracts', request.url);
|
|
const cdduRequest = new NextRequest(apiUrl, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Cookie': request.headers.get('Cookie') || '',
|
|
},
|
|
body: JSON.stringify(adaptedData),
|
|
});
|
|
|
|
// Import de la fonction POST de l'API CDDU pour l'appeler directement
|
|
const { POST: cdduPost } = await import('../cddu-contracts/route');
|
|
const result = await cdduPost(cdduRequest);
|
|
|
|
return result;
|
|
|
|
} catch (error) {
|
|
console.error('Erreur API RG contracts:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Erreur interne du serveur' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
} |