import { TextMessageService } from 'comtele-sdk' import { OnModuleInit, Injectable } from '@nestjs/common' import { format } from 'date-fns' import { isBuffer } from 'lodash' import { debug, Debugger } from 'debug' import { CountryCallingCodes, PhoneUtils } from '../../utils' import { SMSArgs } from '../../models/types' import { DetailedReport } from './vo' export const DEFAULT_DATE_TIME_FORMAT = 'yyyy-MM-dd HH:mm' export type DeliveryStatus = 'All' | 'Delivered' | 'Undelivered' export type ReportResult = { Success: boolean; Object: Array; Message: string } @Injectable() export class ComteleService implements OnModuleInit { private debug: Debugger = debug(`http:${this.constructor.name}`) private _textMessageService: TextMessageService get isEnabled(): boolean { return process.env.COMTELE_ENABLED === 'true' } onModuleInit(): void { this._textMessageService = new TextMessageService(process.env.COMTELE_API_KEY) } async getDetailedReport( startDate: Date, endDate: Date, deliveryStatus: DeliveryStatus = 'All', ): Promise> { const formattedStartDate = format(startDate, DEFAULT_DATE_TIME_FORMAT) const formattedEndDate = format(endDate, DEFAULT_DATE_TIME_FORMAT) this.debug('get_detailed_report:request', JSON.stringify({ formattedStartDate, formattedEndDate, deliveryStatus })) return new Promise((resolve, reject) => this._textMessageService.getDetailedReport( formattedStartDate, formattedEndDate, deliveryStatus, this.processResult(resolve, reject), ), ) } async sendSMS(args: SMSArgs): Promise { const phone = PhoneUtils.toE164(args.phoneNumber).replace(`+${CountryCallingCodes.BR}`, '') this.debug('send_sms:request', JSON.stringify({ args, phone })) return new Promise((resolve, reject) => this._textMessageService.send(args.controlId || '', args.message, [phone], result => { !result.Success ? this.debug('send_sms:error', JSON.stringify({ error: result.Message })) : this.debug('send_sms:success', JSON.stringify({ response: result })) return result.Success ? resolve() : reject(new Error(result.Message)) }), ) } private processResult = ( resolve: (value: any[] | PromiseLike) => void, reject: (reason?: any) => void, ): ((result: ReportResult) => void) => (result: ReportResult): void => { if (!result.Success) { const error = result.Message ? result.Message : isBuffer(result) ? result.toString() : `Undefined error on Comtele` return reject(new Error(error)) } this.debug('get_detailed_report:response', JSON.stringify({ response: result })) return resolve((result?.Object || []).map(value => new DetailedReport(value))) } }