Skip to content

Commit

Permalink
Fix accounts chart ordering
Browse files Browse the repository at this point in the history
  • Loading branch information
mbayopanda authored and jniles committed Sep 28, 2016
1 parent 5934343 commit 6aba69c
Showing 1 changed file with 39 additions and 26 deletions.
65 changes: 39 additions & 26 deletions server/controllers/finance/accounts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,42 +238,55 @@ function lookupAccount(id) {
* @return {array} accounts the updated list of accounts with depths
*/
function processAccountDepth(accounts) {
let indexedAccounts = lodash.keyBy(accounts, 'id');
// root node
const ROOT_NODE = 0;

return accounts.map(acc => {
let depth = getDepth(acc, 0, indexedAccounts);
acc.depth = depth;
return acc;
});
// build the account tree
let tree = getChildren(accounts, ROOT_NODE);

// return a flattened tree (in order)
accounts = flatten(tree);

return accounts;
}

/**
* @function getDepth
* @description return the depth of an account
* @param {object} account An account object
* @param {number} depth The default depth of the account given
* @function getChildren
* @description return the children accounts of an account given
* @param {array} accounts list of accounts
* @return {number} depth The real depth
* @param {number} parentId The parent id
*/
function getDepth(account, depth, accounts) {
if (account.parent === 0) {
return depth;
}
else {
let parent = getParent(account, accounts);
return getDepth(parent, ++depth, accounts);
}
function getChildren(accounts, parentId) {
let children;

if (accounts.length === 0) { return null; }

children = accounts.filter(function (account) {
return account.parent === parentId;
});

children.forEach(function (account) {
account.children = getChildren(accounts, account.id);
});

return children;
}

/**
* @function getParent
* @description return the parent account of an account given
* @param {object} account An account object
* @param {array} accounts list of accounts
* @return {object} account The parent account object
* @function flatten
* @description return a flatten array
* @param {array} tree list of accounts as tree
* @param {number} depth A depth
*/
function getParent(account, accounts) {
return accounts[account.parent];
function flatten(tree, depth) {
depth = isNaN(depth) ? -1 : depth;
depth += 1;

return tree.reduce(function (array, node) {
node.depth = depth;
var items = [node].concat(node.children ? flatten(node.children, depth) : []);
return array.concat(items);
}, []);
}

exports.list = list;
Expand Down

0 comments on commit 6aba69c

Please sign in to comment.