import { Injectable } from '@nestjs/common' import { isEmpty, orderBy } from 'lodash' import { PaymentProviders, PlanFeature } from '../models' import { HttpService } from '../services/http' import { CountryCode } from '../utils' import { BaseRepository } from './base.repository' const FIND_DISTINCT_BY_COUNTRY_CODE = (countryCode: CountryCode) => ` query featuresByCountry($country_code: String!) { plan_feature(where: {country_code: {_eq: $country_code}}, distinct_on: feature) { feature country_code order plan_feature { description_${countryCode.toLowerCase()} } } } ` const FIND_BY_PLAN_ID = (countryCode: CountryCode) => ` query featuresByPlan($plan_id: uuid!, $country_code: String!, $payment_provider: payment_provider_enum!) { plan_feature(where: {plan_id: {_eq: $plan_id}, country_code: {_eq: $country_code}, provider: {_eq: $payment_provider}}, order_by: {order: asc}) { plan_feature { value description_${countryCode.toLowerCase()} } country_code quantity feature } } ` @Injectable() export class PlanFeatureRepository extends BaseRepository { constructor(protected readonly httpService: HttpService) { super(httpService, 'plan_feature') } async findByCountryCode(countryCode: CountryCode): Promise> { const { data } = await this.fetchGraphQL({ body: { query: FIND_DISTINCT_BY_COUNTRY_CODE(countryCode), variables: { country_code: countryCode }, }, }) return isEmpty(data?.plan_feature) ? [] : orderBy( data.plan_feature.map((planFeature: Partial) => PlanFeature.toInstance(planFeature)), 'order', ) } async findByPlanId( planId: string, provider: PaymentProviders, countryCode: CountryCode, ): Promise> { const { data } = await this.fetchGraphQL({ body: { query: FIND_BY_PLAN_ID(countryCode), variables: { country_code: countryCode, payment_provider: provider, plan_id: planId }, }, }) return isEmpty(data?.plan_feature) ? [] : data.plan_feature.map((planFeature: Partial) => PlanFeature.toInstance(planFeature)) } }