finance.js

angular.module('homepage').
directive('finance', function () {
    return {
        controller: 'FinanceController',
        restrict: 'E',
        replace: true,
        transclude: true,
        templateUrl: 'components/feature-components/finance/finance.html'
    }
}).
controller('FinanceController', function ($scope, ArrayUtility, DateUtility, Server) {
    $scope.finances = new Array(12);

    function resetAll() {
        $scope.total = 0;
        ArrayUtility.reassignArray($scope.finances, []);
    }

    function addByMonth(item, timestamp) {
        var finance = {
            amount: item.amount, 
            title: item.title,
            timestamp: timestamp
        };

        var financeMonthIndex = new Date(timestamp).getMonth();
        if(!$scope.finances[financeMonthIndex]) {
            $scope.finances[financeMonthIndex] = [];
        }
        $scope.finances[financeMonthIndex].push(finance);
        $scope.total += finance.amount;
    }

    function calculateTotal(expenses, attrName) {
        if(expenses) {
            return expenses.reduce(function(total,current) {
                if(current[attrName]) {
                    return total + current[attrName];
                }
                return total;
            }, 0);
        } else {
            return 0;
        }
    };

    resetAll();

    $scope.getTotal = calculateTotal;

    $scope.getMoneyData = function (dateRange) {	
        Server.getMoneyData(dateRange).success(function (result) {
            resetAll();

            var entries = result.documents;
            
            entries.forEach(function(entry) {
                entry.data.list.forEach(function(item) {
                    if(item.amount) {
                        addByMonth(item, entry.timestamp);
                    }
                })
            });
        });
	};
	
	var currentMonthIndex = new Date().getMonth();

	$scope.choosen = {
		year: 2018,
		month: currentMonthIndex
	};

	$scope.getMoneyData(DateUtility.
		getMonthDateRange(new Date($scope.choosen.year, currentMonthIndex, 1)));
});