245 lines
8.3 KiB
TypeScript
245 lines
8.3 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { DolibarrErrorResponse, DolibarrThirdParty, DolibarrUser } from "@/app/types/dolibarr";
|
|
|
|
/**
|
|
* Create a user in Dolibarr
|
|
* @param userData User data to create in Dolibarr
|
|
* @returns Response with success status and ID or error
|
|
*/
|
|
export async function createDolibarrUser(userData: {
|
|
username: string;
|
|
firstName: string;
|
|
lastName: string;
|
|
email: string;
|
|
password: string;
|
|
}): Promise<{ success: boolean; id?: number; error?: string }> {
|
|
console.log('=== DOLIBARR CREATE USER FUNCTION CALLED ===');
|
|
try {
|
|
// Validate environment variables
|
|
if (!process.env.DOLIBARR_API_URL) {
|
|
console.error('Missing DOLIBARR_API_URL environment variable');
|
|
return { success: false, error: 'Dolibarr API URL not configured' };
|
|
}
|
|
|
|
if (!process.env.DOLIBARR_API_KEY) {
|
|
console.error('Missing DOLIBARR_API_KEY environment variable');
|
|
return { success: false, error: 'Dolibarr API key not configured' };
|
|
}
|
|
|
|
// Format the API URL properly
|
|
const apiUrl = process.env.DOLIBARR_API_URL.endsWith('/')
|
|
? process.env.DOLIBARR_API_URL
|
|
: `${process.env.DOLIBARR_API_URL}/`;
|
|
|
|
console.log(`Creating Dolibarr user for ${userData.email}`);
|
|
console.log('Full API URL:', apiUrl + 'users');
|
|
console.log('API Key (first 5 chars):', process.env.DOLIBARR_API_KEY.substring(0, 5) + '...');
|
|
|
|
// Format the user data for Dolibarr user creation
|
|
const requestBody = {
|
|
login: userData.username,
|
|
lastname: userData.lastName,
|
|
firstname: userData.firstName,
|
|
password: userData.password,
|
|
email: userData.email,
|
|
admin: 0, // Not an administrator
|
|
employee: 1, // Is an employee
|
|
signature: `${userData.firstName} ${userData.lastName}`,
|
|
note_private: 'Created via API integration from platform',
|
|
entity: 1, // Main entity
|
|
status: 1 // Active
|
|
};
|
|
|
|
console.log('Request body:', JSON.stringify(requestBody, null, 2));
|
|
|
|
// Create the user in Dolibarr as a user account
|
|
const response = await fetch(`${apiUrl}users`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'DOLAPIKEY': process.env.DOLIBARR_API_KEY,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(requestBody),
|
|
});
|
|
|
|
console.log('Dolibarr API response status:', response.status);
|
|
|
|
// Handle non-OK responses
|
|
if (!response.ok) {
|
|
let errorMessage = `HTTP error ${response.status}`;
|
|
|
|
try {
|
|
const errorData = await response.json() as DolibarrErrorResponse;
|
|
console.error('Dolibarr API error response full data:', errorData);
|
|
errorMessage = errorData.error?.message || errorMessage;
|
|
console.error('Dolibarr API error response:', errorMessage);
|
|
} catch (jsonError) {
|
|
console.error('Failed to parse Dolibarr error response');
|
|
const textResponse = await response.text();
|
|
console.error('Raw error response:', textResponse);
|
|
}
|
|
|
|
return {
|
|
success: false,
|
|
error: `Failed to create Dolibarr user: ${errorMessage}`
|
|
};
|
|
}
|
|
|
|
// Parse the successful response
|
|
const data = await response.json();
|
|
console.log('Dolibarr user created successfully with ID:', data);
|
|
console.log('=== END DOLIBARR CREATE USER FUNCTION ===');
|
|
|
|
return { success: true, id: data };
|
|
} catch (error) {
|
|
console.error('Error creating Dolibarr user:', error);
|
|
if (error instanceof Error) {
|
|
console.error('Error details:', {
|
|
name: error.name,
|
|
message: error.message,
|
|
stack: error.stack
|
|
});
|
|
}
|
|
console.log('=== END DOLIBARR CREATE USER FUNCTION WITH ERROR ===');
|
|
return {
|
|
success: false,
|
|
error: error instanceof Error ? error.message : 'Unknown error'
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if a user exists in Dolibarr by email
|
|
* @param email Email to search for
|
|
* @returns Boolean indicating if user exists and user ID if found
|
|
*/
|
|
export async function checkDolibarrUserExists(email: string): Promise<{ exists: boolean; id?: number }> {
|
|
console.log('=== DOLIBARR CHECK USER FUNCTION CALLED ===');
|
|
try {
|
|
if (!process.env.DOLIBARR_API_URL || !process.env.DOLIBARR_API_KEY) {
|
|
console.error('Missing Dolibarr API configuration');
|
|
return { exists: false };
|
|
}
|
|
|
|
// Format the API URL
|
|
const apiUrl = process.env.DOLIBARR_API_URL.endsWith('/')
|
|
? process.env.DOLIBARR_API_URL
|
|
: `${process.env.DOLIBARR_API_URL}/`;
|
|
|
|
// Use the users endpoint instead of thirdparties
|
|
const queryUrl = `${apiUrl}users?sortfield=t.rowid&sortorder=ASC&limit=1&sqlfilters=(t.email:=:'${encodeURIComponent(email)}')`;
|
|
console.log('Full search URL:', queryUrl);
|
|
|
|
// Search for user with matching email
|
|
const response = await fetch(queryUrl, {
|
|
method: 'GET',
|
|
headers: {
|
|
'DOLAPIKEY': process.env.DOLIBARR_API_KEY,
|
|
},
|
|
});
|
|
|
|
console.log('Dolibarr check user API response status:', response.status);
|
|
|
|
if (!response.ok) {
|
|
console.error(`Error checking if Dolibarr user exists: 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 { exists: false };
|
|
}
|
|
|
|
const data = await response.json() as DolibarrUser[];
|
|
console.log('Dolibarr user search response:', data);
|
|
|
|
// If we got results, user exists
|
|
if (Array.isArray(data) && data.length > 0) {
|
|
console.log('User found in Dolibarr with ID:', data[0].id);
|
|
console.log('=== END DOLIBARR CHECK USER FUNCTION (USER FOUND) ===');
|
|
return { exists: true, id: data[0].id };
|
|
}
|
|
|
|
console.log('User not found in Dolibarr');
|
|
console.log('=== END DOLIBARR CHECK USER FUNCTION (USER NOT FOUND) ===');
|
|
return { exists: false };
|
|
} catch (error) {
|
|
console.error('Error checking if Dolibarr user exists:', error);
|
|
if (error instanceof Error) {
|
|
console.error('Error details:', {
|
|
name: error.name,
|
|
message: error.message,
|
|
stack: error.stack
|
|
});
|
|
}
|
|
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'
|
|
};
|
|
}
|
|
}
|