import { Injectable } from '@nestjs/common' import { plainToClass } from 'class-transformer' import { PatientRepository, PlanRepository } from '../../../repositories' import { SubscriptionService, SmartfitApi, AccountService } from '../../../services' import { BusinessExceptionError, NotFoundError } from '../../../errors' import { PaymentProviders, Patient } from '../../../models' @Injectable() export class ConverterPage { constructor( private readonly patientRepository: PatientRepository, private readonly subscriptionService: SubscriptionService, private readonly smartfitApi: SmartfitApi, private readonly planRepository: PlanRepository, private readonly accountService: AccountService, ) {} async isStudent(login: string): Promise { const [person, patient] = await Promise.all([ this.smartfitApi.getPersonByLogin(login), this.patientRepository.findByLogin(login), ]) if (patient?.subscriber) throw new BusinessExceptionError('Already subscribed') if (person && !person.allowPurchaseAddons) return false return !!person } async addSubscriptionToStudent(login: string): Promise { const patient = await this.getOrCreateStudentPatient(login) if (patient.subscriber) throw new BusinessExceptionError('Already subscribed') const plan = await this.planRepository.findByAddonCode( globalThis.secret.converter_page.addon_code, PaymentProviders.SMARTFIT, ) const subscription = await this.subscriptionService.subscribe({ patient, plan, paymentProvider: { provider: PaymentProviders.SMARTFIT }, data: { sales_channel: 'converter_page', origin: 'smartfit' }, }) return !!subscription } async addExternalSubscriptionToPatient(data: Patient, token: string): Promise { const patient = await this.getOrCreateNonStudentPatient(data) if (patient.subscriber) throw new BusinessExceptionError('Already subscribed') const plan = await this.planRepository.get(globalThis.secret.converter_page.plan_id) const subscription = await this.subscriptionService.subscribe({ patient, plan, paymentProvider: { provider: PaymentProviders.WIX }, data: { sales_channel: 'converter_page', origin: 'wix' as any }, options: { token, }, }) return !!subscription } private async getOrCreateNonStudentPatient(data: Partial): Promise { let patient = await this.patientRepository.findByLogin(data.login) if (!patient) { patient = await this.accountService.createPatientAndAuth( plainToClass(Patient, { ...data, }), ) } return patient } private async getOrCreateStudentPatient(login: string): Promise { const patient = await this.accountService.createOrUpdatePatient(login) if (!patient) throw new NotFoundError('Patient not found') return patient } }