Skip to content
Snippets Groups Projects
onDeleteAccount.js 2.11 KiB
Newer Older
  • Learn to ignore specific revisions
  • // @ts-check
    const { log, errors } = require('cozy-konnector-libs')
    const { getAccountRev, getAccountSecret } = require('./helpers/account')
    const { getBoConsent, deleteBoConsent } = require('./requests/bo')
    const { terminateContract } = require('./core/contractTermination')
    const { getAccount } = require('./requests/cozy')
    const moment = require('moment')
    require('moment-timezone')
    moment.locale('fr') // set the language
    moment.tz.setDefault('Europe/Paris') // set the timezone
    const { isLocal } = require('./helpers/env')
    const ACCOUNT_ID = isLocal() ? 'default_account_id' : 'enedis-sge-grandlyon'
    
    async function onDeleteAccount() {
      log('info', 'Deleting account ...')
      log('info', 'Getting secrets ...')
      const secrets = getAccountSecret()
      const accountRev = getAccountRev()
    
      if (accountRev) {
        log('info', 'Account rev exist')
        const accountData = await getAccount(ACCOUNT_ID)
        const userConsent = await getBoConsent(
          secrets.boBaseUrl,
          secrets.boToken,
          accountData.data.consentId
        )
    
        if (userConsent.ID && userConsent.pointID) {
          log('log', `Consent ${userConsent.ID} found for user`)
          if (userConsent.serviceID) {
            await deleteBoConsent(
              secrets.boBaseUrl,
              secrets.boToken,
              userConsent.ID
            )
            await terminateContract(
              secrets.baseUrl,
              secrets.apiAuthKey,
              secrets.sgeLogin,
              secrets.contractId,
              userConsent.pointID,
              userConsent.serviceID
            )
          } else {
            log('error', `No service id retrieved from BO`)
            throw errors.VENDOR_DOWN
          }
        }
    
        log('info', 'Deleting account succeed')
      } else {
        log(
          'error',
          'No account revision was found, something went wrong during the deletion of said account'
        )
        throw errors.VENDOR_DOWN
      }
    }
    
    onDeleteAccount().then(
      () => {
        log('info', `onDeleteAccount: Successfully delete consent and account.`)
      },
      err => {
        log(
          'error',
          `onDeleteAccount: An error occured during script: ${err.message}`
        )
        throw errors.VENDOR_DOWN
      }
    )
    
    module.exports = { onDeleteAccount }