dolibarr user
This commit is contained in:
parent
acc7a44165
commit
b629102a51
@ -451,41 +451,81 @@ export async function POST(req: Request) {
|
||||
// We just log the error and continue
|
||||
}
|
||||
|
||||
// Add detailed diagnostic logging
|
||||
console.log('=== DOLIBARR INTEGRATION DIAGNOSTICS ===');
|
||||
console.log('Role check values:', {
|
||||
allRoles: validRoles,
|
||||
exactCase: {
|
||||
hasMediationExact: validRoles.includes('Mediation'),
|
||||
hasExpressionExact: validRoles.includes('Expression')
|
||||
},
|
||||
lowerCase: {
|
||||
hasMediationLower: validRoles.includes('mediation'),
|
||||
hasExpressionLower: validRoles.includes('expression')
|
||||
}
|
||||
});
|
||||
console.log('Environment variables:', {
|
||||
dolibarrUrlExists: !!process.env.DOLIBARR_API_URL,
|
||||
dolibarrUrl: process.env.DOLIBARR_API_URL ? `${process.env.DOLIBARR_API_URL.substring(0, 10)}...` : 'undefined',
|
||||
dolibarrKeyExists: !!process.env.DOLIBARR_API_KEY,
|
||||
dolibarrKeyFirstChars: process.env.DOLIBARR_API_KEY ? `${process.env.DOLIBARR_API_KEY.substring(0, 5)}...` : 'undefined'
|
||||
});
|
||||
|
||||
// Check if the user has mediation or expression role and create in Dolibarr if needed
|
||||
const hasMediationRole = validRoles.includes('mediation');
|
||||
const hasExpressionRole = validRoles.includes('expression');
|
||||
|
||||
console.log('Role check results:', {
|
||||
hasMediationRole,
|
||||
hasExpressionRole,
|
||||
shouldCreateInDolibarr: hasMediationRole || hasExpressionRole
|
||||
});
|
||||
|
||||
let dolibarrUserId = null;
|
||||
|
||||
if (hasMediationRole || hasExpressionRole) {
|
||||
console.log(`User has special role (mediation: ${hasMediationRole}, expression: ${hasExpressionRole}), creating in Dolibarr`);
|
||||
|
||||
// First check if the user already exists in Dolibarr
|
||||
const existingUser = await checkDolibarrUserExists(data.email);
|
||||
|
||||
if (existingUser.exists) {
|
||||
console.log(`User already exists in Dolibarr with ID: ${existingUser.id}`);
|
||||
dolibarrUserId = existingUser.id;
|
||||
} else {
|
||||
// Create user in Dolibarr
|
||||
const dolibarrResult = await createDolibarrUser({
|
||||
username: data.username,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
});
|
||||
|
||||
if (dolibarrResult.success) {
|
||||
console.log(`User created in Dolibarr with ID: ${dolibarrResult.id}`);
|
||||
dolibarrUserId = dolibarrResult.id;
|
||||
try {
|
||||
// First check if the user already exists in Dolibarr
|
||||
console.log('Checking if user already exists in Dolibarr with email:', data.email);
|
||||
const existingUser = await checkDolibarrUserExists(data.email);
|
||||
|
||||
if (existingUser.exists) {
|
||||
console.log(`User already exists in Dolibarr with ID: ${existingUser.id}`);
|
||||
dolibarrUserId = existingUser.id;
|
||||
} else {
|
||||
console.error("Dolibarr user creation failed:", dolibarrResult.error);
|
||||
// We don't return an error here since Keycloak user was created successfully
|
||||
// We just log the error and continue
|
||||
// Create user in Dolibarr
|
||||
console.log('Creating new user in Dolibarr with data:', {
|
||||
username: data.username,
|
||||
email: data.email,
|
||||
name: `${data.firstName} ${data.lastName}`
|
||||
});
|
||||
|
||||
const dolibarrResult = await createDolibarrUser({
|
||||
username: data.username,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
});
|
||||
|
||||
if (dolibarrResult.success) {
|
||||
console.log(`User created in Dolibarr with ID: ${dolibarrResult.id}`);
|
||||
dolibarrUserId = dolibarrResult.id;
|
||||
} else {
|
||||
console.error("Dolibarr user creation failed:", dolibarrResult.error);
|
||||
// We don't return an error here since Keycloak user was created successfully
|
||||
// We just log the error and continue
|
||||
}
|
||||
}
|
||||
} catch (dolibarrError) {
|
||||
console.error('Unexpected error during Dolibarr integration:', dolibarrError);
|
||||
}
|
||||
} else {
|
||||
console.log('User does not have mediation or expression role, skipping Dolibarr creation');
|
||||
}
|
||||
console.log('=== END DOLIBARR INTEGRATION DIAGNOSTICS ===');
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
|
||||
@ -13,6 +13,7 @@ export async function createDolibarrUser(userData: {
|
||||
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) {
|
||||
@ -31,6 +32,20 @@ export async function createDolibarrUser(userData: {
|
||||
: `${process.env.DOLIBARR_API_URL}/`;
|
||||
|
||||
console.log(`Creating Dolibarr user for ${userData.email}`);
|
||||
console.log('Full API URL:', apiUrl + 'thirdparties');
|
||||
console.log('API Key (first 5 chars):', process.env.DOLIBARR_API_KEY.substring(0, 5) + '...');
|
||||
|
||||
const requestBody = {
|
||||
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
|
||||
};
|
||||
|
||||
console.log('Request body:', JSON.stringify(requestBody, null, 2));
|
||||
|
||||
// Create the user in Dolibarr as a thirdparty/customer
|
||||
const response = await fetch(`${apiUrl}thirdparties`, {
|
||||
@ -39,27 +54,24 @@ export async function createDolibarrUser(userData: {
|
||||
'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
|
||||
}),
|
||||
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:', errorData);
|
||||
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 {
|
||||
@ -71,10 +83,19 @@ export async function createDolibarrUser(userData: {
|
||||
// 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'
|
||||
@ -88,6 +109,7 @@ export async function createDolibarrUser(userData: {
|
||||
* @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');
|
||||
@ -99,29 +121,53 @@ export async function checkDolibarrUserExists(email: string): Promise<{ exists:
|
||||
? process.env.DOLIBARR_API_URL
|
||||
: `${process.env.DOLIBARR_API_URL}/`;
|
||||
|
||||
const queryUrl = `${apiUrl}thirdparties?sortfield=t.rowid&sortorder=ASC&limit=1&sqlfilters=(t.email:=:'${encodeURIComponent(email)}')`;
|
||||
console.log('Full search URL:', queryUrl);
|
||||
|
||||
// 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)}')`, {
|
||||
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 DolibarrThirdParty[];
|
||||
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 };
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user