import { ConsentPaginationEntity, IConsentPagination, } from './../models/consent.model' import axios, { AxiosRequestConfig } from 'axios' import { ConsentEntity, IConsent } from '../models/consent.model' import { toast } from 'react-toastify' import { DateTime } from 'luxon' export class ConsentService { /** * Search for consents * @param search * @param axiosHeaders */ public searchConsent = async ( search: string, axiosHeaders: AxiosRequestConfig ): Promise<IConsent[] | null> => { try { const { data } = await axios.get( `/api/admin/consent?search=${search}`, axiosHeaders ) const consentEntities = data as ConsentEntity[] return consentEntities.map((entity) => this.parseConsent(entity)) } catch (e: any) { if (e.response.status === 403) { toast.error( "Unauthorized : You don't have the rights to do this operation" ) } else { toast.error('Failed to search consents') } console.error(e) return null } } /** * Gets consents * @param limit * @param page * @param axiosHeaders */ public getConsents = async ( limit: number, page: number, axiosHeaders: AxiosRequestConfig ): Promise<IConsentPagination | null> => { try { const { data } = await axios.get( `/api/admin/consent?limit=${limit}&page=${page}`, axiosHeaders ) const consentPagination = data as ConsentPaginationEntity return this.parseConsentPagination(consentPagination) } catch (e: any) { if (e.response.status === 403) { toast.error( "Unauthorized : You don't have the rights to do this operation" ) } else { toast.error('Failed to get consents') } console.error(e) return null } } /** * Converts consent entity into consent * @param consentEntity */ public parseConsent = (consentEntity: ConsentEntity): IConsent => { const startDate: string = DateTime.fromISO(consentEntity.CreatedAt, { zone: 'utc', }) .setLocale('fr-FR') .toLocaleString() const endDate: string = DateTime.fromISO(consentEntity.endDate, { zone: 'utc', }) .setLocale('fr-FR') .toLocaleString() return { ID: consentEntity.ID, startDate: startDate, endDate: endDate, firstname: consentEntity.firstname, lastname: consentEntity.lastname, pointID: consentEntity.pointID, address: consentEntity.address, postalCode: consentEntity.postalCode, city: consentEntity.city, } } /** * Converts consent pagination entity into consent pagination * @param consentPaginationEntity */ public parseConsentPagination = ( consentPaginationEntity: ConsentPaginationEntity ): IConsentPagination => { const rows = consentPaginationEntity.rows.map((consent) => this.parseConsent(consent) ) const consentPagination: IConsentPagination = { rows: rows, totalRows: consentPaginationEntity.totalRows, totalPages: consentPaginationEntity.totalPages, } return consentPagination } }