import { Engine } from 'json-rules-engine' ; import { requireRegionFile } from 'services/region-loader' ; const rules = requireRegionFile ( 'rules.json' ) ; export const isRule = rule => typeof rule === 'object' && ! ! rule . conditions && ! ! rule . event ; export const isDefined = value => value !== undefined ; export const stepHasValue = step => isDefined ( step . value ) ; export const getRulesFromChatSteps = ( steps = [ ] ) => steps . map ( step => step && step . metadata && step . metadata . rule ) . filter ( isRule ) ; export const getFactsFromChatSteps = ( steps = [ ] ) => steps . filter ( stepHasValue ) . reduce ( ( facts , step ) => ( { ... facts , [ step . id ] : step . value } ) , { } ) ; export const getClassesFromRuleResults = ( { events } ) => events . flatMap ( event => event && event . params && event . params . classes ) . filter ( isDefined ) ; export const getChatClassesFromSteps = steps => { const answeredSteps = Object . values ( steps ) . filter ( ( step ) => step . value !== undefined ) ; let engine = new Engine ( ) ; rules . forEach ( rule => engine . addRule ( rule ) ) ; const stepRules = getRulesFromChatSteps ( answeredSteps ) ; stepRules . forEach ( rule => engine . addRule ( rule ) ) ; const facts = getFactsFromChatSteps ( answeredSteps ) ; const cleanUp = ( ) => { engine = null ; } ; return engine . run ( facts ) . then ( getClassesFromRuleResults ) . finally ( cleanUp ) ; } ;