diff --git a/src/common/repositories/UsersRepository.ts b/src/common/repositories/UsersRepository.ts index 4dc65708..a6e8871c 100644 --- a/src/common/repositories/UsersRepository.ts +++ b/src/common/repositories/UsersRepository.ts @@ -100,9 +100,9 @@ export default class UsersRepository extends BaseRepository { update: { first_name: user.contact?.first_name, last_name: user.contact?.last_name, - email: user.contact?.email, - phone_number: user.contact?.phone_number, - cell_phone_number: user.contact?.cell_phone_number, + email: user.contact?.email === null ? undefined : user.contact?.email, + phone_number: user.contact?.phone_number === null ? undefined : user.contact?.phone_number, + cell_phone_number: user.contact?.cell_phone_number === null ? undefined : user.contact?.cell_phone_number, civility: ECivility[user.contact?.civility as keyof typeof ECivility], }, }, diff --git a/src/services/common/IdNotService/IdNotService.ts b/src/services/common/IdNotService/IdNotService.ts index deeb732f..903791fb 100644 --- a/src/services/common/IdNotService/IdNotService.ts +++ b/src/services/common/IdNotService/IdNotService.ts @@ -11,6 +11,7 @@ import { EOfficeStatus } from "@prisma/client"; import OfficeRolesService from "@Services/super-admin/OfficeRolesService/OfficeRolesService"; import DeedTypesService from "@Services/super-admin/DeedTypesService/DeedTypesService"; import DocumentTypesService from "@Services/super-admin/DocumentTypesService/DocumentTypesService"; +import OfficeFoldersService from "@Services/super-admin/OfficeFoldersService/OfficeFoldersService"; import * as Sentry from "@sentry/node"; interface IIdNotToken { @@ -50,6 +51,7 @@ interface IRattachementData { numeroTelephone: string; statutDuRattachement: boolean; mailRattachement: string; + deleted: boolean; } interface IOfficeData { @@ -110,6 +112,7 @@ export default class IdNotService extends BaseService { private officeRolesService: OfficeRolesService, private deedTypesService: DeedTypesService, private documentTypesService: DocumentTypesService, + private officeFoldersService: OfficeFoldersService, ) { super(); } @@ -219,51 +222,74 @@ export default class IdNotService extends BaseService { } public async updateUser(userId: string) { - const userInfos = await this.userService.getByUid(userId, { contact: true, role: true, office_membership: true }); + const userInfos = await this.userService.getByUid(userId, { + contact: true, + role: true, + office_membership: true, + office_folders: true + }); const user = User.hydrate(userInfos!); const searchParams = new URLSearchParams({ key: this.variables.IDNOT_API_KEY, }); - let userData: IRattachementData; + let userRawData: Response; try { - userData = (await ( - await fetch( + userRawData = await fetch( `${this.variables.IDNOT_API_BASE_URL}/api/pp/v2/rattachements/${user.idNot}_${user.office_membership!.idNot}?` + searchParams, { method: "GET", }, ) - ).json()) as IRattachementData; } catch (error) { - console.error("Error fetching user data", error); + console.error(`Error fetching user data for ${user.uid}: ${error}`); + return; + } + + if (userRawData.status === 404) { + console.error(`User ${user.uid} not found in idnot`); + return; + } else if (userRawData.status !== 200) { + console.error(`Error fetching user data for ${user.uid}: ${userRawData.status} - ${userRawData.statusText}`); return; } - if (!userData.statutDuRattachement) { + let userData = (await userRawData.json()) as IRattachementData; + + if (userData.deleted) { let rattachements: any; try { - rattachements = (await ( - await fetch(`${this.variables.IDNOT_API_BASE_URL}/api/pp/v2/personnes/${user.idNot}/rattachements?` + searchParams, { - method: "GET", - }) - ).json()) as any; + const res = await fetch(`${this.variables.IDNOT_API_BASE_URL}/api/pp/v2/personnes/${user.idNot}/rattachements?` + searchParams, { + method: "GET", + }); + if (res.status === 404) { + console.error(`User ${user.uid} not found in idnot`); + return; + } else if (res.status !== 200) { + console.error(`Error fetching rattachements for ${user.uid}: ${rattachements.status} - ${rattachements.statusText}`); + return; + } + + rattachements = await res.json(); } catch (error) { console.error("Error fetching rattachements", error); return; } - if (rattachements.totalResultCount === 0) { + if (rattachements && rattachements.totalResultCount === 0 && rattachements.result.length === 0) { + console.warn("User has no valid rattachements", user.uid); await this.userService.updateCheckedAt(user.uid!); - //await this.userService.delete(user.uid!); return; + } else { + console.log(`Found ${rattachements.totalResultCount} rattachements for ${user.uid}`); } const rattachementsResults = rattachements.result as IRattachementData[]; if (!rattachementsResults) return; - rattachementsResults.forEach(async (rattachement) => { - if (rattachement.statutDuRattachement) { + + for (const rattachement of rattachementsResults) { + if (rattachement.statutDuRattachement && !rattachement.deleted) { let officeData: IOfficeData; try { @@ -274,20 +300,37 @@ export default class IdNotService extends BaseService { ).json()) as IOfficeData; } catch (error) { console.error("Error fetching office data", error); - return; + continue; } if (officeData.typeEntite.name === "office") { userData = rattachement; + userData.entite = officeData; + break; // Found the first valid office, no need to continue } } - }); + } + + // If user was deleted and no valid office was found, delete the user + if (userData.deleted) { + console.log(`User ${user.uid} is deleted from all offices, deleting user from database`); + try { + await this.userService.delete(user.uid!); + console.log(`Successfully deleted user ${user.uid}`); + return; + } catch (error) { + console.error(`Error deleting user ${user.uid}:`, error); + return; + } + } } - let updates = 0; + let update = false; if (user.office_membership!.idNot !== userData.entite.ou) { - updates++; + update = true; + const oldOfficeId = user.office_membership!.uid; + let officeData = (await this.officeService.get({ where: { idNot: userData.entite.ou } }))[0]; if (!officeData) { let officeLocationData: IOfficeLocation; @@ -321,17 +364,55 @@ export default class IdNotService extends BaseService { officeData = await this.officeService.create(office); } user.office_membership = officeData; + console.log("New office_membership found", JSON.stringify(user.office_membership)); + + // Handle stakeholder relationships when user changes office + try { + // Get folders from the old office where the user is a stakeholder + const oldOfficeFolders = user.office_folders?.filter(folder => (folder as any).office_uid === oldOfficeId) || []; + + // Remove user from all stakeholder relationships in old office folders + for (const folder of oldOfficeFolders) { + // Get the current folder with stakeholders to update it + const folderWithStakeholders = await this.officeFoldersService.getByUid(folder.uid!, { stakeholders: true }); + if (!folderWithStakeholders) continue; + + const updatedStakeholders = (folderWithStakeholders as any).stakeholders.filter((stakeholder: any) => stakeholder.uid !== user.uid); + + // Update the folder with the new stakeholder list (excluding the user) + await this.officeFoldersService.update(folder.uid!, { + ...folderWithStakeholders, + stakeholders: updatedStakeholders + }); + + console.log(`Removed user ${user.uid} from stakeholder list of folder ${folder.uid} (old office ${oldOfficeId})`); + } + + if (oldOfficeFolders.length > 0) { + console.log(`Removed user ${user.uid} from ${oldOfficeFolders.length} folders in old office ${oldOfficeId}`); + } + } catch (error) { + console.error(`Error updating stakeholder relationships for user ${user.uid}:`, error); + // Don't fail the entire update if stakeholder update fails + } } - if (user.contact!.email !== userData.mailRattachement) { - updates++; + if (userData.mailRattachement && (user.contact!.email === null || user.contact!.email === undefined || user.contact!.email !== userData.mailRattachement)) { + update = true; user.contact!.email = userData.mailRattachement; + console.log("New email found", JSON.stringify(user.contact!.email)); } - if (user.contact!.cell_phone_number !== userData.numeroMobile) { - updates++; + if (userData.numeroMobile && (user.contact!.cell_phone_number === null || user.contact!.cell_phone_number === undefined || user.contact!.cell_phone_number !== userData.numeroMobile)) { + update = true; user.contact!.cell_phone_number = userData.numeroMobile; + console.log("New cell phone number found", JSON.stringify(user.contact!.cell_phone_number)); + } + if (update) { + console.log("Found updates for user", user.uid!); + // Filter out null values before updating to prevent Prisma errors + const convertedUser = this.convertNullToUndefined(user); + await this.userService.update(user.uid!, convertedUser); } - if (updates != 0) await this.userService.update(user.uid!, user); await this.userService.updateCheckedAt(user.uid!); } @@ -359,19 +440,20 @@ export default class IdNotService extends BaseService { return; } const officeData = (await officeRawData.json()) as IOfficeData; - console.log("office", office); - - console.log("officeData", officeData); let updates = 0; //093051 = demo if (office.name !== officeData.denominationSociale && office.name !== officeData.codeCrpcen && office.crpcen !== "029178" && office.crpcen !== "035010" && office.crpcen !== "093051") { + console.log(`Updating office name: ${office.uid} - ${office.name} - ${office.crpcen}`); updates++; office.name = officeData.denominationSociale ?? officeData.codeCrpcen; + console.log(`New name: ${office.name}`); } if (office.office_status !== this.getOfficeStatus(officeData.statutEntite.name)) { + console.log(`Updating office status: ${office.uid} - ${office.name} - ${office.crpcen}`); updates++; office.office_status = this.getOfficeStatus(officeData.statutEntite.name); + console.log(`New status: ${office.office_status}`); } if (updates != 0) await this.officeService.update(office.uid!, office); await this.officeService.updateCheckedAt(office.uid!); @@ -541,16 +623,36 @@ export default class IdNotService extends BaseService { public async updateUsers() { const usersReq = await this.userService.getUsersToBeChecked(); const users = User.hydrateArray(usersReq); - users.forEach(async (user) => { + for (const user of users) { await this.updateUser(user.uid!); - }); + } } public async updateOffices() { const officesReq = await this.officeService.getOfficesToBeChecked(); const offices = Office.hydrateArray(officesReq); - offices.forEach(async (office) => { + console.log(`Updating ${offices.length} offices`); + for (const office of offices) { await this.updateOffice(office.uid!); - }); + } } -} + + /** + * Utility function to convert null values to undefined + * This prevents Prisma from throwing errors about null values + */ + private convertNullToUndefined>(obj: T): T { + const converted = { ...obj }; + + for (const [key, value] of Object.entries(converted)) { + if (value === null) { + console.log(`Converting null to undefined for key: ${key}`); + (converted as any)[key] = undefined; + } else if (typeof value === 'object' && !Array.isArray(value)) { + (converted as any)[key] = this.convertNullToUndefined(value); + } + } + + return converted; + } +} \ No newline at end of file