Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
12 kB
10
Indexable
Never
import { useAppDispatch } from '@store/hooks';
import { setLoading } from '@store/slices/config';
import axios, { AxiosInstance } from 'axios';
import moment from 'moment';
import RNFetchBlob from 'rn-fetch-blob';
import { tempUrl } from '../../app.json';
import axiosConfiguration, { activeEnv, appEnv } from './axiosConfiguration';
import { IContactDetailsPayload } from './types/registerationRoute.types';

const versionCustomerManagementCRM = '1.0';
const versionMarketWatch = '1.0';
const versionInvestorManagement = '1.0';
const versionTradingManagement = '1.0';
const versionExternalPartner = '1.0';
const versionNotificationService = '1.0';
const baseAxios: AxiosInstance = axiosConfiguration(
  '',
  appEnv[activeEnv].baseUrl,
  // process.env.REACT_APP_API_ROOT_REST_API || tempUrl,
  'application/json',
);

export const customerManagementCRM: AxiosInstance = axiosConfiguration(
  '',
  `${appEnv[activeEnv].baseUrl}/adx/crm/${versionCustomerManagementCRM}`,
);

export const marketWatch: AxiosInstance = axiosConfiguration(
  '',
  `${appEnv[activeEnv].baseUrl}/adx/marketwatch/${versionMarketWatch}`,
);

export const investorManagement: AxiosInstance = axiosConfiguration(
  '',
  `${appEnv[activeEnv].baseUrl}/adx/investors/${versionInvestorManagement}`,
);

export const tradingManagement: AxiosInstance = axiosConfiguration(
  '',
  `${appEnv[activeEnv].baseUrl}/adx/tradings/${versionTradingManagement}`,
);
export const externalPartner: AxiosInstance = axiosConfiguration(
  '',
  `${appEnv[activeEnv].baseUrl}/adx/external-partners/${versionExternalPartner}`,
);
export const notificationService: AxiosInstance = axiosConfiguration(
  '',
  `${appEnv[activeEnv].baseUrl}/adx/notifications/${versionNotificationService}`,
);

export const adxServiceInstance: AxiosInstance = axiosConfiguration(
  '',
  appEnv[activeEnv].baseUrl,
);

export const powerBiAccessToken: AxiosInstance = axiosConfiguration(
  '',
  `https://adxnextjsdev.azurewebsites.net`,
  'application/json',
);
export const powerBiApi: AxiosInstance = accessToken =>
  axiosConfiguration(
    '',
    'https://api.powerbi.com/v1.0/myorg',
    'application/json',
    accessToken,
  );

export const PowerBiExportTo = async params => {
  const { accessToken, groupsId = '', reportId = '', formData = {} } = params;

  const powerBiInstance = await axiosConfiguration(
    '',
    'https://api.powerbi.com/v1.0/myorg',
    'application/json',
    accessToken,
  );
  return powerBiInstance.post(
    `/groups/${groupsId}/reports/${reportId}/ExportTo`,
    formData,
  );
};

export const PowerBiExportToStatus = async params => {
  const { accessToken, groupsId = '', reportId = '', id = '' } = params;
  const powerBiInstance = await axiosConfiguration(
    '',
    'https://api.powerbi.com/v1.0/myorg',
    'application/json',
    accessToken,
  );
  return powerBiInstance.get(
    `/groups/${groupsId}/reports/${reportId}/exports/${id}`,
  );
};
export const PowerBiExportToFile1 = async params => {
  const { accessToken, groupsId = '', reportId = '', id = '' } = params;
  const powerBiInstance = await axiosConfiguration(
    '',
    'https://api.powerbi.com/v1.0/myorg',
    'application/pdf',
    accessToken,
  );
  return powerBiInstance.get(
    `/groups/${groupsId}/reports/${reportId}/exports/${id}/file`,
  );
};

export const PowerBiExportToFile = async params => {
  return new Promise((resolve, reject) => {
    try {
      const { accessToken, groupsId = '', reportId = '', id = '' } = params;
      const url = `https://api.powerbi.com/v1.0/myorg/groups/${groupsId}/reports/${reportId}/exports/${id}/file`;
      const headers = {
        Authorization: `Bearer ${accessToken}`,
      };

      RNFetchBlob.config({
        fileCache: true,
      })
        .fetch('GET', url, headers)
        .then(res => {
          res.base64().then(res => {
            const fileName = `${moment()
              .utcOffset('+05:30')
              .format('YYYY_MM_DD_hh_mm_ss_')}downloaded_file.pdf`; // Replace with the desired filename
            const filePath = `${RNFetchBlob.fs.dirs.DownloadDir}/${fileName}`;
            RNFetchBlob.fs
              .writeFile(filePath, res, 'base64')
              .then(() => {
                resolve(filePath);
                console.log(
                  'File created successfully',
                  RNFetchBlob.fs.dirs.DownloadDir,
                );
              })
              .catch(error => {
                reject(error);
                console.log('error', error);
              });
          });
        })
        .catch(error => {
          console.log('error', error);
        });
    } catch (error) {
      console.error('Error downloading file:', error);
    }
  });
};
const usingFetch = async (method, param) => {
  console.log('Inside Fetch', param);
  const BASE_URL = `${appEnv[activeEnv].baseUrl}/adx/crm/${versionCustomerManagementCRM}${param}`;
  console.log('Final URL', BASE_URL);
  const response = await fetch(BASE_URL, {
    method: method,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'Channel-ID': appEnv[activeEnv]['Channel-ID'],
      'adx-Gateway-APIKey': appEnv[activeEnv]['adx-Gateway-APIKey'],
    },
    // body: JSON.stringify({
    //   firstParam: 'yourValue',
    //   secondParam: 'yourOtherValue',
    // }),
  })
    .then(response => response.json())
    .then(response => console.log('responseFetch', response))
    .catch(error => {
      console.log('fE0', JSON.parse(JSON.stringify(error)));
      if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        console.log('fE1', error.response.data);
        console.log('fE2', error.response.status);
        console.log('fE3', error.response.headers);
      } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser
        // and an instance of http.ClientRequest in node.js
        console.log('fE4', error.request);
      } else {
        // Something happened in setting up the request that triggered an Error
        console.log('FE5Error', error.message);
      }
    });
  return response;
};

export const ApiRoutes = {
  powerBi: {
    getEmbedToken: () => powerBiAccessToken.get('/api/getEmbedToken'),
    getMsalToken: () => powerBiAccessToken.get('/api/getEmbedToken?type=msal'),
  },
  registration: {
    getContactDetails: (data: IContactDetailsPayload) =>
      baseAxios.get(`/investors/${data?.investorId}/contact-details`),

    getAddressDetails: (data: IContactDetailsPayload) =>
      baseAxios.get(`/investors/${data?.investorId}/address-details`),

    checkDuplicateNin: (data: IContactDetailsPayload) =>
      baseAxios.get(`/investors/checkDuplicateNin/${data?.investorId}`),

    checkDuplicateIBAN: (data: IContactDetailsPayload) =>
      baseAxios.get(`/investors/checkDuplicateIban/${data?.iban}`),

    personalEnquiryICP: (data: IContactDetailsPayload) =>
      externalPartner.get(`/icp/person-enquiry/${data?.investorId}`),

    checkValidBankAccount: (data: IContactDetailsPayload) =>
      baseAxios.get(`/external-partners/central-bank/${data?.iban}`),

    getCountriesList: () => customerManagementCRM.get(`/data/countries`),
    getCitiesList: (countryCode: string) =>
      customerManagementCRM.get(`/data/cities/${countryCode}`),
  },
  userDetail: {
    getUserDetail: (params: object) => {
      const { email } = params;
      console.log('getUserDetail', email);
      if (customerManagementCRM) {
        console.log('Axios Instance found', customerManagementCRM.get);
        customerManagementCRM
          .get(`/profile?emailaddress=${email}&username=a`)
          .then(res => {
            console.log('resObj', res);
            return res;
          })
          .catch(error => {
            if (error.response) {
              // The request was made and the server responded with a status code
              // that falls out of the range of 2xx
              console.log(error.response.data);
              console.log(error.response.status);
              console.log(error.response.headers);
            } else if (error.request) {
              // The request was made but no response was received
              // `error.request` is an instance of XMLHttpRequest in the browser
              // and an instance of http.ClientRequest in node.js
              console.log(error.request);
            } else {
              // Something happened in setting up the request that triggered an Error
              console.log('Error', error.message);
            }
            usingFetch('GET', `/profile?emailaddress=${email}&username=a`);
            return error;
          });
        // return customerManagementCRM.get(
        //   `/profile?emailaddress=${email}&username=a`,
        // );
      } else {
        console.log('No instance of Axis is found');
      }

      // const data = usingFetch(
      //   'GET',
      //   `/profile?emailaddress=${email}&username=a`,
      // )
      //   .then(res => res.json())
      //   .then(res => {
      //     console.log('responseinFetch', res);
      //   });
      // const { email } = params;
      // return customerManagementCRM.get(
      //   `/profile?emailaddress=${email}&username=a`,
      // );
    },
    getUserProfileDetail: (params: object) => {
      const { investorId } = params;
      return investorManagement.get(`/investor/${investorId}`);
    },
    updateUserProfileDetail: (param: object) => {
      const { investorId = '', formData = {}, apiEndPoint = '' } = param;
      const constructApiEndPoint = apiEndPoint.replace(
        '{INVESTOR_NUMBER}',
        investorId,
      );
      return adxServiceInstance.put(constructApiEndPoint, formData);
    },
    getBeneficiaryList: (params: object) => {
      const { investorId } = params;
      return investorManagement.get(`/beneficiary/${investorId}`);
    },
    deleteBeneficiaryList: (param: object) => {
      const { payload } = param;
      return investorManagement.delete('/investors/beneficiary', {
        data: payload,
      });
    },
    addBeneficiaryToList: (param: object) => {
      const { investorId = '', payload = {} } = param;
      return investorManagement.get(`/beneficiary`, {
        data: payload,
      });
    },

    createInvestor: (param: object) => {
      return adxServiceInstance.post(`/investors`, param);
    },
    getAGM: (userNin, fromDate, toDate) => {
      // console.log('userNin, fromDate, toDate', userNin, fromDate, toDate);
      return tradingManagement.get(
        `/agms?fromDate=${fromDate}&nin=UAE151002136303&toDate=${toDate}`,
      );
    },
  },
  notification: {
    sms: (param: object) => {
      const { phoneNo = '', otp = '' } = param;
      const formData = {
        sendSMSrequestDoc: {
          to: `+971${phoneNo}`,
          from: 'ADX_',
          text: `Here is the one time password(OTP) ${otp} to update your profile details`,
        },
      };
      return notificationService.post('/sms', formData);
    },
    email: (param: object) => {
      const { email = '', otp = '' } = param;
      const formData = {
        templateName: 'OTP Template',
        contactEmailAddress: `${email}`,
        parameter: {
          otp: `${otp}`,
          customerName: 'bc',
          serviceType: 'Logo Update',
          otpValidTime: '1',
          city: 'pune',
          state: 'mh',
          zip: '00012',
        },
      };
      return notificationService.post('/email', formData);
    },
  },
  watchList: {
    getScrollingTicker: () => {
      return marketWatch.get(`/scrollingTicker`);
    },
    getSecurityBoard: () => {
      return marketWatch.get(`/securityBoardData`);
    },
    getSecurityBoardById: () => {
      return marketWatch.get('/securityBoardData/AEA002901014');
    },
    getAnnouncement: () => {
      return baseAxios.get('/ADX-ListedCompany/announcements');
    },
  },
};