import { Transform } from 'class-transformer' import { isNil } from 'lodash' import { parseISO } from '../../utils/date' import { BaseModel } from '../base.model' import { Patient } from '../patient.model' import { User } from '../user.model' export type CreditAuthorType = 'user' | 'patient' | 'system' | 'crava' export type GenericAuthor = { id?: string; type?: CreditAuthorType } export type CreditAuthor = User | Patient | GenericAuthor export const isGenericAuthor = (author: CreditAuthor): author is GenericAuthor => !isNil(author['type']) export const getCreditAuthorType = (creditAuthor: CreditAuthor): CreditAuthorType => { if (isGenericAuthor(creditAuthor)) return creditAuthor.type if (creditAuthor instanceof Object) return creditAuthor.constructor.name.toLocaleLowerCase() as CreditAuthorType return null } export class Credit extends BaseModel> { id: string reason: ModelCreditReason @Transform(value => parseISO(value), { toClassOnly: true }) created_at: Date created_by_id: string created_by_type: CreditAuthorType patient_id?: string subscription_id?: string value: number campaign_value: string credit_id: string setAuthor(author: CreditAuthor): void { if (author instanceof User) this.created_by_type = 'user' if (author instanceof Patient) this.created_by_type = 'patient' if (isGenericAuthor(author)) this.created_by_type = author.type this.created_by_id = author.id } static createBy( this: { new (args?: any): T }, params: Partial & { author?: CreditAuthor }, ): T { return this['createCreditBy'](params) } protected static createCreditBy( this: { new (args?: any): T }, { patient_id, reason, value, author, subscription_id, campaign_value, credit_id, }: Partial & { author?: CreditAuthor }, ): T { const partial: T = new this({ patient_id, reason, value, subscription_id, campaign_value, credit_id }) if (isNil(author)) return partial partial.setAuthor(author) return partial } }