127 lines
4.1 KiB
TypeScript
127 lines
4.1 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { DolibarrErrorResponse, DolibarrThirdParty } 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 }> {
|
|
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}`);
|
|
|
|
// Create the user in Dolibarr as a thirdparty/customer
|
|
const response = await fetch(`${apiUrl}thirdparties`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'DOLAPIKEY': process.env.DOLIBARR_API_KEY,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
name: `${userData.firstName} ${userData.lastName}`,
|
|
name_alias: userData.username,
|
|
email: userData.email,
|
|
client: '1', // Mark as customer
|
|
code_client: 'auto', // Auto-generate client code
|
|
note_private: 'Created via API integration from platform',
|
|
status: '1', // Active
|
|
}),
|
|
});
|
|
|
|
// Handle non-OK responses
|
|
if (!response.ok) {
|
|
let errorMessage = `HTTP error ${response.status}`;
|
|
|
|
try {
|
|
const errorData = await response.json() as DolibarrErrorResponse;
|
|
errorMessage = errorData.error?.message || errorMessage;
|
|
console.error('Dolibarr API error response:', errorData);
|
|
} catch (jsonError) {
|
|
console.error('Failed to parse Dolibarr error response');
|
|
}
|
|
|
|
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);
|
|
|
|
return { success: true, id: data };
|
|
} catch (error) {
|
|
console.error('Error creating Dolibarr user:', 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 }> {
|
|
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}/`;
|
|
|
|
// Search for thirdparty/customer with matching email
|
|
const response = await fetch(`${apiUrl}thirdparties?sortfield=t.rowid&sortorder=ASC&limit=1&sqlfilters=(t.email:=:'${encodeURIComponent(email)}')`, {
|
|
method: 'GET',
|
|
headers: {
|
|
'DOLAPIKEY': process.env.DOLIBARR_API_KEY,
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
console.error(`Error checking if Dolibarr user exists: HTTP ${response.status}`);
|
|
return { exists: false };
|
|
}
|
|
|
|
const data = await response.json() as DolibarrThirdParty[];
|
|
|
|
// If we got results, user exists
|
|
if (Array.isArray(data) && data.length > 0) {
|
|
return { exists: true, id: data[0].id };
|
|
}
|
|
|
|
return { exists: false };
|
|
} catch (error) {
|
|
console.error('Error checking if Dolibarr user exists:', error);
|
|
return { exists: false };
|
|
}
|
|
}
|