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
|
// 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
|
// Check if the user has mediation or expression role and create in Dolibarr if needed
|
||||||
const hasMediationRole = validRoles.includes('mediation');
|
const hasMediationRole = validRoles.includes('mediation');
|
||||||
const hasExpressionRole = validRoles.includes('expression');
|
const hasExpressionRole = validRoles.includes('expression');
|
||||||
|
|
||||||
|
console.log('Role check results:', {
|
||||||
|
hasMediationRole,
|
||||||
|
hasExpressionRole,
|
||||||
|
shouldCreateInDolibarr: hasMediationRole || hasExpressionRole
|
||||||
|
});
|
||||||
|
|
||||||
let dolibarrUserId = null;
|
let dolibarrUserId = null;
|
||||||
|
|
||||||
if (hasMediationRole || hasExpressionRole) {
|
if (hasMediationRole || hasExpressionRole) {
|
||||||
console.log(`User has special role (mediation: ${hasMediationRole}, expression: ${hasExpressionRole}), creating in Dolibarr`);
|
console.log(`User has special role (mediation: ${hasMediationRole}, expression: ${hasExpressionRole}), creating in Dolibarr`);
|
||||||
|
|
||||||
// First check if the user already exists in Dolibarr
|
try {
|
||||||
const existingUser = await checkDolibarrUserExists(data.email);
|
// First check if the user already exists in Dolibarr
|
||||||
|
console.log('Checking if user already exists in Dolibarr with email:', data.email);
|
||||||
if (existingUser.exists) {
|
const existingUser = await checkDolibarrUserExists(data.email);
|
||||||
console.log(`User already exists in Dolibarr with ID: ${existingUser.id}`);
|
|
||||||
dolibarrUserId = existingUser.id;
|
if (existingUser.exists) {
|
||||||
} else {
|
console.log(`User already exists in Dolibarr with ID: ${existingUser.id}`);
|
||||||
// Create user in Dolibarr
|
dolibarrUserId = existingUser.id;
|
||||||
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 {
|
} else {
|
||||||
console.error("Dolibarr user creation failed:", dolibarrResult.error);
|
// Create user in Dolibarr
|
||||||
// We don't return an error here since Keycloak user was created successfully
|
console.log('Creating new user in Dolibarr with data:', {
|
||||||
// We just log the error and continue
|
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({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
|
|||||||
@ -13,6 +13,7 @@ export async function createDolibarrUser(userData: {
|
|||||||
email: string;
|
email: string;
|
||||||
password: string;
|
password: string;
|
||||||
}): Promise<{ success: boolean; id?: number; error?: string }> {
|
}): Promise<{ success: boolean; id?: number; error?: string }> {
|
||||||
|
console.log('=== DOLIBARR CREATE USER FUNCTION CALLED ===');
|
||||||
try {
|
try {
|
||||||
// Validate environment variables
|
// Validate environment variables
|
||||||
if (!process.env.DOLIBARR_API_URL) {
|
if (!process.env.DOLIBARR_API_URL) {
|
||||||
@ -31,6 +32,20 @@ export async function createDolibarrUser(userData: {
|
|||||||
: `${process.env.DOLIBARR_API_URL}/`;
|
: `${process.env.DOLIBARR_API_URL}/`;
|
||||||
|
|
||||||
console.log(`Creating Dolibarr user for ${userData.email}`);
|
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
|
// Create the user in Dolibarr as a thirdparty/customer
|
||||||
const response = await fetch(`${apiUrl}thirdparties`, {
|
const response = await fetch(`${apiUrl}thirdparties`, {
|
||||||
@ -39,27 +54,24 @@ export async function createDolibarrUser(userData: {
|
|||||||
'DOLAPIKEY': process.env.DOLIBARR_API_KEY,
|
'DOLAPIKEY': process.env.DOLIBARR_API_KEY,
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify(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('Dolibarr API response status:', response.status);
|
||||||
|
|
||||||
// Handle non-OK responses
|
// Handle non-OK responses
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
let errorMessage = `HTTP error ${response.status}`;
|
let errorMessage = `HTTP error ${response.status}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const errorData = await response.json() as DolibarrErrorResponse;
|
const errorData = await response.json() as DolibarrErrorResponse;
|
||||||
|
console.error('Dolibarr API error response full data:', errorData);
|
||||||
errorMessage = errorData.error?.message || errorMessage;
|
errorMessage = errorData.error?.message || errorMessage;
|
||||||
console.error('Dolibarr API error response:', errorData);
|
console.error('Dolibarr API error response:', errorMessage);
|
||||||
} catch (jsonError) {
|
} catch (jsonError) {
|
||||||
console.error('Failed to parse Dolibarr error response');
|
console.error('Failed to parse Dolibarr error response');
|
||||||
|
const textResponse = await response.text();
|
||||||
|
console.error('Raw error response:', textResponse);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -71,10 +83,19 @@ export async function createDolibarrUser(userData: {
|
|||||||
// Parse the successful response
|
// Parse the successful response
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
console.log('Dolibarr user created successfully with ID:', data);
|
console.log('Dolibarr user created successfully with ID:', data);
|
||||||
|
console.log('=== END DOLIBARR CREATE USER FUNCTION ===');
|
||||||
|
|
||||||
return { success: true, id: data };
|
return { success: true, id: data };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error creating Dolibarr user:', 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 {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: error instanceof Error ? error.message : 'Unknown error'
|
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
|
* @returns Boolean indicating if user exists and user ID if found
|
||||||
*/
|
*/
|
||||||
export async function checkDolibarrUserExists(email: string): Promise<{ exists: boolean; id?: number }> {
|
export async function checkDolibarrUserExists(email: string): Promise<{ exists: boolean; id?: number }> {
|
||||||
|
console.log('=== DOLIBARR CHECK USER FUNCTION CALLED ===');
|
||||||
try {
|
try {
|
||||||
if (!process.env.DOLIBARR_API_URL || !process.env.DOLIBARR_API_KEY) {
|
if (!process.env.DOLIBARR_API_URL || !process.env.DOLIBARR_API_KEY) {
|
||||||
console.error('Missing Dolibarr API configuration');
|
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
|
||||||
: `${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
|
// 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',
|
method: 'GET',
|
||||||
headers: {
|
headers: {
|
||||||
'DOLAPIKEY': process.env.DOLIBARR_API_KEY,
|
'DOLAPIKEY': process.env.DOLIBARR_API_KEY,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log('Dolibarr check user API response status:', response.status);
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
console.error(`Error checking if Dolibarr user exists: HTTP ${response.status}`);
|
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 };
|
return { exists: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json() as DolibarrThirdParty[];
|
const data = await response.json() as DolibarrThirdParty[];
|
||||||
|
console.log('Dolibarr user search response:', data);
|
||||||
|
|
||||||
// If we got results, user exists
|
// If we got results, user exists
|
||||||
if (Array.isArray(data) && data.length > 0) {
|
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 };
|
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 };
|
return { exists: false };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error checking if Dolibarr user exists:', 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 };
|
return { exists: false };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Loading…
Reference in New Issue
Block a user