Skip to content

Feature/data calculation #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
119 changes: 24 additions & 95 deletions README.md
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,95 +1,24 @@
# 9Spokes Coding Challenge

## Overview

This repo contains the instructions and the data you need to complete the _9Spokes coding challenge_. This challenge is not intended to be complex, but it is an opportunity for you to showcase your understanding and applying of good development practices.

You are encouraged to treat this as a real-life project. This typically means:

- Use version control effectively
- Include some basic documentation
- Include some unit tests
- Use a naming convention

You are free to use any programming language you'd like.

## The Challenge

You are tasked with developing an application that performs the following tasks in sequence:

- Read and parse an external data file `data.json` (located in this repo)
- Using this data, calculate and print the values of 5 common accounting metrics:
1. Revenue
2. Expenses
3. Gross Profit Margin
4. Net Profit Margin
5. Working Capital Ratio
- Commit your changes, and upload all your work to a feature branch of your choice.

## Instructions

- Begin by _forking_ the current repository to your own `github.com` account
- Clone the repo locally
- Write your code, commit often
- Once you are satisfied with the output, push your changes to your `github.com` account
- Share the link

## Calculations

Use the formulas below to calculate your values:

### Revenue

This should be calculated by adding up all the values under `total_value` where the `account_category` field is set to `revenue`

### Expenses

This should be calculated by adding up all the values under `total_value` where the `account_category` field is set to `expense`

### Gross Profit Margin

This is calculated in two steps: first by adding all the `total_value` fields where the `account_type` is set to `sales` and the `value_type` is set to `debit`; then dividing that by the `revenue` value calculated earlier to generate a percentage value.

### Net Profit Margin

This metric is calculated by subtracting the `expenses` value from the `revenue` value and dividing the remainder by `revenue` to calculate a percentage.

### Working Capital Ratio

This is calculated dividing the `assets` by the `liabilities` creating a percentage value where `assets` are calculated by:

- adding the `total_value` from all records where the `account_category` is set to `assets`, the `value_type` is set to `debit`, and the `account_type` is one of `current`, `bank`, or `current_accounts_receivable`
- subtracting the `total_value` from all records where the `account_category` is set to `assets`, the `value_type` is set to `credit`, and the `account_type` is one of `current`, `bank`, or `current_accounts_receivable`

and liabilities are calculated by:

- adding the `total_value` from all records where the `account_category` is set to `liability`, the `value_type` is set to `credit`, and the `account_type` is one of `current` or `current_accounts_payable`
- subtracting the `total_value` from all records where the `account_category` is set to `liability`, the `value_type` is set to `debit`, and the `account_type` is one `current` or `current_accounts_payable`

## Formatting

All currency figures must be formatted as follows:
- The value is prefixed with a `$` sign
- A comma is used to separate every 3 digits in the thousands, millions, billions, and trillions
- Cents are removed

All percentage values must be formatted to one decimal digit and be prefixed with a `%` sign. Don't forget to multiply by 100 each time you're tasked with calculating a percentage value.

## Example

Below is what a typical output should look like. Please note this is *not* the output of the challenge but a mere example.

```
$ ./myChallenge
Revenue: $519,169
Expenses: $411,664
Gross Profit Margin: 22%
Net Profit Margin: 21%
Working Capital Ratio: 95%
```

# Dependencies

If your program requires a special way to compile or a specific version of a toolset, please be sure to include that in your running instructions.

__Thank you and good luck!__
## Statics Calculations

> Project documentation can be found [here](https://github.com/akumbhani66/coding-challenge/blob/feature/data-calculation/instructions.md)

## Prerequestics
* Node v12.0 or above
* NPM v5.0 or above

## How to Run?
`./run`

OR

1. `$npm install` - to install depedencies
2. `$npm start` - to Run the project

## How to test?
* `$npm test` - to run test suits
* `$npm run coverage` - to get the coverage report of codebase.
* current codebase report can be found [here](https://github.com/akumbhani66/coding-challenge/blob/feature/data-calculation/tests/test-report/index.html) - This report can be host somewhere


## How to publish?
TODO:
62 changes: 62 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const {
readDataFromFile, calcAccountRevenue, calcAccountExpenses, calcGrossProfitMargin,
calcNetProfitMargin, calcWorkingCapitalRatio, formatCurrency
} = require('./helpers/helpers');

async function calcResult() {
// STEP:1 Read the data.
let data;
try {
data = await readDataFromFile("seed/data.json");
} catch (err) {
console.log(`Invalid filename or inappropriate file content: Error:${err}`);
return;
}

// STEP: 2 Calc account revenue
let accountRevenue;
try {
accountRevenue = await calcAccountRevenue(data);
} catch (err) {
console.log(`Error on calculating account revenue:${err}`);
return;
}

// STEP: 3 Calc account Expenses
let accountExpenses;
try {
accountExpenses = await calcAccountExpenses(data);
} catch (err) {
console.log(`Error on calculating account Expenses:${err}`);
return;
}

// STEP: 3 Calc Gross Profit Margin
let grossProfitMargin;
try {
grossProfitMargin = await calcGrossProfitMargin(data, accountRevenue);
} catch (err) {
console.log(`Error on calculating Gross Profit Margin:${err}`);
return;
}

// STEP: 4 Calc Net Profit Margin
const netProfitMargin = calcNetProfitMargin(accountExpenses, accountRevenue);

// Step: 5 Calc Working Capital Ratio
let workingCapitalRatio;
try {
workingCapitalRatio = await calcWorkingCapitalRatio(data);
} catch (err) {
console.log(`Error on calculating Gross Profit Margin:${err}`);
return;
}

console.log(`Revenue: $${formatCurrency(accountRevenue)}`);
console.log(`Expenses: $${formatCurrency(accountExpenses)}`);
console.log(`Gross Profit Margin: ${Math.round(grossProfitMargin)}%`);
console.log(`Net Profit Margin: ${Math.round(netProfitMargin)}%`);
console.log(`Working Capital Ratio: ${Math.round(workingCapitalRatio)}%`);
}

calcResult();
184 changes: 184 additions & 0 deletions helpers/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
const fs = require('fs');

module.exports.readDataFromFile = (FILE_PATH) => {
return new Promise((resolve, reject) => {
try {
const rawdata = fs.readFileSync(FILE_PATH);
const data = JSON.parse(rawdata);
resolve(data);
} catch (err) {
reject(err);
}
})
};


/**
* This should be calculated by adding up all the values under total_value where the account_category field is set to revenue
*
* @param {*} data Obj
* @returns totalRevenue Int
*/
module.exports.calcAccountRevenue = (data) => {
return new Promise((resolve, reject) => {
if (data === undefined || data.data === undefined || data.data.length < 0) return reject("Insufficient/Incorrect data.")

let totalRevenue = 0;
for (let i = 0; i < data.data.length; i += 1)
if (data.data[i].account_category.toLowerCase() === `revenue`)
totalRevenue += data.data[i].total_value;

return resolve(totalRevenue);
});
};


/**
* This should be calculated by adding up all the values under total_value where the account_category field is set to expense
* @param {*} data Obj
* @returns expenses Int
*/
module.exports.calcAccountExpenses = (data) => {
return new Promise((resolve, reject) => {
if (data === undefined || data.data === undefined || data.data.length < 0) return reject("Insufficient/Incorrect data.")

let expenses = 0;
for (let i = 0; i < data.data.length; i += 1)
if (data.data[i].account_category.toLowerCase() === `expense`)
expenses += data.data[i].total_value;

return resolve(expenses);
});
};


/**
* This is calculated in two steps:
* first by adding all the total_value fields where the account_type is set to sales and the value_type is set to debit;
* then dividing that by the revenue value calculated earlier to generate a percentage value.
*
* @param {*} data Obj
* @param {*} revenue Int
* @returns grossProfitMargin Int
*/
module.exports.calcGrossProfitMargin = (data, revenue) => {
return new Promise((resolve, reject) => {
if (data === undefined || data.data === undefined || data.data.length < 0) return reject("Insufficient/Incorrect data.")

let grossProfitToCalc = 0;
for (let i = 0; i < data.data.length; i += 1)
if (data.data[i].account_category.toLowerCase() === `sales` && data.data[i].value_type.toLowerCase() === `debit`)
grossProfitToCalc += data.data[i].total_value;

return resolve(grossProfitToCalc / revenue);
});
};


/**
* This metric is calculated by subtracting the expenses value from the revenue value and
* dividing the remainder by revenue to calculate a percentage.
*
* @param {*} expenses Int
* @param {*} revenue Int
* @returns
*/
module.exports.calcNetProfitMargin = (expenses, revenue) => {
return ((expenses - revenue) / revenue);
};


/**
* This is calculated dividing the assets by the liabilities creating a percentage value
*
* @param {*} data Obj
* @returns workingCapitalRatio Int
*/
module.exports.calcWorkingCapitalRatio = (data) => {
return new Promise((resolve, reject) => {
if (data === undefined || data.data === undefined || data.data.length < 0) return reject("Insufficient/Incorrect data.")
const assets = calcAssets(data);
const liabilities = calcLiabilities(data);

return resolve(assets / liabilities);
});
};


/**
* adding the total_value from all records where the account_category is set to assets, the value_type is set to debit,
* and the account_type is one of current, bank, or current_accounts_receivable
*
* subtracting the total_value from all records where the account_category is set to assets, the value_type is set to credit,
* and the account_type is one of current, bank, or current_accounts_receivable
*
* @param {*} data Obj
* @returns assets Int
*/
function calcAssets(data) {
let assets = 0;
for (let i = 0; i < data.data.length; i += 1)
if (
data.data[i].account_category.toLowerCase() === `assets` &&
data.data[i].value_type.toLowerCase() === `debit` &&
data.data[i].account_type.toLowerCase() === `current` ||
data.data[i].account_type.toLowerCase() === `bank` ||
data.data[i].account_type.toLowerCase() === `current_accounts_receivable`
)
assets += data.data[i].total_value;

let assetsToDeduct = 0;
for (let i = 0; i < data.data.length; i += 1)
if (
data.data[i].account_category.toLowerCase() === `assets` &&
data.data[i].value_type.toLowerCase() === `credit` &&
data.data[i].account_type.toLowerCase() === `current` ||
data.data[i].account_type.toLowerCase() === `bank` ||
data.data[i].account_type.toLowerCase() === `current_accounts_receivable`
) {
assetsToDeduct += data.data[i].total_value
}

return assets - assetsToDeduct;
};


/**
* adding the total_value from all records where the account_category is set to liability, the value_type is set to credit,
* and the account_type is one of current or current_accounts_payable
*
* subtracting the total_value from all records where the account_category is set to liability, the value_type is set to debit,
* and the account_type is one current or current_accounts_payable
*
* @param {*} data Obj
* @returns liabilities Int
*/
function calcLiabilities(data) {
let liabilities = 0;
for (let i = 0; i < data.data.length; i += 1)
if (
data.data[i].account_category.toLowerCase() === `liability` &&
data.data[i].value_type.toLowerCase() === `credit` &&
data.data[i].account_type.toLowerCase() === `current` ||
data.data[i].account_type.toLowerCase() === `current_accounts_payable`
)
liabilities += data.data[i].total_value;

let liabilitiesToDeduct = 0
for (let i = 0; i < data.data.length; i += 1)
if (
data.data[i].account_category.toLowerCase() === `liability` &&
data.data[i].value_type.toLowerCase() === `debit` &&
data.data[i].account_type.toLowerCase() === `current` ||
data.data[i].account_type.toLowerCase() === `current_accounts_payable`
)
liabilitiesToDeduct += data.data[i].total_value

return liabilities - liabilitiesToDeduct;
};

module.exports.formatCurrency = (x) => {
const parts = x.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");

}
Loading