accountant-ui/src/html/js/months.js

97 lines
3.0 KiB
JavaScript

/*
This file is part of Accountant.
Accountant is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Foobar is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Accountant. If not, see <http://www.gnu.org/licenses/>.
*/
// Month object
function month() {
this.year = null;
this.month = null;
}
var MonthController = function($scope, $http, $rootScope) {
// Month store and selection
$scope.months = null;
$scope.month = null;
$scope.account = null;
$scope.monthClass = function(month) {
if(month == $scope.month) {
return "active";
}
};
// Function to load months
$scope.loadMonths = function(account) {
if(account) {
$scope.account = account;
}
if($scope.account) {
$http.get("api/accounts/" + $scope.account.id + "/months").success($scope.loadMonths_success);
} else {
$scope.$emit("monthsLoadedEvent", {account: null, month: null});
}
};
$scope.loadMonths_success = function (data) {
// Update months
$scope.months = angular.fromJson(data);
var monthToSelect = null;
var today = new Date();
var currentYear = today.getFullYear().toString();
var currentMonth = (today.getMonth() + 1 < 10 ? "0" : "") + (today.getMonth() + 1);
// Find the new instance of the previously selected month.
angular.forEach($scope.months, function(month) {
// Reset selected month to the new instance corresponding to the old one
if($scope.month) {
if(month == $scope.month) {
monthToSelect = month;
}
} else {
if(month.year === currentYear && month.month === currentMonth) {
monthToSelect = month;
}
}
});
// Set selected month to the last one if not yet selected.
if(!monthToSelect && $scope.months.length > 0) {
monthToSelect = $scope.months[$scope.months.length - 1];
}
// Reset to month to select
$scope.month = monthToSelect;
$scope.$emit("monthsLoadedEvent", {account: $scope.account, month: $scope.month});
};
// Callback function to select a new month.
$scope.selectMonth = function(month) {
if(month) {
$scope.month = month;
$scope.$emit("monthsLoadedEvent", {account: $scope.account, month: month});
}
};
$rootScope.$on("accountsLoadedEvent", function(event, args) {
$scope.loadMonths(args.account);
});
};