All files / src/services/idnot index.ts

0% Statements 0/156
0% Branches 0/95
0% Functions 0/20
0% Lines 0/145

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import fetch from 'node-fetch';
import { IdNotUser, ECivility, EOfficeStatus, EIdnotRole } from '../../types';
import { ValidationError, UnauthorizedError, ExternalServiceError } from '../../types/errors';
import { Logger } from '../../utils/logger';
 
export class IdNotService {
  static async exchangeCodeForTokens(code: string) {
    const {
      IDNOT_CLIENT_ID,
      IDNOT_CLIENT_SECRET,
      IDNOT_REDIRECT_URI,
      IDNOT_TOKEN_URL
    } = process.env;
 
    if (!IDNOT_CLIENT_ID || !IDNOT_CLIENT_SECRET || !IDNOT_REDIRECT_URI || !IDNOT_TOKEN_URL) {
      throw new Error('Missing IDnot environment variables');
    }
 
    const params = {
      client_id: IDNOT_CLIENT_ID,
      client_secret: IDNOT_CLIENT_SECRET,
      redirect_uri: IDNOT_REDIRECT_URI,
      grant_type: 'authorization_code',
      code
    };
 
    const response = await fetch(IDNOT_TOKEN_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams(params).toString()
    });
 
    if (!response.ok) {
      const text = await response.text().catch(() => '');
      Logger.error('IdNot token exchange failed', {
        url: IDNOT_TOKEN_URL,
        status: response.status,
        statusText: response.statusText,
        bodySnippet: text?.substring(0, 500)
      });
      if (response.status === 400) {
        throw new ValidationError('Invalid authorization code received from IdNot');
      }
      if (response.status === 401) {
        throw new UnauthorizedError('Invalid IdNot client credentials');
      }
      throw new ExternalServiceError('IdNot', `Token exchange failed: ${response.status} ${response.statusText}`);
    }
 
    return response.json();
  }
 
  static async getUserRattachements(idNot: string) {
    const { IDNOT_API_KEY, IDNOT_ANNUARY_BASE_URL } = process.env;
 
    if (!IDNOT_API_KEY || !IDNOT_ANNUARY_BASE_URL) {
      throw new Error('Missing IDnot API key or annuary base URL');
    }
 
    // Essayer plusieurs variantes d'endpoints et paramètres
    const endpoints = [
      // Format standard avec deleted=false
      `${IDNOT_ANNUARY_BASE_URL}/api/pp/v2/personnes/${idNot}/rattachements`,
      // Sans deleted=false (peut-être que ce paramètre cause l'erreur 500)
      `${IDNOT_ANNUARY_BASE_URL}/api/pp/v2/personnes/${idNot}/rattachements`,
      // Variante sans /annuaire
      `${IDNOT_ANNUARY_BASE_URL.replace('/annuaire', '')}/api/pp/v2/personnes/${idNot}/rattachements`
    ];
 
    const searchParamsVariants = [
      new URLSearchParams({ key: IDNOT_API_KEY, deleted: 'false' }),
      new URLSearchParams({ key: IDNOT_API_KEY }),
      new URLSearchParams({ key: IDNOT_API_KEY, deleted: 'false' })
    ];
 
    for (let i = 0; i < endpoints.length; i++) {
      const baseUrl = endpoints[i];
      const searchParams = searchParamsVariants[i];
      const url = `${baseUrl}?${searchParams}`;
 
      try {
        Logger.info(`IdNot getUserRattachements attempt ${i + 1}`, { url, idNot });
 
        const response = await fetch(url, { method: 'GET' });
 
        if (response.ok) {
          const data = await response.json();
          Logger.info(`IdNot getUserRattachements success`, { url, idNot });
          return data;
        }
 
        // Log détaillé pour les erreurs
        const text = await response.text().catch(() => '');
        Logger.error(`IdNot getUserRattachements attempt ${i + 1} failed`, {
          url,
          idNot,
          status: response.status,
          statusText: response.statusText,
          bodySnippet: text?.substring(0, 500)
        });
 
        // Si c'est une erreur 4xx (sauf 404), ne pas réessayer
        if (response.status >= 400 && response.status < 500 && response.status !== 404) {
          throw new ExternalServiceError('IdNot', `Failed to fetch rattachements: ${response.status} ${response.statusText}`);
        }
 
      } catch (error) {
        Logger.error(`IdNot getUserRattachements attempt ${i + 1} error`, {
          url,
          idNot,
          error: error instanceof Error ? error.message : String(error)
        });
 
        // Si c'est la dernière tentative, relancer l'erreur
        if (i === endpoints.length - 1) {
          throw error;
        }
      }
 
      // Attendre un peu avant la prochaine tentative
      if (i < endpoints.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 300 * (i + 1)));
      }
    }
 
    throw new ExternalServiceError('IdNot', 'Failed to fetch rattachements after all attempts');
  }
 
  static async getOfficeRattachements(idNot: string) {
    const { IDNOT_API_KEY, IDNOT_ANNUARY_BASE_URL } = process.env;
 
    if (!IDNOT_API_KEY || !IDNOT_ANNUARY_BASE_URL) {
      throw new Error('Missing IDnot API key or annuary base URL');
    }
 
    const searchParams = new URLSearchParams({
      key: IDNOT_API_KEY,
      deleted: 'false'
    });
 
    const url = `${IDNOT_ANNUARY_BASE_URL}/api/pp/v2/entites/${idNot}/personnes?` + searchParams;
 
    const response = await fetch(url, { method: 'GET' });
    if (!response.ok) {
      const text = await response.text().catch(() => '');
      Logger.error('IdNot getOfficeRattachements failed', {
        url,
        status: response.status,
        statusText: response.statusText,
        bodySnippet: text?.substring(0, 500)
      });
      throw new Error(`Failed to fetch office rattachements: ${response.status} ${response.statusText}`);
    }
    const json = await response.json();
 
    return json;
  }
 
  static async getUserData(profileIdn: string) {
    const { IDNOT_API_KEY, IDNOT_ANNUARY_BASE_URL } = process.env;
 
    if (!IDNOT_API_KEY || !IDNOT_ANNUARY_BASE_URL) {
      throw new Error('Missing IDnot API key or annuary base URL');
    }
 
    // Essayer plusieurs variantes d'endpoints selon la documentation API Annuaire V2
    const endpoints = [
      // Format correct selon doc: /api/pp/v2/personnes/{id}/rattachements
      `${IDNOT_ANNUARY_BASE_URL}/api/pp/v2/personnes/${profileIdn}/rattachements`,
      // Variante sans /annuaire dans l'URL de base
      `${IDNOT_ANNUARY_BASE_URL.replace('/annuaire', '')}/api/pp/v2/personnes/${profileIdn}/rattachements`,
      // Ancien format (fallback)
      `${IDNOT_ANNUARY_BASE_URL}/api/pp/v2/rattachements/${profileIdn}`
    ];
 
    const searchParams = new URLSearchParams({
      key: IDNOT_API_KEY
    });
 
    for (let i = 0; i < endpoints.length; i++) {
      const baseUrl = endpoints[i];
      const userUrl = `${baseUrl}?${searchParams}`;
 
      try {
        Logger.info(`IdNot getUserData attempt ${i + 1}`, { url: userUrl, profileIdn });
 
        const userResp = await fetch(userUrl, { method: 'GET' });
 
        if (userResp.ok) {
          const userData = await userResp.json();
          Logger.info(`IdNot getUserData success`, { url: userUrl, profileIdn });
          return userData;
        }
 
        // Log détaillé pour les erreurs
        const text = await userResp.text().catch(() => '');
        Logger.error(`IdNot getUserData attempt ${i + 1} failed`, {
          url: userUrl,
          profileIdn,
          status: userResp.status,
          statusText: userResp.statusText,
          bodySnippet: text?.substring(0, 500)
        });
 
        // Si c'est une erreur 4xx (sauf 404), ne pas réessayer
        if (userResp.status >= 400 && userResp.status < 500 && userResp.status !== 404) {
          throw new ExternalServiceError('IdNot', `Failed to fetch user data: ${userResp.status} ${userResp.statusText}`);
        }
 
      } catch (error) {
        Logger.error(`IdNot getUserData attempt ${i + 1} error`, {
          url: userUrl,
          profileIdn,
          error: error instanceof Error ? error.message : String(error)
        });
 
        // Si c'est la dernière tentative, relancer l'erreur
        if (i === endpoints.length - 1) {
          throw error;
        }
      }
 
      // Attendre un peu avant la prochaine tentative
      if (i < endpoints.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 200 * (i + 1)));
      }
    }
 
    throw new ExternalServiceError('IdNot', 'Failed to fetch user data after all attempts');
  }
 
  static async getEntiteData(entiteUrl: string) {
    const { IDNOT_API_KEY, IDNOT_ANNUARY_BASE_URL } = process.env;
 
    if (!IDNOT_API_KEY || !IDNOT_ANNUARY_BASE_URL) {
      throw new Error('Missing IDnot API key or annuary base URL');
    }
 
    const searchParams = new URLSearchParams({
      key: IDNOT_API_KEY
    });
 
    const url = `${IDNOT_ANNUARY_BASE_URL}${entiteUrl}?${searchParams}`;
    const response = await fetch(url, { method: 'GET' });
 
    if (!response.ok) {
      const text = await response.text().catch(() => '');
      Logger.error('IdNot getEntiteData failed', {
        url,
        status: response.status,
        statusText: response.statusText,
        bodySnippet: text?.substring(0, 500)
      });
      throw new Error(`Failed to fetch entite data: ${response.status} ${response.statusText}`);
    }
 
    return response.json();
  }
 
  static async getPersonneData(personneUrl: string) {
    const { IDNOT_API_KEY, IDNOT_ANNUARY_BASE_URL } = process.env;
 
    if (!IDNOT_API_KEY || !IDNOT_ANNUARY_BASE_URL) {
      throw new Error('Missing IDnot API key or annuary base URL');
    }
 
    const searchParams = new URLSearchParams({
      key: IDNOT_API_KEY
    });
 
    const url = `${IDNOT_ANNUARY_BASE_URL}${personneUrl}?${searchParams}`;
    const response = await fetch(url, { method: 'GET' });
 
    if (!response.ok) {
      const text = await response.text().catch(() => '');
      Logger.error('IdNot getPersonneData failed', {
        url,
        status: response.status,
        statusText: response.statusText,
        bodySnippet: text?.substring(0, 500)
      });
      throw new Error(`Failed to fetch personne data: ${response.status} ${response.statusText}`);
    }
 
    return response.json();
  }
 
  static async getOfficeLocationData(locationsUrl: string) {
    const { IDNOT_API_KEY, IDNOT_ANNUARY_BASE_URL } = process.env;
 
    if (!IDNOT_API_KEY || !IDNOT_ANNUARY_BASE_URL) {
      throw new Error('Missing IDnot API key or annuary base URL');
    }
 
    const searchParams = new URLSearchParams({
      key: IDNOT_API_KEY
    });
 
    const locUrl = `${IDNOT_ANNUARY_BASE_URL}${locationsUrl}?${searchParams}`;
    const locResp = await fetch(locUrl, { method: 'GET' });
    if (!locResp.ok) {
      const text = await locResp.text().catch(() => '');
      Logger.error('IdNot getOfficeLocationData failed', {
        url: locUrl,
        status: locResp.status,
        statusText: locResp.statusText,
        bodySnippet: text?.substring(0, 500)
      });
      throw new Error(`Failed to fetch office location data: ${locResp.status} ${locResp.statusText}`);
    }
    const officeLocationData = await locResp.json();
 
    return officeLocationData;
  }
 
  static getOfficeStatus(statusName: string): EOfficeStatus {
    switch (statusName) {
      case "Pourvu":
        return EOfficeStatus.ACTIVATED;
      case "Pourvu mais décédé":
        return EOfficeStatus.ACTIVATED;
      case "Sans titulaire":
        return EOfficeStatus.ACTIVATED;
      case "Vacance":
        return EOfficeStatus.ACTIVATED;
      case "En activité":
        return EOfficeStatus.ACTIVATED;
      default:
        return EOfficeStatus.DESACTIVATED;
    }
  }
 
  static getOfficeRole(roleName: string): { name: string } | null {
    switch (roleName) {
      case EIdnotRole.NOTAIRE_TITULAIRE:
        return { name: 'Notaire' };
      case EIdnotRole.NOTAIRE_ASSOCIE:
        return { name: 'Notaire' };
      case EIdnotRole.NOTAIRE_SALARIE:
        return { name: 'Notaire' };
      case EIdnotRole.COLLABORATEUR:
        return { name: 'Collaborateur' };
      case EIdnotRole.SUPPLEANT:
        return { name: 'Collaborateur' };
      case EIdnotRole.ADMINISTRATEUR:
        return { name: 'Collaborateur' };
      case EIdnotRole.CURATEUR:
        return { name: 'Collaborateur' };
      default:
        return null;
    }
  }
 
  static getRole(roleName: string): { name: string } {
    switch (roleName) {
      case EIdnotRole.NOTAIRE_TITULAIRE:
        return { name: 'admin' };
      case EIdnotRole.NOTAIRE_ASSOCIE:
        return { name: 'admin' };
      case EIdnotRole.NOTAIRE_SALARIE:
        return { name: 'notary' };
      case EIdnotRole.COLLABORATEUR:
        return { name: 'notary' };
      case EIdnotRole.SUPPLEANT:
        return { name: 'notary' };
      case EIdnotRole.ADMINISTRATEUR:
        return { name: 'admin' };
      case EIdnotRole.CURATEUR:
        return { name: 'notary' };
      default:
        return { name: 'default' };
    }
  }
 
  static getCivility(civility: string): ECivility {
    switch (civility) {
      case 'Monsieur':
        return ECivility.MALE;
      case 'Madame':
        return ECivility.FEMALE;
      default:
        return ECivility.OTHERS;
    }
  }
}