import { Injectable } from '@nestjs/common' import { isEmpty } from 'lodash' import { UnprocessableEntityError } from '../../errors' import { TeleconsultationsCredit, Products, Credit, Appointment } from '../../models' import { CreditPendingRepository, SeparateCredits, TeleconsultationsCreditRepository } from '../../repositories/credits' import { CreateTransactionResult, CreditOpArgs, CreditService } from './credit.service' type CreditOpArgsWithOtherReason = CreditOpArgs & { otherReason?: string subscriptionId?: string } @Injectable() export class TeleconsultationsCreditService extends CreditService< TeleconsultationsCredit, TeleconsultationsCreditRepository > { constructor( private readonly teleconsultationsCreditRepository: TeleconsultationsCreditRepository, creditPendingRepository: CreditPendingRepository, ) { super(TeleconsultationsCredit, teleconsultationsCreditRepository, creditPendingRepository) } async getByAppointmentId(id: string): Promise { return this.teleconsultationsCreditRepository.getByAppointmentId(id) } async createTransaction(args: CreditOpArgsWithOtherReason): Promise { if (args.reason === 'other' && isEmpty(args.otherReason)) throw new UnprocessableEntityError('When using reason "other" is required a reason') return super.createTransaction({ ...args, extraArgs: { other_reason: args.otherReason || null, subscription_id: args.subscriptionId || null, }, product: Products.TELECONSULTATIONS, }) } async getSeparateCredits(patientId: string): Promise { return this.creditRepository.getSeparateCredits(patientId) } async undoCredit( refundedCredit: Credit, reasonText: string, appointment?: Appointment, ): Promise { return this.createTransaction({ patientId: refundedCredit.patient_id, reason: 'other', value: refundedCredit.value * -1, author: { type: 'system' }, creditId: refundedCredit.id, otherReason: reasonText, objectModel: appointment || { id: refundedCredit?.['appointment_id'] }, }) } }