import { ExecutorKey , IEventWiseKey , Condition , ConditionOperation } from '@client/pdfRenderer/transformer/types' ; import { Event , IFormData , IFormSectionData , IFormFieldValue } from '@opencrvs/client/src/forms' ; import { IApplication } from '@client/applications' ; import { MessageDescriptor } from 'react-intl' ; const eventMessageDescriptor = { [ Event . BIRTH ] : { defaultMessage : 'Birth' , description : 'A label from the birth event' , id : 'constants.birth' } , [ Event . DEATH ] : { defaultMessage : 'Death' , description : 'A label from the death event' , id : 'constants.death' } } ; export function getValueFromApplicationDataByKey ( data , valueKey ) { const keyTree = valueKey . split ( '.' ) ; let valueObject = null ; keyTree . forEach ( ( keyNode ) => { valueObject = valueObject === null ? data [ keyNode ] || null : ( valueObject as IFormSectionData ) [ keyNode ] ; } ) ; if ( valueObject === null ) { console . error ( `Given value key structure is not valid: ${ valueKey }` ) ; } return valueObject ; } export function getEventMessageDescription ( event ) { return eventMessageDescriptor [ event ] ; } export function getExecutorKeyValue ( key ) { if ( key === 'CURRENT_DATE' ) { return Date . now ( ) ; } throw new Error ( 'Invalid executor key found' ) ; } export function getExecutorFieldValue ( key , application ) { let value = null ; if ( typeof key === 'string' ) { value = getExecutorKeyValue ( key as ExecutorKey ) ; } else { value = getValueFromApplicationDataByKey ( application . data , ( key as IEventWiseKey ) [ application . event ] ) ; } return value ; } function executeConditionalOperation ( operation , conditionInputs , value ) { switch ( operation ) { case ConditionOperation . VALUE_EXISTS : return value !== '' ; case ConditionOperation . VALUE_DOES_NOT_EXISTS : return value === '' ; case ConditionOperation . DOES_NOT_MATCH : return ! conditionInputs . includes ( value ) ; default : return conditionInputs . includes ( value ) ; } } function getConditionalOperationEnumByValue ( value ) { if ( ! value ) { return ConditionOperation . MATCH ; } return ConditionOperation [ value as keyof typeof ConditionOperation ] ; } export function getMatchedCondition ( conditions , applicationData ) { return conditions . find ( ( conditionObj ) => { try { if ( ! conditionObj . condition ) { return true ; } return executeConditionalOperation ( getConditionalOperationEnumByValue ( conditionObj . condition . operation ) , conditionObj . condition . values , getValueFromApplicationDataByKey ( applicationData , conditionObj . condition . key || '' ) || '' ) ; } catch ( error ) { console . info ( `PDF UTILS ERROR: ${ error }` ) ; return false ; } } ) ; }