import path from 'node:path'; import chalk from 'chalk'; import fs from 'node:fs'; import { ProductModulePayloadType } from '../domain/invoke-payloads'; import { PolicyholderIDType, PolicyholderIdentification } from '../domain/policyholder'; import { readPayloadFile } from './read-file'; /** * @param rootConfig Root product module configuration * @returns ID type as per the configuration */ const getIDTypeFromRootConfig = (rootConfig: Record): PolicyholderIDType | null => { const { policyholder } = rootConfig.settings; if (!policyholder.individualsAllowed) { console.log(chalk.red('Individuals are not allowed')); return null; } if (policyholder.individualsCellphoneAllowed) { return PolicyholderIDType.Cellphone; } if (policyholder.individualsIdAllowed) { return PolicyholderIDType.ID; } if (policyholder.individualsPassportAllowed) { return PolicyholderIDType.Passport; } if (policyholder.individualsCustomIdAllowed) { return PolicyholderIDType.Custom; } if (policyholder.individualsEmailAllowed) { return PolicyholderIDType.Email; } return PolicyholderIDType.Cellphone; }; /** * Generate the policyholder request body based on which ID is chosen in the root-config * @returns policyholder request body */ const generatePolicyholderPayload = (rootConfig: Record) => { const mapping: Record = { id: '9604185800083', passport: 'GB123 FS', cellphone: '+447812720304', custom: '123ABC', email: 'back@future.com', }; const idType = getIDTypeFromRootConfig(rootConfig); let id: PolicyholderIdentification = { country: 'GB', }; if (idType) { id = { ...id, type: idType, number: mapping[idType], }; } return { first_name: 'Marty', last_name: 'McFly', email: 'back@future.com', cellphone: { number: '+27829542232', country: 'ZA', }, id, date_of_birth: '19960418', }; }; /** * Generate policyholder payload or load it from payload file * @param rootConfig Root config to determine ID type of policyholder * @returns payload request body */ export const generatePolicyholderPayloadOrReadFromFile = (rootConfig: Record) => { if (fs.existsSync(path.join(path.join('.', 'payloads', 'policyholder.json')))) { return readPayloadFile({ payloadsDirectory: path.join('.', 'payloads'), fileName: 'policyholder.json' }); } return generatePolicyholderPayload(rootConfig); }; /** * Read the payload of a given type from a file * @returns will return an error message if a file/folder does not exists or is empty */ export const readRequestPayloadFromFile = (params: { type: ProductModulePayloadType }) => { const { type } = params; const payloadsDirectory = path.join('.', 'payloads'); if (!fs.existsSync(payloadsDirectory)) { fs.mkdirSync(payloadsDirectory); console.log('Created payloads folder.'); } return readPayloadFile({ payloadsDirectory, fileName: `${type}.json` }); };