200 lines
7.3 KiB
TypeScript
200 lines
7.3 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { createClient } from '@supabase/supabase-js';
|
|
import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs';
|
|
import { cookies } from 'next/headers';
|
|
|
|
// GET: Récupérer la signature d'une organisation
|
|
export async function GET(req: NextRequest) {
|
|
try {
|
|
// Vérifier l'authentification
|
|
const supabaseAuth = createRouteHandlerClient({ cookies });
|
|
const { data: { user } } = await supabaseAuth.auth.getUser();
|
|
|
|
if (!user) {
|
|
console.log('❌ [GET /api/organization/signature] Non authentifié');
|
|
return NextResponse.json({ error: 'Non authentifié' }, { status: 401 });
|
|
}
|
|
|
|
console.log('✅ [GET /api/organization/signature] Utilisateur authentifié:', user.id);
|
|
|
|
// Récupérer l'org_id depuis les paramètres
|
|
const { searchParams } = new URL(req.url);
|
|
const orgId = searchParams.get('org_id');
|
|
|
|
console.log('🔍 [GET /api/organization/signature] org_id:', orgId);
|
|
|
|
if (!orgId) {
|
|
console.log('❌ [GET /api/organization/signature] org_id manquant');
|
|
return NextResponse.json({ error: 'org_id manquant' }, { status: 400 });
|
|
}
|
|
|
|
// Créer un client avec service role pour lire organization_details
|
|
const supabase = createClient(
|
|
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
|
process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
|
{ auth: { persistSession: false } }
|
|
);
|
|
|
|
// Récupérer la signature depuis organization_details
|
|
const { data, error } = await supabase
|
|
.from('organization_details')
|
|
.select('signature_b64')
|
|
.eq('org_id', orgId)
|
|
.maybeSingle();
|
|
|
|
console.log('📦 [GET /api/organization/signature] Query result:', { data, error });
|
|
|
|
if (error) {
|
|
console.error('❌ [GET /api/organization/signature] Erreur Supabase:', error);
|
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
|
}
|
|
|
|
const signature = data?.signature_b64 || null;
|
|
console.log('✅ [GET /api/organization/signature] Signature:', signature ? `présente (${signature.substring(0, 50)}...)` : 'absente');
|
|
|
|
return NextResponse.json({
|
|
signature_b64: signature
|
|
});
|
|
|
|
} catch (e: any) {
|
|
console.error('❌ [GET /api/organization/signature] Exception:', e);
|
|
return NextResponse.json({ error: e.message }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
// POST: Sauvegarder ou mettre à jour la signature d'une organisation
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
// Vérifier l'authentification
|
|
const supabaseAuth = createRouteHandlerClient({ cookies });
|
|
const { data: { user } } = await supabaseAuth.auth.getUser();
|
|
|
|
if (!user) {
|
|
console.log('❌ [POST /api/organization/signature] Non authentifié');
|
|
return NextResponse.json({ error: 'Non authentifié' }, { status: 401 });
|
|
}
|
|
|
|
console.log('✅ [POST /api/organization/signature] Utilisateur authentifié:', user.id);
|
|
|
|
const body = await req.json();
|
|
const { org_id, signature_b64 } = body;
|
|
|
|
console.log('💾 [POST /api/organization/signature] org_id:', org_id);
|
|
console.log('💾 [POST /api/organization/signature] signature_b64 length:', signature_b64?.length);
|
|
|
|
if (!org_id) {
|
|
return NextResponse.json({ error: 'org_id manquant' }, { status: 400 });
|
|
}
|
|
|
|
if (!signature_b64 || typeof signature_b64 !== 'string') {
|
|
console.log('❌ [POST /api/organization/signature] signature_b64 invalide:', typeof signature_b64);
|
|
return NextResponse.json({ error: 'signature_b64 invalide' }, { status: 400 });
|
|
}
|
|
|
|
// Créer un client avec service role pour écrire dans organization_details
|
|
const supabase = createClient(
|
|
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
|
process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
|
{ auth: { persistSession: false } }
|
|
);
|
|
|
|
console.log('📝 [POST /api/organization/signature] Tentative upsert...');
|
|
|
|
// Vérifier d'abord si l'enregistrement existe
|
|
const { data: existing, error: selectError } = await supabase
|
|
.from('organization_details')
|
|
.select('org_id')
|
|
.eq('org_id', org_id)
|
|
.maybeSingle();
|
|
|
|
if (selectError) {
|
|
console.error('❌ [POST /api/organization/signature] Erreur SELECT:', selectError);
|
|
} else {
|
|
console.log('📦 [POST /api/organization/signature] Enregistrement existant:', existing ? 'oui' : 'non');
|
|
}
|
|
|
|
// Upsert dans organization_details
|
|
const { error: upsertError } = await supabase
|
|
.from('organization_details')
|
|
.upsert({
|
|
org_id: org_id,
|
|
signature_b64: signature_b64
|
|
}, {
|
|
onConflict: 'org_id'
|
|
});
|
|
|
|
if (upsertError) {
|
|
console.error('❌ [POST /api/organization/signature] Erreur upsert Supabase:', upsertError);
|
|
console.error('❌ [POST /api/organization/signature] Détails erreur:', JSON.stringify(upsertError, null, 2));
|
|
return NextResponse.json({ error: upsertError.message }, { status: 500 });
|
|
}
|
|
|
|
console.log('✅ [POST /api/organization/signature] Signature sauvegardée avec succès');
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: 'Signature enregistrée avec succès'
|
|
});
|
|
|
|
} catch (e: any) {
|
|
console.error('❌ [POST /api/organization/signature] Exception:', e);
|
|
return NextResponse.json({ error: e.message }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
// DELETE: Supprimer la signature d'une organisation
|
|
export async function DELETE(req: NextRequest) {
|
|
try {
|
|
// Vérifier l'authentification
|
|
const supabaseAuth = createRouteHandlerClient({ cookies });
|
|
const { data: { user } } = await supabaseAuth.auth.getUser();
|
|
|
|
if (!user) {
|
|
console.log('❌ [DELETE /api/organization/signature] Non authentifié');
|
|
return NextResponse.json({ error: 'Non authentifié' }, { status: 401 });
|
|
}
|
|
|
|
console.log('✅ [DELETE /api/organization/signature] Utilisateur authentifié:', user.id);
|
|
|
|
const body = await req.json();
|
|
const { org_id } = body;
|
|
|
|
console.log('🗑️ [DELETE /api/organization/signature] org_id:', org_id);
|
|
|
|
if (!org_id) {
|
|
return NextResponse.json({ error: 'org_id manquant' }, { status: 400 });
|
|
}
|
|
|
|
// Créer un client avec service role pour écrire dans organization_details
|
|
const supabase = createClient(
|
|
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
|
process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
|
{ auth: { persistSession: false } }
|
|
);
|
|
|
|
console.log('📝 [DELETE /api/organization/signature] Tentative suppression...');
|
|
|
|
// Mettre à jour en mettant signature_b64 à NULL
|
|
const { error: updateError } = await supabase
|
|
.from('organization_details')
|
|
.update({ signature_b64: null })
|
|
.eq('org_id', org_id);
|
|
|
|
if (updateError) {
|
|
console.error('❌ [DELETE /api/organization/signature] Erreur update Supabase:', updateError);
|
|
console.error('❌ [DELETE /api/organization/signature] Détails erreur:', JSON.stringify(updateError, null, 2));
|
|
return NextResponse.json({ error: updateError.message }, { status: 500 });
|
|
}
|
|
|
|
console.log('✅ [DELETE /api/organization/signature] Signature supprimée avec succès');
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: 'Signature supprimée avec succès'
|
|
});
|
|
|
|
} catch (e: any) {
|
|
console.error('❌ [DELETE /api/organization/signature] Exception:', e);
|
|
return NextResponse.json({ error: e.message }, { status: 500 });
|
|
}
|
|
}
|