From 75854b3b28d11238edd20c1bbc7ae3796c354de3 Mon Sep 17 00:00:00 2001 From: alma Date: Sun, 4 May 2025 10:01:29 +0200 Subject: [PATCH] dolibarr user --- app/api/users/route.ts | 37 +++++++++++++++++- components/users/users-table.tsx | 6 +-- lib/dolibarr-api.ts | 66 ++++++++++++++++++++++++++++++++ 3 files changed, 104 insertions(+), 5 deletions(-) diff --git a/app/api/users/route.ts b/app/api/users/route.ts index 6b3ff3ab..06947784 100644 --- a/app/api/users/route.ts +++ b/app/api/users/route.ts @@ -1,7 +1,7 @@ import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { NextResponse } from "next/server"; -import { createDolibarrUser, checkDolibarrUserExists } from "@/lib/dolibarr-api"; +import { createDolibarrUser, checkDolibarrUserExists, deleteDolibarrUser } from "@/lib/dolibarr-api"; export async function GET() { const session = await getServerSession(authOptions); @@ -604,6 +604,8 @@ export async function DELETE(req: Request) { ); } + console.log(`Deleting user: ID=${userId}, email=${email}`); + const token = await getAdminToken(); if (!token) { return NextResponse.json({ error: "Erreur d'authentification" }, { status: 401 }); @@ -629,6 +631,8 @@ export async function DELETE(req: Request) { ); } + console.log("Successfully deleted user from Keycloak"); + // Delete user from Leantime const leantimeResult = await deleteLeantimeUser(email); @@ -636,9 +640,38 @@ export async function DELETE(req: Request) { console.error("Leantime user deletion failed:", leantimeResult.error); // We don't return an error here since Keycloak user was deleted successfully // We just log the error and continue + } else { + console.log("Successfully deleted user from Leantime"); } - return NextResponse.json({ success: true }); + // Check if user exists in Dolibarr and delete if found + console.log(`Checking if user exists in Dolibarr with email: ${email}`); + try { + const dolibarrUser = await checkDolibarrUserExists(email); + + if (dolibarrUser.exists && dolibarrUser.id) { + console.log(`User found in Dolibarr with ID: ${dolibarrUser.id}. Proceeding with deletion.`); + const dolibarrResult = await deleteDolibarrUser(dolibarrUser.id); + + if (!dolibarrResult.success) { + console.error("Dolibarr user deletion failed:", dolibarrResult.error); + // We don't return an error here since Keycloak user was deleted successfully + // We just log the error and continue + } else { + console.log(`Successfully deleted user from Dolibarr with ID: ${dolibarrUser.id}`); + } + } else { + console.log("User not found in Dolibarr, skipping Dolibarr deletion"); + } + } catch (dolibarrError) { + console.error("Error during Dolibarr user deletion:", dolibarrError); + // Continue despite Dolibarr errors + } + + return NextResponse.json({ + success: true, + message: "User deleted from all systems" + }); } catch (error) { console.error("Error deleting user:", error); diff --git a/components/users/users-table.tsx b/components/users/users-table.tsx index 6fcf1781..ae95072f 100644 --- a/components/users/users-table.tsx +++ b/components/users/users-table.tsx @@ -292,9 +292,9 @@ export function UsersTable({ userRole = [] }: UsersTableProps) { } }; - const handleDelete = async (userId: string) => { + const handleDelete = async (userId: string, email: string) => { try { - const response = await fetch(`/api/users/${userId}`, { + const response = await fetch(`/api/users?id=${userId}&email=${encodeURIComponent(email)}`, { method: "DELETE", }); @@ -618,7 +618,7 @@ export function UsersTable({ userRole = [] }: UsersTableProps) { onClick={(e) => { e.preventDefault(); e.stopPropagation(); - handleDelete(user.id); + handleDelete(user.id, user.email); }} > diff --git a/lib/dolibarr-api.ts b/lib/dolibarr-api.ts index 7539289b..47a502e8 100644 --- a/lib/dolibarr-api.ts +++ b/lib/dolibarr-api.ts @@ -176,4 +176,70 @@ export async function checkDolibarrUserExists(email: string): Promise<{ exists: console.log('=== END DOLIBARR CHECK USER FUNCTION WITH ERROR ==='); return { exists: false }; } +} + +/** + * Delete a user from Dolibarr by their ID + * @param userId The Dolibarr user ID to delete + * @returns Response with success status and any error message + */ +export async function deleteDolibarrUser(userId: number): Promise<{ success: boolean; error?: string }> { + console.log('=== DOLIBARR DELETE USER FUNCTION CALLED ==='); + try { + if (!process.env.DOLIBARR_API_URL || !process.env.DOLIBARR_API_KEY) { + console.error('Missing Dolibarr API configuration'); + return { success: false, error: 'Dolibarr API not configured' }; + } + + // Format the API URL + const apiUrl = process.env.DOLIBARR_API_URL.endsWith('/') + ? process.env.DOLIBARR_API_URL + : `${process.env.DOLIBARR_API_URL}/`; + + const deleteUrl = `${apiUrl}users/${userId}`; + console.log(`Deleting Dolibarr user with ID ${userId}`); + console.log('Full delete URL:', deleteUrl); + + // Delete user in Dolibarr + const response = await fetch(deleteUrl, { + method: 'DELETE', + headers: { + 'DOLAPIKEY': process.env.DOLIBARR_API_KEY, + }, + }); + + console.log('Dolibarr delete API response status:', response.status); + + if (!response.ok) { + console.error(`Error deleting Dolibarr user: HTTP ${response.status}`); + try { + const errorText = await response.text(); + console.error('Error response body:', errorText); + } catch (e) { + console.error('Could not read error response body'); + } + return { + success: false, + error: `Failed to delete user in Dolibarr: HTTP ${response.status}` + }; + } + + console.log('Successfully deleted user from Dolibarr'); + console.log('=== END DOLIBARR DELETE USER FUNCTION ==='); + return { success: true }; + } catch (error) { + console.error('Error deleting Dolibarr user:', error); + if (error instanceof Error) { + console.error('Error details:', { + name: error.name, + message: error.message, + stack: error.stack + }); + } + console.log('=== END DOLIBARR DELETE USER FUNCTION WITH ERROR ==='); + return { + success: false, + error: error instanceof Error ? error.message : 'Unknown error' + }; + } } \ No newline at end of file