npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@bamburobo/bambu-sync-sdk

v1.0.167

Published

An API set to communicate with Bambu services that abstracts away the implementation of local storage for offline use.

Downloads

29

Readme

Bambu Sync SDK

An API set to communicate with Bambu services that abstracts away the implementation of local storage for offline use.

Overview

This SDK is a JS library for an RN app. Below is the big picture of how the SDK works:

overview

The SDK exposes Bambu endpoints as functions that upon called will check the device connectivity. If the device is connected to the internet the SDK will use server data, otherwise it will use data in Realm.

Installation

Let's assume we are starting an RN project:

react-native init <project-name> 

To install the SDK, run this npm command:

npm install --save @bamburobo/bambu-sync-sdk

To integrate this SDK with your RN project, you need to install Realm JS version 2.29.1:

npm install --save [email protected]
react-native link realm

This SDK also requires PCCW's Quotation Service Library as a dependency. To install it, run this command:

npm install --save @bamburobo/quotation-service-wrapper

This SDK accepts environment variable to set the endpoints, so if you want to set the endpoints at runtime we need to enable environment variable in the RN project. We can do it using this babel plugin:

npm install babel-plugin-transform-inline-environment-variables

After the plugin is installed, modify the projects' .babelrc to use the plugin:

{
  "presets": ["react-native"],
  "plugins": ["transform-inline-environment-variables"]
}

We can then set the API endpoints the SDK will use by setting environment variable on the start script like this:

"start": "BAMBU_BASE_URL=[YOUR_DESIRED_URL] node node_modules/react-native/local-cli/cli.js start",

This is the list of endpoints that can be set at compile time:

  1. [TO BE DECIDED],
  2. ...

Features

This SDK contains modules below:

  1. Agent, containers methods for manipulating Agent data
  2. Customer, contains methods for manipulating Customer data
  3. Lead, contains methods for manipulating Lead that are children to Customer. Lead is a data model that represents a customer's session. It's a group of goals
  4. Goal, contains methods for manipulating Goal that are children to Lead
  5. Retirement, contains methods for manipulating Retirement goal that are children to Goal
  6. Education, contains methods for manipulating Education goal that are children to Goal
  7. Hajj, contains methods for manipulating Hajj goal that are children to Goal
  8. Protection, contains methods for protection products related calculation
  9. Budget, contains budget related functions
  10. Risk, contains methods for determining consumer's risk profile
  11. GoalOptimization, contains goal optimization related functions
  12. Sync, a module for sync-ing offline data with the server
  13. Utilities, a module with various helper functions
  14. Flush, a module for clearing offline data

Models Relationship

  1. Customer has many Lead
  2. Lead has many Goal
  3. Goal has many Education, Retirement and Hajj

Usage

Let's take a look at how to use one of the module. We'll use Customer in this example.

This is one way to use the SDK in the RN code base:

import BambuSdk from '@bamburobo/bambu-sync-sdk';
const sdk = new BambuSdk({
  agentToken: 'agent-token',  // agent token, used to filter customer by agent represented by the token
  gatewayToken: 'gateway-token', // api gateway token should needed,
  baseUrl: 'base-url', // base url of the Bambu services
})

async getCustomers() {
  const { customer } = sdk;
  const { getCustomers } = customer;
  const { status, message, data, error } = await getCustomers();
  console.log(
    status, // 'OK'
    message, // 'Fresh server data is used. Stale local data is refreshed'
    data, // '[{ ...customerAttributes }]'
    error // null
  )
}

Module functions (except for Sync) like Customer.getCustomers return a promise which will always resolve into an object with attributes below:

  1. status
  2. message
  3. data
  4. error

Important

Each element in the data (e.g customer data) will have either or both id and localId attributes. id attribute is given from the server, whereas localId is given by the SDK to enable the app developer to manipulate local data.

The functions exposed in the SDK will decide what to do based on which kind of id is given. For example if you call deleteById({ localId }) with local id as the parameter, the function will assume we're just deleting the local data without attempting to request delete to the server. This is useful to make a connection free transaction. If we call create without internet connection, the saved data will only have localId and that localId can be used to display, update, or delete the data without internet connection.

Available API

Agent

findAll()

Get current agent info

const { agent } = sdk;
const { findAll } = agent;
const { data, error } = await findAll();

console.log(data);
[  
  {  
    "agentId":123456,
    "agentName":"string2",
    "password":"string",
    "agentSettings":"string",
    "countryCode":"string",
    "languageCode":"string",
    "loginTime":"string",
    "expiry":"string",
    "id":8
  }
]
create(data)

Create new agent data

const { agent } = sdk;
const { create } = agent;
const { data, error } = await create({
  agentName: "string",
  password: "string",
  agentSettings: "string",
  countryCode: "string",
  languageCode: "string",
  loginTime: "string",
  expiry: "string"
});
update(data)

Update agent data

const { agent } = sdk;
const { update } = agent;
const { data, error } = await update({
  id: 8,
  agentName: "string2",
  password: "string2",
  agentSettings: "string2",
  countryCode: "string2",
  languageCode: "string2",
  loginTime: "string2",
  expiry: "string2"
});

Customer

create(data)
const { customer } = sdk;
const { create } = customer;
const { status, message, data, error } = await create({
  firstName: 'Jane',
  lastName: 'Doe',
});

If the request is successful the data will be saved both locally and in the server, so the new customer data will have an id assigned from the server. But if the request failed the data will only be saved locally and the SDK will assign a localId to it.

The data param is an object containing below customer data. Note that every attribute listed is optional.

  1. firstName, accepts a String
  2. lastName, accepts a String
  3. fullName, accepts a String
  4. nationality, accepts a String
  5. gender, accepts "male" and "female"
  6. maritalStatus, accepts "single" and "married"
  7. numberOfChildren, accepts a Number
  8. birthDate, accepts a date ISO string e.g 2018-07-02T05:33:41.948Z
  9. age, accepts a Number
  10. countryOfBirth, accepts a String
  11. race, accepts a String
  12. religion, accepts a String
  13. ethnicOrigin, accepts a String
  14. taxResidency, accepts a String
  15. yearsOfResidency, accepts a String
  16. height, accepts a Number
  17. width, accepts a Number
  18. interests, accepts a String
  19. sourceoFFunds, accepts a String
  20. purposeOfInvestment, accepts a String
  21. householdIncome, accepts a Number
  22. personalIncome, accepts a Number
  23. additionalIncome, accepts a Number
  24. riskAppetite, accepts a String
  25. status, accepts a String
  26. agentId, accepts a Number
  27. clientName (optional), accepts a String
  28. policiesOwned (optional), accepts a Number
  29. fnaStatus (optional), accepts a String
  30. goalScore (optional), accepts a Number
  31. protectionScore (optional), accepts a Number
  32. riskAppetite (optional), accepts a String
  33. lastUpdated (optional), accepts a String
  34. profpicString (optional), accepts a String
  35. phone (optional), accepts a String
  36. email (optional), accepts a String
  37. notes (optional), accepts a String
  38. favorited (optional), accepts a Boolean
  39. displayGoalMonthly (optional), accepts a Boolean
  40. goalProgress (optional), accepts a Number
  41. middleName, accepts a String
  42. suffix, accepts a String
  43. signature, accepts a String
  44. disclaimerChecked, accepts a Boolean
  45. disclaimerSubmitted, accepts a Boolean
  46. budgetBreakdown, accepts a Boolean
findAll()
const { customer } = sdk;
const { findAll } = customer;
const { status, message, data, error } = await findAll({
  pagination: {
    limit: 0,
    skip: 5,
  }
});

This will return a list of customer sorted from most updated with pagination settings specified in pagination object. The pagination object accepts limit and skip as it's attributes.

findById({ id, localId })
const { customer } = sdk;
const { findById } = customer;
const { status, message, data, error } = await findById({
  id: 1, // accepts either id or localId, can't accept both
});
update(data)
const { customer } = sdk;
const { update } = customer;
const { status, message, data, error } = await update({
  id: 2, // accepts either id or localId, can't accept both
  firstName: 'Another Jane',
});
deleteById({ id, localId })
const { customer } = sdk;
const { deleteById } = customer;
const { status, message, data, error } = await deleteById({
  id: 2, // accepts either id or localId, can't accept both
});
findAllLocal(filter)

Get locally saved customer given a filter.

const { customer } = sdk;
const { findAllLocal } = customer;
const { data, error } = await findAllLocal({
  lastUpdatedStartDate: '2018-09-04T03:32:52.411Z',
  lastUpdatedEndDate: '2018-09-01T03:32:52.411Z',
  fnaStatus: ['completed', 'not-completed'],
  riskAppetite: ['high', 'low'],
  policiesOwned: [true, false],
  favorited: true,
});
console.log(data); // returns an array similar with getCustomers()

The filter object contains below attributes:

  1. lastUpdatedStartDate, the start of last updated date range filter, this value should be earlier than lastUpdatedEndDate accepts an ISO Date String
  2. lastUpdatedEndDate, the end of last updated date range filter an ISO Date String
  3. fnaStatus, an array of String containing the possible completion status you want to filter
  4. riskAppetite, an array of String containing the possible risk appetite type status you want to filter
  5. policiesOwned, an array of Boolean, set [true] if you want only true, [false] if you want only false, or [true, false] if you want both
  6. favorited, a Boolean

Lead

createByCustomerId({ customerId, customerLocalId, data })
const { lead } = sdk;
const { createByCustomerId } = lead;
const { status, message, data, error } = await createByCustomerId({
  customerId: 1, // accepts either customerId or customerLocalId, can't accept both
  data: {
    initialInvestment: 50000,
    regularContribution: 2000,
    contributionSchedule: "Monthly",
    expenseBreakdown: JSON.stringify({}),
    protectionBreakdown: JSON.stringify({}),
    riskProfileScores: JSON.stringify({}),
    budgetModuleCompletion: 'completed',
    protectionModuleCompletion: 'completed',
    riskModuleCompletion: 'completed',
    budgetModuleLastVisitedPage: 'budget/1',
    protectionModuleLastVisitedPage: 'protection/1',
    riskModuleLastVisitedPage: 'risk/1',
    goals: JSON.stringify({}),
  }
});
console.log(data);
/*
  {
    "id": 1,
    "localId": null,
    "customerId": 1,
    "customerLocalId": null,
    "initialInvestment": 50000,
    "regularContribution": 2000,
    "contributionSchedule": "Monthly",
    "expenseBreakdown": "{}",
    "protectionBreakdown": "{}",
    "riskProfileScores": "{}",
    "budgetModuleCompletion": 1,
    "protectionModuleCompletion": 1,
    "riskModuleCompletion": 0.5,
    "budgetModuleLastVisitedPage": "budget/1",
    "protectionModuleLastVisitedPage": "protection/1",
    "riskModuleLastVisitedPage": "risk/1",
    "goals": {},
    "createdAt": "2018-07-26T08:00:44.836Z",
    "modifiedAt": "2018-07-26T08:00:44.836Z"
  }
*/

If the request is successful the data will be saved both locally and in the server, so the new lead data will have an id assigned from the server. But if the request failed the data will only be saved locally and the SDK will assign a localId to it.

The data param is an object containing below goal data. Note that the data must have either leadLocalId or leadId but not both.

  1. initialInvestment (optional), accepts a Number
  2. regularContribution (optional), accepts a Number
  3. contributionSchedule (optional), accepts a String
  4. expenseBreakdown (optional), accepts a String
  5. protectionBreakdown (optional), accepts a String
  6. riskProfileScores (optional), accepts a String
  7. budgetModuleCompletion (optional), accepts a String
  8. protectionModuleCompletion (optional), accepts a String
  9. riskModuleCompletion (optional), accepts a String
  10. budgetModuleLastVisitedPage (optional), accepts a String
  11. protectionModuleLastVisitedPage (optional), accepts a String
  12. riskModuleLastVisitedPage (optional), accepts a String
  13. goals (optional), accepts a String
  14. currentInsuranceBreakdown (optional), accepts a String
  15. lifeStyleOptionsEnabled (optional), accepts a Boolean
  16. regularContributionBreakdown (optional), accepts a String
  17. protectionConcerns (optional), accepts a String
  18. goalProtectionBreakdown (optional), accepts a String
findAllByCustomerId({ customerId, customerLocalId })
const { lead } = sdk;
const { findAllByCustomerId } = lead;
const { status, message, data, error } = await findAllByCustomerId({
  customerId: 1, // accepts either customerId or customerLocalId, can't accept both
});
update(data)
const { lead } = sdk;
const { update } = lead;
const { status, message, data, error } = await update({
  id: 1, // accepts either customerId or customerLocalId, can't accept both
  customerId: 2,
});

Note that this function will delete all existing data and replace it with new input data. Always pass in all intended fields to prevent loss of data.

deleteById({ id, localId })
const { lead } = sdk;
const { deleteById } = lead;
const { status, message, data, error } = await deleteById({
  id: 1, // accepts either id or localId, can't accept both
});
composeEAppPayload({ country, leadId, isEducation })

Compose eApp payload given leadId

const { lead } = sdk;
const { composeEAppPayload } = lead;
const { data, error } = await composeEAppPayload({
  country: 'Vietnam',
  leadId: 7044,
  isEducation: false
});

console.log(data);
/*
{  
  "USERNAME":"07080653",
  "PASSWORD":"0079HHSGF7723244BSV283Y87NSBDFF",
  "DATA":{  
    "com.c2lbiz.symbiosys.insurance.businesscommon.dataobjects.quotation.QuotationDO":{  
      "class":"com.c2lbiz.symbiosys.insurance.businesscommon.dataobjects.quotation.QuotationDO",
      "proposerLASame":"COPYFROMINSURED",
      "versionID":"1",
      "listQuotationPartyDOList":[  
        {  
          "partyTypeCd":"INDIVIDUAL",
          "roleCd":"PROPOSER",
          "title":"MR",
          "corporateName":"",
          "lastname":null,
          "corporateName2":"",
          "dob":"1980-01-01T09:07:42.000Z",
          "age":39,
          "genderCd":"MALE",
          "taxId":"",
          "emailAddress":"[email protected]",
          "occupationCd":"1",
          "contactNum":"987654321",
          "officeContactNum":"",
          "relationCd":"SELF",
          "guid":1,
          "class":"com.c2lbiz.symbiosys.insurance.businesscommon.dataobjects.quotation.QuotationPartyDO"
        }
      ],
      "listQuotationProductDOList":[  
        {  
          "class":"com.c2lbiz.symbiosys.insurance.businesscommon.dataobjects.quotation.QuotationProductDO",
          "partyRoleCd":"PRIMARY",
          "productFamilyCd":"ENDOWMENT",
          "productId":"NEP",
          "productPlanOptionCd":"NEP1",
          "productSeq":39,
          "productTypeCd":"PLAN",
          "productVersion":1,
          "baseSumAssured":300000000,
          "productTerm":12,
          "premiumPayingTerm":8,
          "paymentTypeCd":"REGULAR",
          "paymentFrequencyCd":"YEARLY",
          "capturedPremiumAmt":55800000
        },
        {  
          "class":"com.c2lbiz.symbiosys.insurance.businesscommon.dataobjects.quotation.QuotationProductDO",
          "productSeq":68,
          "productId":"MR01",
          "productVersion":1,
          "productTypeCd":"RIDER",
          "productFamilyCd":"AHRIDER",
          "baseSumAssured":100000000,
          "productTerm":12,
          "premiumPayingTerm":12,
          "productPlanOptionCd":"MA",
          "partyRoleCd":"PRIMARY",
          "capturedPremiumAmt":2500000,
          "insuredPartyRefGuid":2
        },
        {  
          "class":"com.c2lbiz.symbiosys.insurance.businesscommon.dataobjects.quotation.QuotationProductDO",
          "productSeq":72,
          "productId":"CI03",
          "productVersion":1,
          "productTypeCd":"RIDER",
          "productFamilyCd":"AHRIDER",
          "baseSumAssured":200000000,
          "productTerm":12,
          "premiumPayingTerm":12,
          "productPlanOptionCd":"",
          "partyRoleCd":"PRIMARY",
          "capturedPremiumAmt":664000,
          "insuredPartyRefGuid":2
        },
        {  
          "class":"com.c2lbiz.symbiosys.insurance.businesscommon.dataobjects.quotation.QuotationProductDO",
          "productSeq":68,
          "productId":"MR01",
          "productVersion":1,
          "productTypeCd":"RIDER",
          "productFamilyCd":"AHRIDER",
          "baseSumAssured":100000000,
          "productTerm":12,
          "premiumPayingTerm":12,
          "productPlanOptionCd":"MA",
          "partyRoleCd":"PROPOSER",
          "capturedPremiumAmt":2700000,
          "insuredPartyRefGuid":1
        }
      ]
    },
    "OTHERDATA":{  
      "address4":"YES",
      "address1":"TEST",
      "address2":"TEST",
      "address3":"TEST",
      "state":"VN008",
      "city":"D0093",
      "addressLine1Lang1":"",
      "addressLine2Lang1":"",
      "addressLine3Lang1":"",
      "stateCd1":"",
      "cityCd1":"",
      "alias":"",
      "idNumber":"",
      "nationality":"VNM",
      "country":"VNM",
      "tenantId":"1234567",
      "tenantName":"AI2"
    }
  }
}
*/

Goal

createByLeadId({ leadId, leadLocalId, data })
const { goal } = sdk;
const { createByLeadId } = goal;
const { status, message, data, error } = await createByLeadId({
  leadId: 2, // accepts either leadId or leadLocalId, can't accept both
  data: {
    goalType: 'Retirement',
    goalName: 'My Retirement Plan',
    goalValue: 1000,
    goalName: 'My retirement',
    goalValue: 5000000,
    goalStartYear: 2018,
    goalEndYear: 2032,
    status: 'Active',
    completion: 0.1,
    lastVisitedPage: 'profile-creation',
    goalSaving: 8000,
    assetAllocation: JSON.stringify({}),
    expenseBreakdown: JSON.stringify({}),
    inflationRate: 0.04,
  },
});

If the request is successful the data will be saved both locally and in the server, so the new goal data will have an id assigned from the server. But if the request failed the data will only be saved locally and the SDK will assign a localId to it.

The data param is an object containing below goal data. Note that the data must have either leadLocalId or leadId but not both.

  1. leadLocalId, accepts a Number
  2. leadId, accepts a Number
  3. goalType, accepts a String, accepts available goal types. Example: "Retirement"
  4. goalName, accepts a String
  5. goalValue, accepts a Number
  6. goalStartYear, accepts a Number
  7. goalEndYear, accepts a Number
  8. goalPriority (optional), accepts a Number
  9. status, accepts a String
  10. completion (optional), accepts a Number
  11. lastVisitedPage (optional), accepts a String
  12. goalSaving (optional), accepts a Number
  13. assetAllocation (optional), accepts a String
  14. expenseBreakdown (optional), accepts a String
  15. inflationRate (optional), accepts a Number
  16. favorited (optional), accepts a Boolean
findAllByLeadId({ leadId, leadLocalId })
const { goal } = sdk;
const { findAllByLeadId } = goal;
const { status, message, data, error } = await findAllByLeadId({
  leadId: 2, // accepts either leadId or leadLocalId, can't accept both
});
findById({ id, localId })
const { goal } = sdk;
const { findById } = goal;
const { status, message, data, error } = await findById({
  id: 2, // accepts either id or localId, can't accept both
});
update(data)
const { goal } = sdk;
const { update } = goal;
const { status, message, data, error } = await update({
  id: 2, // accepts either id or localId, can't accept both
  leadId: 2,
  goalType: 'Retirement',
  goalName: 'Another Retirement Plan',
  goalValue: 1000,
  goalStartYear: 2018,
  goalEndYear: 2050,
  status: 'In Progress',
});
deleteById({ id, localId })
const { goal } = sdk;
const { deleteById } = goal;
const { status, message, data, error } = await deleteById({
  id: 2, // accepts either id or localId, can't accept both
});
calculateGoalScoreSingle({ goalValue, goalYears, initialInvestment, country })

Calculate a score of a single goal.

const { goal } = sdk;
const { calculateGoalScoreSingle } = goal;
const { data, error } = await calculateGoalScoreSingle({
  goalValue: 1100,
  lowScenario: 1200,
  midScenario: 1300,
  highScenario: 1400,
});
console.log(data); // 0.80
calculateGoalScoreMulti(goals)

Calculate aggregated goal score given goals with score and their priorities.

const { goal } = sdk;
const { calculateGoalScoreMulti } = goal;
const { data } = await calculateGoalScoreMulti([
  { score: 0.9, priority: 1 },
  { score: 0.8, priority: 2 },
  { score: 0.7, priority: 3 }
]);
console.log(data); // 0.83

Retirement

createByGoalId({ goalId, goalLocalId, data })
const { retirement } = sdk;
const { createByGoalId } = retirement;
const { status, message, data, error } = await createByGoalId({
  goalId: 2, // accepts either goalId or goalLocalId, can't accept both
  data: {
    retirementAge: 65,
    nameOfPerson: 'Jane',
  },
});

If the request is successful the data will be saved both locally and in the server, so the new goal data will have an id assigned from the server. But if the request failed the data will only be saved locally and the SDK will assign a localId to it.

The data param is an object containing below retirement data. Note that the input can only contain either goalLocalId or goalId but not both.

  1. goalLocalId, accepts a Number
  2. goalId, accepts a Number
  3. retirementAge (optional), accepts a Number
  4. expectedDeathAge (optional), accepts a Number
  5. retirementLifeStyle (optional), accepts a String
  6. retirementIncome (optional), accepts a Number
  7. nameOfPerson, accepts a String
  8. relationship (optional), accepts a String
  9. spouseBirthDate (optional), accepts a date ISO string e.g 2018-07-02T05:33:41.948Z
  10. withSpouse (optional), accepts a Boolean
findAllByGoalId({ goalId, goalLocalId })
const { retirement } = sdk;
const { findAllByGoalId } = retirement;
const { status, message, data, error } = await findAllByGoalId({
  goalId: 2, // accepts either goalId or goalLocalId, can't accept both
});
findById({ goalId, id, localId })
const { retirement } = sdk;
const { findById } = retirement;
const { status, message, data, error } = await findById({
  goalId: 2, 
  id: 2, // accepts either id or localId, can't accept both
});
update(data)
const { retirement } = sdk;
const { update } = retirement;
const { status, message, data, error } = await update({
  id: 2,
  goalId: 2, // accepts either goalId or goalLocalId, can't accept both
  retirementAge: 65,
  nameOfPerson: 'Another Jane',
});
deleteById({ id, localId })
const { retirement } = sdk;
const { deleteById } = retirement;
const { status, message, data, error } = await deleteById({
  id: 2, // accepts either id or localId, can't accept both
});
getRetirementCountries()

Get all available countries for the retirement calculator.

const { retirement } = sdk;
const { getRetirementCountries } = retirement;
const { data } = await getRetirementCountries();
console.log(data); // ['Vietnam', 'Philippines', 'Indonesia', 'Malaysia']
getRetirementExpenses()

Get all available retirement expenses

const { retirement } = sdk;
const { getRetirementExpenses } = retirement;
const { data } = await getRetirementExpenses();
console.log(data); // ['Housing', 'Food', 'Transport', 'Healthcare', 'Travel', 'Recreation/Other']
getRetirementLifestyleTiers({ country, income })

Get retirement lifestyle multiplier data from a country, this multiplier will then be applied to the income parameters in calculateRetirementExpenses({ country, income }) and calculateRetirementExpense({ expense, country, expenseDetailAnswers })

const { retirement } = sdk;
const { getRetirementLifestyleTiers } = retirement;
const { data } = await getRetirementLifestyleTiers('Philippines', 100000);
console.log(data);
/*
[
  { "name": "Basic", usageFromIncome: 0.75 },
  { "name": "Comfortable", usageFromIncome: 1 },
  { "name": "Luxurious", usageFromIncome: 1.25 },
]
*/
calculateRetirementExpenses({ country, income })

Calculate approximation of retirement expenses given country and the customer's income

const { retirement } = sdk;
const { calculateRetirementExpenses } = retirement;
const { data } = await calculateRetirementExpenses({
  country: 'Indonesia',
  income: 7550000,
});
console.log(data);
/*
  {
    "currency": "IDR",
    "data": [
      { "category": "Housing", "monthlyExpense": 722700 },
      { "category": "Food", "monthlyExpense": 1397220 },
      { "category": "Transport", "monthlyExpense": 433620 },
      { "category": "Healthcare", "monthlyExpense": 192720 },
      { "category": "Travel", "monthlyExpense": 385440 },
      { "category": "Recreation/Other", "monthlyExpense": 674520 },
    ]
  }
*/
calculateRetirementExpensesPercentage({ country, income })

Same with calculateRetirementExpenses({ country, income }) but this one returns the percentage of each expense category.

const { retirement } = sdk;
const { calculateRetirementExpensesPercentage } = retirement;
const { data, error } = await calculateRetirementExpensesPercentage({
  income: 10000000,
  country: 'Philippines',
});

console.log(data);
/*
[  
  {  
    "category":"Housing",
    "expensePercentage":0.29551820728291317
  },
  {  
    "category":"Food",
    "expensePercentage":0.4943977591036415
  },
  {  
    "category":"Transport",
    "expensePercentage":0.09663865546218488
  },
  {  
    "category":"Healthcare",
    "expensePercentage":0.06022408963585434
  },
  {  
    "category":"Travel",
    "expensePercentage":0.04061624649859944
  },
  {  
    "category":"Recreation/Other",
    "expensePercentage":0.012605042016806723
  }
]
*/
getExpenseDetailQuestions({ expense, country })

Get individual retirement expense calculation options

const { retirement } = sdk;
const { getExpenseDetailQuestions } = retirement;
const { data } = await getExpenseDetailQuestions({
  expense: 'Housing',
  country: 'Vietnam'
});
console.log(data);
/*
[  
  {  
    "type":"band",
    "question":"What kind of house do you want to live in?",
    "answers":[  
      {  
        "label":"Rent",
        "value":2
      },
      {  
        "label":"Apartment/Condo",
        "value":3
      },
      {  
        "label":"Private apartment",
        "value":4
      },
      {  
        "label":"House",
        "value":5
      }
    ]
  },
  {  
    "type":"multiplier",
    "question":"Which area you want to settle in?",
    "answers":[  
      {  
        "label":"Ho Chi Minh",
        "value":1.2
      },
      {  
        "label":"Hanoi",
        "value":1
      },
      {  
        "label":"Da Nang/Nha Trang",
        "value":0.7
      }
    ]
  }
]
*/
calculateRetirementExpense({ expense, country, expenseDetailAnswers })

Calculate approximation of individual retirement expense given expense category, country, and customer's answer for questions from getExpenseDetailQuestions

const { retirement } = sdk;
const { calculateRetirementExpense } = retirement;
const { data } = await calculateRetirementExpense({
  expense: 'Housing',
  country: 'Vietnam',
  expenseDetailAnswers: [
    { type: 'band', value: 5 },
    { type: 'multiplier', value: 1.2 }
  ]
});
console.log(data);
/*
  {
    "currency": "VND",
    "monthlyExpense": 588000,
  }
*/
calculateRetirementGoal({ annualExpense, retirementAge, lifeExpectancy, inflationRate, yearsToGoal, goalSavings, country })

Calculate the amount needed to retire in some certain years given expenses and other retirement data

const { retirement } = sdk;
const { calculateRetirementGoal } = retirement;
const { data } = await calculateRetirementGoal({
  annualExpense: 24000,
  retirementAge: 65,
  lifeExpectancy: 86,
  inflationRate: 0.04,
  yearsToGoal: 40,
});
console.log(data); // 1799659.73
calculateRetirementGoalWithSpouse(payload)

Same with calculateRetirementGoal but accounting for the user's spouse

const { retirement } = sdk;
const { calculateRetirementGoalWithSpouse } = retirement;
const { data, error } = await calculateRetirementGoalWithSpouse({
  annualExpense: 13746348,
  retirementAge: 65,
  lifeExpectancy: 85,
  yearsToGoal: 27,
  inflationRate: 0.04,
  spouseRetirementAge: 60,
  spouseLifeExpectancy: 80,
  spouseYearsToGoal: 24,
});
console.log(JSON.stringify(data)); // 560598332.72
getTidbit({ topic, params })

Get retirement related tidbit

const { retirement } = sdk;
const { getTidbit } = retirement;
const { data } = await getTidbit({
  topic: 'averageRetirementAge',
  params: {
    country: 'Philippines',
    useLocalLanguage: true,
  }
});
console.log(data);
/*
{
  "copy": "Most people retire 2 years after the government plan, at the average age of ",
  "emphasis": "63.",
}
*/

The topic attribute in the payload accepts averageRetirementAge, incomeReplacementSize, and averageLifeExpectancy.

The required attributes of params attribute depends on the topic selected:

  1. topic averageRetirementAge accepts params with attributes: country (e.g Vietnam) and useLocalLanguage (Boolean).
  2. topic incomeReplacementSize accepts params with attributes: country (e.g Vietnam), lifestyleTier (e.g Basic), income (e.g 100,000), and useLocalLanguage (Boolean).
  3. topic averageLifeExpectancy accepts params with attributes: country (e.g Vietnam), gender (e.g male), and useLocalLanguage (Boolean).

Education

createByGoalId({ goalId, goalLocalId, data })
const { education } = sdk;
const { createByGoalId } = education;
const { status, message, data, error } = await createByGoalId({
  goalId: 2, // accepts either goalId or goalLocalId, can't accept both
  data: {
    typeOfEducation:  'Masters',
    nameOfPerson: 'Jane',
  },
});

If the request is successful the data will be saved both locally and in the server, so the new goal data will have an id assigned from the server. But if the request failed the data will only be saved locally and the SDK will assign a localId to it.

The data param is an object containing below retirement data. Note that the input can only contain either goalLocalId or goalId but not both.

  1. goalLocalId (optional), accepts a Number
  2. goalId (optional), accepts a Number
  3. nameOfPerson , accepts a String
  4. birthDate (optional), accepts a date ISO string e.g 2018-07-02T05:33:41.948Z
  5. typeOfEducation (optional), accepts a String
  6. internationalOrLocal (optional), accepts a String
  7. locationOfStudy (optional), accepts a String
  8. specialization (optional), accepts a String
  9. yearOfStudy (optional), accepts a Number
  10. costOfStudy (optional), accepts a Number
  11. monthlyRent (optional), accepts a Number
  12. monthlyLivingExpense (optional), accepts a Number
  13. goalSaving (optional), accepts a Number
  14. basicOrAdvanced (optional), accepts a String
  15. calculatedCost (optional), accepts a String
  16. startAge (optional), accepts a Number
  17. inflationRate (optional), accepts a Number
  18. goalValue (optional), accepts a Number
findAllByGoalId({ goalId, goalLocalId })
const { education } = sdk;
const { findAllByGoalId } = education;
const { status, message, data, error } = await findAllByGoalId({
  goalId: 2, // accepts either goalId or goalLocalId, can't accept both
});
findById({ goalId, id, localId })
const { education } = sdk;
const { findById } = education;
const { status, message, data, error } = await findById({
  goalId: 2, 
  id: 2, // accepts either id or localId, can't accept both
});
update(data)
const { education } = sdk;
const { update } = education;
const { status, message, data, error } = await update({
  id: 2,
  goalId: 2, // accepts either goalId or goalLocalId, can't accept both
  typeOfEducation:  'Masters',
  nameOfPerson: 'Jane',
});
deleteById({ id, localId })
const { education } = sdk;
const { deleteById } = education;
const { status, message, data, error } = await deleteById({
  id: 2, // accepts either id or localId, can't accept both
});
getAvailableEducationData()

Get list of available education cost data

const { education } = sdk;
const { getAvailableEducationData } = education;
const { data, error } = await getAvailableEducationData();

console.log(data);
/*
[  
  {  
    "country":"Singapore",
    "isMedicine":true,
    "isPublicCollege":true
  },
  {  
    "country":"Singapore",
    "isMedicine":false,
    "isPublicCollege":true
  },
  {  
    "country":"Singapore",
    "isMedicine":false,
    "isPublicCollege":false
  },
  // other data
]
*/
getEducationCost(payload)

Get list of expenses of a child education.

const { education } = sdk;
const { getEducationCost } = education;
const { data, error } = await getEducationCost({
  isPublicCollege: true,
  isMedicine: true,
  country: 'Indonesia', // accepts `"Singapore"`, `"Indonesia"`, `"Vietnam"`, "Philippines", "Malaysia", "Australia", and "USA"
  currency: 'IDR', // accepts `"USD"`, `"SGD"`, `"IDR"`, `"PHP"`, `"VND"`, `"CAD"`, `"GBP"`, `"AUD"`, `"NZD"`, and `"THB"`
});
console.log(data);
/*
{  
  "yearlyTuitionCost":45000000,
  "yearlyAccommodationCost":12000000,
  "yearlyLivingCost":18000000,
  "currency":"IDR",
  "terms":4
}
*/
calculateEducationGoal(payload)

Calculate cost of university for a child after adjusting for inflation to the year of child's education.

const { education } = sdk;
const { calculateEducationGoal } = education;
const { data, error } = await calculateEducationGoal({
  yearlyTuitionCost: 300000,
  yearlyAccommodationCost: 30000,
  yearlyLivingCost: 30000,
  terms: 4,
  ageOfUni: 18,
  age: 3,
  inflationRate: 0.04,
  isPublicCollege: false,
  isMedicine: true,
  country: 'Philippines',
  currency: 'PHP',
});
console.log(data); // 4324321
getTidbit({ topic, params })

Get education related tidbit

const { education } = sdk;
const { getTidbit } = education;
const { data } = await getTidbit({
  topic: 'avarageUniCostByLocality',
  params:{  
    educationCountry: 'USA',
    originCountry: 'Vietnam',
    useLocalLanguage: true,
    isInternationalClass: true,
    currency: 'VND'
  }
});
console.log(data);
/*
{  
  "copy":"Chi phí giáo dục trung bình hàng năm ở các trường đại học dân lập tại Việt Nam là ",
  "emphasis":"4,343,831,700 USD"
}
*/

The topic attribute in the payload accepts avarageUniCostByLocality and averageUniCostByOwner.

The required attributes of params attribute depends on the topic selected:

  1. topic averageRetirementAge accepts params with attributes: educationCountry (e.g USA), originCountry (e.g Vietnam), isInternationalClass (Boolean), currency (e.g PHP), and useLocalLanguage (Boolean).
  2. topic averageUniCostByOwner accepts params with attributes: educationCountry (e.g USA), originCountry (e.g Vietnam), isPublicCollege (Boolean), currency (e.g PHP), and useLocalLanguage (Boolean).
getDefaultAgeOfUni({ age, country, isMedicine })
const { education } = sdk;
const { getDefaultAgeOfUni } = education;
const { data, error } = await getDefaultAgeOfUni({
  age: 10,
  country: 'Philippines',
  isMedicine: false,
});

console.log(data); // 16

Budget

getDefaultGoalSavingBreakdown(country)

Get default values for customer's saving towards a goal.

const { budget } = sdk;
const { getDefaultGoalSavingBreakdown } = budget;
const { data, error } = await getDefaultGoalSavingBreakdown({
  country: 'Indonesia',
  useLocalLanguage: false,
});
console.log(data);
/*
[  
  {  
    "assetClass":"Banks (Money Market) fund",
    "rate":0.07
  },
  {  
    "assetClass":"Bonds (Fixed Income) fund",
    "rate":0.09
  },
  {  
    "assetClass":"Balanced (Managed) fund",
    "rate":0.12
  },
  {  
    "assetClass":"Stocks (Equity) fund",
    "rate":0.14
  }
]
*/
getTidbit({ topic, params })

Get protection related tidbit

const { budget } = sdk;
const { getTidbit } = budget;
const { data, error } = await getTidbit({
  topic: 'howMuchPeopleLikeYouInvest',
  params: {
    country: 'Vietnam',
    gender: 'male',
    age: 27,
    useLocalLanguage: false,
  }
});
console.log(data);
/*
{
  "copy": "As a rule of thumb, you should put aside 15% of your monthly income for investment every month.",
  "emphasis": null,
}
*/

The topic attribute in the payload accepts howMuchPeopleLikeYouInvest.

The required attributes of params attribute depends on the topic selected:

  1. topic howMuchPeopleLikeYouInvest accepts params with attributes: country (e.g Philippines), gender (e.g male), age (e.g 25), and useLocalLanguage (Boolean).
getBudgetExpenseBreakdown({ country, income })

Calculate approximation of expenses budget given country and the customer's income

const { budget } = sdk;
const { getBudgetExpenseBreakdown } = budget;
const { data, error } = await getBudgetExpenseBreakdown({
  country: 'Philippines',
  income: 1000000
});

console.log(data);
/*
  {  
    "currency":"PHP",
    "data":[  
      {  
        "category":"Housing",
        "monthlyExpense":112830
      },
      {  
        "category":"Food",
        "monthlyExpense":13031364
      },
      {  
        "category":"Transport",
        "monthlyExpense":264091
      },
      {  
        "category":"Healthcare",
        "monthlyExpense":1275636
      },
      {  
        "category":"Travel",
        "monthlyExpense":8858909
      },
      {  
        "category":"Recreation/Other",
        "monthlyExpense":3041818
      },
      {  
        "category":"Regular Commitments",
        "monthlyExpense":0
      }
    ]
  }
*/
calculateBudgetExpensesPercentage({ country, income })

Same with getBudgetExpenseBreakdown({ country, income }) but this one returns the percentage of each expense category.

const { budget } = sdk;
const { calculateBudgetExpensesPercentage } = budget;
const { data, error } = await calculateBudgetExpensesPercentage({
  country: 'Philippines',
  income: 30001
});

console.log(data);
/*
[  
  {  
    "category":"Housing",
    "expensePercentage":0.24131510037823684
  },
  {  
    "category":"Food",
    "expensePercentage":0.6848996217631655
  },
  {  
    "category":"Transport",
    "expensePercentage":0.03366307826592959
  },
  {  
    "category":"Healthcare",
    "expensePercentage":0.02542915333139366
  },
  {  
    "category":"Travel",
    "expensePercentage":0.00887401803898749
  },
  {  
    "category":"Recreation/Other",
    "expensePercentage":0.005819028222286878
  },
  {  
    "category":"Regular Commitments",
    "expensePercentage":0
  }
]
*/

Protection

getProtectionOptions({ country, language })

Get available protection product options in a country along with it descriptive question.

const { protection } = sdk;
const { getProtectionOptions } = protection;
const { data } = await getProtectionOptions({
  country: 'Philippines',
  language: 'Filipino',
});
console.log(data);
/*
  [
    {
      "productName": "criticalIllness",
      "description": "Pagkuha ng malubhang karamdaman at hindi upang bayaran ang paggamot",
    },
    // other products
  ]
*/

Attribute language accepts 'English', 'Indonesian', 'Filipino', and 'Vietnamese'.

getProtectionBreakdown({ protections, country, annualIncome })

Get recommendation of selected protection products along with their detailed breakdown

const { protection } = sdk;
const { getProtectionBreakdown } = protection;
const { data } = await getProtectionBreakdown({
  selectedProtections: ['lifeInsurance'],
  country: 'Indonesia',
  annualIncome: 8000000,
  goalValues: {
    retirement: 333,
  },
});
console.log(data);
/*
{
  "currency": "IDR",
  "products": [
    {
      "productName": "lifeInsurance",
      "recommended": true,
      "mortgage" {
        "min": 0,
        "max": 400000000,
        "default": 240000000
      },
      "funeralCost": {
        "min": 0,
        "max": 500000000,
        "default": 150000000
      },
      "incomeReplacement": {
        "value": {
          "min": 0,
          "max": 160000000,
          "default": 400000000
        },
        "duration": {
          "min": 0,
          "max": 20,
          "default": 5
        }
      },
      "retirement": 120000,
      "totalCover": {
        "min": 0,
        "max": 288719000000,
        "default": 79000333
      },
    },
    // other products available in `country` with attribute `recommended` set to false because it's not included in `selectedProtections`
  ]
}
*/

The attribute protections is an array of string containing the selected products we want to breakdown. Accepts ['criticalIllness', 'lifeInsurance', 'totalPermanentDisability', 'hospitalCash', 'personalAccident', 'medicalReimbursement'].

getTreatmentCostOptions(country)

Get available treatment options for criticalIllness product.

const { protection } = sdk;
const { getTreatmentCostOptions } = protection;
const { data } = await getTreatmentCostOptions('Philippines');
console.log(data);
/*
{
  "currency": "PHP",
  "options": {
    "hospitalType": [
      {
        "id": 0,
        "value": 35000,
        "label": "Government (Public)",
      },
      {
        "id": 1,
        "value": 70000,
        "label": "Private",
      },
    ],
    "wardType": [
      {
        "id": 0,
        "value": 35000,
        "label": "Shared",
      },
      {
        "id": 1,
        "value": 70000,
        "label": "Semi-private",
      },
      {
        "id": 2,
        "value": 105000,
        "label": "Private",
      },
    ],
    "hospitalLocation": [
      {
        "id": 0,
        "value": 35000,
        "label": "Local only",
      },
      {
        "id": 1,
        "value": 70000,
        "label": "International",
      },
    ],
  }
}
*/
getMedicalPlanOptions(country)

Get available medical plan options for medicalReimbursement product.

const { protection } = sdk;
const { getMedicalPlanOptions } = protection;
const { data, error } = await getMedicalPlanOptions('Philippines');
console.log(data);
/*
[
  {
    "id":0,
    "name":"A",
    "totalAnnualLimit":25000,
    "currency":"USD",
    "areaOfCoverage":[  
      "Indonesia"
    ],
    "treatmentCategories":[  
      {  
        "categoryName":"Benefits of Inpatient and Surgical",
        "treatments":[  
          {  
            "name":"Room & Board",
            "value":50,
            "highlighted":true
          },
          {  
            "name":"Intensive Care Unit",
            "value":100,
            "highlighted":false
          },
          {  
            "name":"Accommodation Fees For Family",
            "value":160,
            "highlighted":false
          },
          {  
            "name":"Medical Doctor Visit",
            "value":"As charged; Within the maximum limit of total annual benefits",
            "highlighted":false
          },
          {  
            "name":"Specialist Doctor Visit",
            "value":"As charged; Within the maximum limit of total annual benefits",
            "highlighted":false
          },
          {  
            "name":"Miscellaneous Treatment Fee",
            "value":"As charged; Within the maximum limit of total annual benefits",
            "highlighted":false
          },
          {  
            "name":"Surgical",
            "value":"As charged; Within the maximum limit of total annual benefits",
            "highlighted":false
          }
        ]
      },
      {  
        "categoryName":"Pre and Post Hospitalization Treatment",
        "treatments":[  
          {  
            "name":"Nursing fee for post hospitalization",
            "value":30,
            "highlighted":true
          },
          {  
            "name":"Physiotherapy Fee",
            "value":20,
            "highlighted":false
          },
          {  
            "name":"Local Ambulance Fee",
            "value":50,
            "highlighted":false
          },
          {  
            "name":"Medical Report Fee",
            "value":20,
            "highlighted":false
          },
          {  
            "name":"Pre Hospitalization Treatment",
            "value":"As charged; Within the maximum limit of total annual benefits",
            "highlighted":false
          },
          {  
            "name":"Post Hospitalization Treatment",
            "value":"As charged; Within the maximum limit of total annual benefits",
            "highlighted":false
          },
          {  
            "name":"Implant and Prosthesis Fee",
            "value":"As charged; Within the maximum limit of total annual benefits",
            "highlighted":false
          }
        ]
      },
      {  
        "categoryName":"Outpatient Benefits",
        "treatments":[  
          {  
            "name":"Hemodialysis",
            "value":3000,
            "highlighted":true
          },
          {  
            "name":"Cancer Treatment",
            "value":7500,
            "highlighted":false
          },
          {  
            "name":"One Day Surgery",
            "value":500,
            "highlighted":false
          },
          {  
            "name":"Outpatient due to Accident",
            "value":1000,
            "highlighted":false
          },
          {  
            "name":"Burn Injury Treatment Fee",
            "value":500,
            "highlighted":false
          },
          {  
            "name":"Medical Check-up",
            "value":35,
            "highlighted":false
          }
        ]
      }
    ]
  }
  // other plans
]
*/
getTidbit({ topic, params })

Get protection related tidbit

const { protection } = sdk;
const { getTidbit } = protection;
const { data, error } = await getTidbit({
  topic: 'averageInsuranceProductCoverage',
  params: {
    productName: 'criticalIllness',
    country: 'Vietnam',
    gender: 'male',
    age: 27,
  }
});
console.log(data);
/*
{
  "copy": "Most people your age, have an average Critical Illness cover of 15,000,000.",
  "emphasis": null,
}
*/

The topic attribute in the payload accepts averageInsuranceProductCoverage and averageHospitalCashCoverage.

The required attributes of params attribute depends on the topic selected:

  1. topic averageInsuranceProductCoverage accepts params with attributes: productName (e.g criticalIllness), country (e.g Philippines), gender (e.g male), age (e.g 25), and useLocalLanguage (Boolean).
  2. topic averageHospitalCashCoverage accepts params with attributes: country (e.g Philippines), gender (e.g male), age (e.g 25), and useLocalLanguage (Boolean).
calculateProtectionScoreSingle({ country, annualIncome, productName, productsCoverage, otherCoverage, coverageTarget })

Calculate a score of a single protection.

const { protection } = sdk;
const { calculateProtectionScoreSingle } = protection;
const { data } = await calculateProtectionScoreSingle({
  assuredCoverage: 1000,
  defaultTotalCoverage: 2000,
  externalCoverage: 1500,
  targetCoverage: 1600,
});
console.log(data); // 0.55
calculateProjectionScoreMulti(protections)

Calculate aggregated protection score given protections scores.

const { protection } = sdk;
const { calculateProjectionScoreMulti } = protection;
const { data, error } = await calculateProjectionScoreMulti([
  { score: 0.9 },
  { score: 0.8 },
  { score: 0.7 },
]);
console.log(data); // 0.8

GoalOptimization

getMinSavings(payload)

Get minimum budget needed for goal optimization given a country.

const { goalOptimization } = sdk;
const { getMinSavings } = goalOptimization;
const { data, error } = await getMinSavings('Philippines');

console.log(data); // 18000
optimizeGoal(payload)

Calculate plans recommendation given initial target.

const { goalOptimization } = sdk;
const { optimizeGoal } = goalOptimization;
const { data, error } = await optimizeGoal({
  country: 'Philippines',
  paymentMode: 'A',
  dob: '1994-01-01',
  gender: 'F',
  budget: 5000000,
  protectionTargets: [
    {
      initialProtection: 0,
      target: 4100000,
      concern: 'lifeInsurance',
    },
    {
      initialProtection: 0,
      target: 2944450,
      concern: 'criticalIllness',
    },
  ],
  goalTargets: [
    {
      initialSavings: 0,
      projectionYear: 30,
      savingsTarget: 23730000,
    },
    {
      initialSavings: 0,
      projectionYear: 30,
      savingsTarget: 23730000,
    },
  ],
});

console.log(data);
/*
{ 
   "error":{ 
      "index":1,
      "message":"budget not enough for goal"
   },
   "data":{ 
      "protectionScore":0.2316169462832031,
      "goalData":[ 
         { 
            "goalScore":0.11799951327433629,
            "projection":2800128.45,
            "scoreDiff":-0.1136174330088668,
            "riders":[ 
               { 
                  "concern":"lifeInsurance",
                  "coi":1571.3,
                  "sumAssured":949629.4797611327
               },
               { 
                  "concern":"criticalIllness",
                  "coi":1235.16,
                  "sumAssured":681984.5174835774
               }
            ]
         },
         null
      ]
   }
}
*/

For Vietnam, we have to specify isEducation because education and other goal has a different product mapping.

const { goalOptimization } = sdk;
const { optimizeGoal } = goalOptimization;
const { data, error } = await optimizeGoal({
  country: 'Vietnam',
  paymentMode: 'M', // A (annually), S (semi-annually), Q (quarterly), M (monthly)
  dob: '2001-01-01', // yyyy-mm-dd
  gender: 'F', // M or F
  budget: 50000000,
  protectionTargets: [
    {
      initialProtection: 0,
      target: 1200000000,
      concern: 'lifeinsurance',
    },
    {
      initialProtection: 0,
      target: 500000000,
      concern: 'criticalIllness',
    },
  ],
  goalTargets: [
    {
      initialSavings: 0,
      isEducation: true,
      projectionYear: 18,
      savingsTarget: 1171139584,
    },
    {
      initialSavings: 0,
      isEducation: true,
      projectionYear: 5,
      savingsTarget: 1171139584,
    },
  ],
});

console.log(data);

/*
{ 
   "error":null,
   "data":{ 
      "protectionScore":0.32057708828125,
      "goalData":[ 
         { 
            "goalScore":0.36056643027298213,
            "projection":902825.62,
            "scoreDiff":0.03998934199173215,
            "riders":[ 
               { 
                  "concern":"lifeInsurance",
                  "coi":1389.68,
                  "sumAssured":801442.720703125
               },
               { 
                  "concern":"personalAccident",
                  "coi":969.36,
                  "sumAssured":801442.720703125
               }
            ]
         },
         { 
            "goalScore":0,
            "projection":0,
            "scoreDiff":0,
            "riders":[ 

            ]
         }
      ]
   }
}
*/

Risk

getRiskQuestions({ country, inEnglish })

Get list of risk profile questions which will be answered by customers. The results of this question will then be passed as a parameter of calculateRiskProfile({ country, riskScores }).

const { risk } = sdk;
const { getRiskQuestions } = risk;
const { data } = await getRiskQuestions({
  country: 'Philippines',
  inEnglish: true,
});
console.log(data);
/*
  [
    {
      "questionType": "investmentGoal",
      "question": "What is your primary goal in investing?",
      "options": [
        { "value:" 1, "label": "To earn regular income while preserving my capital" },
        { "value": 2, "label": "To have the potential for medium gains while accepting moderate risks" },
        { "value": 3, "label": "To have the potential for large gains while accepting potential losses" },
      ],
    },
    {
      "questionType": "investmentTerm",
      "question": "How long do you intend to keep your investment?",
      "options": [
        { "value": 1, "label": "Short-term(1 year or less)" },
        { "value": 2, "label": "Medium (1-3 years)" },
        { "value": 3, "label": "Long (more than 3 years)" },
      ],
    },
  ]
*/
calculateRiskProfile({ country, riskScores })

Compute user's risk profile based on the questions from getRiskQuestions(country).

const { risk } = sdk;
const { calculateRiskProfile } = risk;
const { data } = await calculateRiskProfile({
  country: 'Philippines',
  riskScores: {
    investmentGoal: 2,
    investmentTerm: 2,
  }
});
console.log(data);
/*
  {
    "riskLevel": "Balanced",
    "productRiskLevel": "Medium"
  }
*/

sync

Use sync to try to push all locally modified data to the server

const { sync } = sdk;
const {
  status,
  message,
  customerSyncData,
  leadSyncData,
  goalSyncData,
  retirementSyncData,
  educationSyncData,
  hajjSyncData,
} = await sync();

This will command the SDK to go through all the changes that are saved locally and send them all to the server.

Utilities

getCountryIncomeRanges(country)

Get all income ranges for retirement calculator in a country.

const { utilities } = sdk;
const { getCountryIncomeRanges } = utilities;
const { data } = await getCountryIncomeRanges('Indonesia');
console.log(data);
/*
  {
    "currency": "IDR",
    "data": [
      { "lowerBound": 0, "upperBound": 1000000 },
      { "lowerBound": 1000001, "upperBound": 2000000 },
      { "lowerBound": 2000001, "upperBound": 3000000 },
      { "lowerBound": 3000001, "upperBound": 5000000 },
      { "lowerBound": 5000001, "upperBound": 7500000 },
      { "lowerBound": 7500001, "upperBound": 10000000 },
      { "lowerBound": 10000001, "upperBound": 9007199254740991 },
    ]
  }
*/
calculateGoalProjection(payload)

Calculate a goal value of a common goal.

async calculateGoalProjection() {
  const { utilities } = sdk;
  const { calculateGoalProjection } = utilities;
  const { data, error } = await calculateGoalProjection({
    goalValue: 10000,
    yearsToGoal: 20,
    inflationRate: 0.04
  });
  console.log(JSON.stringify(data)); // 21911.23
}
getConvertedCurrencyAmount({ amount, sourceCurrency, targetCurrency })

Convert a currency amount.

async getConvertedCurrencyAmount() {
  const { utilities } = sdk;
  const { getConvertedCurrencyAmount } = utilities;
  const { data, error } = await getConvertedCurrencyAmount({
    amount: 1000,
    sourceCurrency: 'PHP',
    targetCurrency: 'IDR',
  });

  console.log(data); // 272107.53
}
updateExchangeRate()

Update local exchange data with the latest one from the server.

const { utilities } = sdk;
const { updateExchangeRate } = utilities;
const { data, error } = await updateExchangeRate();

console.log(data);
/*
[  
  {  
    "source":"USD",
    "target":"USD",
    "rate":1
  },
  {  
    "source":"USD",
    "target":"SGD",
    "rate":1.366195
  },
  {  
    "source":"USD",
    "target":"IDR",
    "rate":14256
  },
  {  
    "source":"USD",
    "target":"PHP",
    "rate":52.40599
  },
  {  
    "source":"USD",
    "target":"VND",
    "rate":23302.5
  },
  {  
    "source":"USD",
    "target":"THB",
    "rate":32.777017
  },
  {  
    "source":"USD",
    "target":"MYR",
    "rate":4.159598
  },
  {  
    "source":"USD",
    "target":"HKD",
    "rate":7.82001
  }
]
*/
getDefaultInflationRate(country)

Get default inflation rate given a country name

const { utilities } = sdk;
const { getDefaultInflationRate } = utilities;
const { data, error } = await getDefaultInflationRate('NewZealand');

console.log(data); // 0.02

The parameter country accepts Philippines, Indonesia, Vietnam, USA, UK, Singapore, Malaysia, NewZealand, Australia, and Canada.

getTidbit({ topic, params })

Get miscellaneous tidbit

const { utilities } = sdk;
const { getTidbit } = utilities;
const { data } = await getTidbit({
  topic: 'averageRetirementAge',
  params: {
    country: 'Philippines',
  }
});
console.log(data);
/*
{
  "copy": "Don't forget about inflation. Philippines had an average annual inflation rate of 4.95% p.a. in 2018.",
  "emphasis": null,
}
*/

The topic attribute in the payload accepts averageRetirementAge, incomeReplacementSize, and averageLifeExpectancy.

The required attributes of params attribute depends on the topic selected:

  1. topic inflationRate accepts params with attributes: country (e.g Vietnam) and useLocalLanguage (Boolean).

flush

Use flush to clear all local data, for example, you might need to clear one user's data before logging in another user.

const { flush } = sdk;
const { status, message } = await flush();
console.log(status, message); // OK, Local data is successfully flushed.