accountant/src/html/js/entries.js

496 lines
15 KiB
JavaScript
Raw Normal View History

// Entry object
2013-01-13 12:27:42 +01:00
function entry(){
this.id=ko.observable();
this.value_date=ko.observable();
this.operation_date=ko.observable();
this.label=ko.observable();
this.value=ko.observable();
this.account_id=ko.observable();
this.sold=ko.observable();
this.pointedsold=ko.observable();
this.category=ko.observable();
2013-01-07 18:42:02 +01:00
}
// Account object
function account() {
this.id=ko.observable();
this.name=ko.observable();
this.future=ko.observable();
this.current=ko.observable();
this.pointed=ko.observable();
}
// Month object
function month() {
this.year=ko.observable();
this.month=ko.observable();
}
2013-01-13 10:14:43 +01:00
// Util function to show a message in message placeholder.
2013-01-07 18:42:02 +01:00
function message(alertType, title, message) {
$(".alert").alert('close');
$("#message-placeholder").append('<div class="alert alert-' + alertType + '"><button type="button" class="close" data-dismiss="alert">&times;</button><h4>' + title + '</h4><strong>' + message + '</strong></div>');
}
// The ListViewModel used to instanciate viewmodel.
2013-01-07 18:42:02 +01:00
var ListViewModel = function() {
var self = this;
2013-01-13 10:14:43 +01:00
// Account store and selection
2013-01-07 18:42:02 +01:00
self.account = ko.observable();
self.accounts = ko.observableArray([]);
2013-01-13 10:14:43 +01:00
// Month store and selection
2013-01-07 18:42:02 +01:00
self.months = ko.observableArray();
self.month = ko.observable();
2013-01-13 10:14:43 +01:00
// Entry store and selection
self.entries = ko.observableArray([]);
2013-01-07 18:42:02 +01:00
self.selectedItem = ko.observable();
2013-01-13 10:14:43 +01:00
// Placeholder for saved value to cancel entry edition
self.savedItem = null;
2013-01-13 10:14:43 +01:00
// Placeholder for entry to remove to be available in modal function "yes" click callback
self.itemToRemove = ko.observable();
2013-01-07 18:42:02 +01:00
2013-01-13 10:14:43 +01:00
// Returns the data for the categories by summing values with same category
self.expenseCategoriesChart = ko.computed(function() {
2013-01-13 13:32:23 +01:00
var unwrap = ko.utils.unwrapObservable;
var entries=unwrap(self.entries);
2013-01-13 10:14:43 +01:00
// First pass: get sum values for each category.
var chartValuesTmp = {};
$.each(entries, function(index, entry) {
2013-01-13 13:32:23 +01:00
var category = unwrap(entry.category);
var value = unwrap(entry.value) ? Number(unwrap(entry.value)) : null;
2013-01-13 10:14:43 +01:00
if(category && value && value < 0.0) {
var oldValue = 0.0;
if(chartValuesTmp[category]) {
oldValue = chartValuesTmp[category];
}
chartValuesTmp[category] = oldValue - value
}
});
2013-01-13 10:14:43 +01:00
// Second pass: transform to an array readable by jqplot.
var chartValues = [];
$.each(chartValuesTmp, function(key, value) {
chartValues.push([key, value]);
});
return chartValues;
});
2013-01-13 10:14:43 +01:00
// Return the data for the sold chart.
self.entriesChart = ko.computed(function() {
2013-01-13 13:32:23 +01:00
var unwrap = ko.utils.unwrapObservable;
2013-01-13 10:14:43 +01:00
// We assume that entries are sorted by value date descending.
2013-01-13 13:32:23 +01:00
var entries = unwrap(self.entries).slice().reverse();
2013-01-13 10:14:43 +01:00
// First pass: get open, high, low and close values for each day.
var chartValuesTmp = {};
$.each(entries, function(index, entry) {
//var date = entry.value_date() ? entry.value_date().toString() : null;
2013-01-13 13:32:23 +01:00
var date = unwrap(entry.value_date);
var value = unwrap(entry.value) ? Number(unwrap(entry.value())) : null;
if(date && value) {
var values = {};
2013-01-13 13:32:23 +01:00
var sold = Number(unwrap(entry.sold));
var open = Number((sold - value).toFixed(2));
values['open'] = open;
values['high'] = sold > open ? sold : open;
values['low'] = sold < open ? sold : open;
values['close'] = sold;
if(chartValuesTmp[date]) {
var oldValues = chartValuesTmp[date];
if(oldValues['high'] > values['high']) {
values['high'] = oldValues['high'];
}
if(oldValues['low'] < values['low']) {
values['low'] = oldValues['low'];
}
values['open'] = oldValues['open'];
}
chartValuesTmp[date] = values;
}
});
2013-01-13 10:14:43 +01:00
// Second pass: transform to an array readable by jqplot OHLC renderer.
var chartValues = [];
$.each(chartValuesTmp, function(key, value) {
2013-01-13 10:14:43 +01:00
chartValues.push([key, value['open'], value['high'], value['low'], value['close']]);
});
return chartValues;
}, self);
2013-01-13 10:14:43 +01:00
// Function to load entries from server for a specific account and month.
self.loadEntries = function(account, month) {
$.post("api/entry.php", {action: "get_entries", account: account.id(), year: month.year(), month: month.month()}, function(data) {
2013-01-13 10:14:43 +01:00
// Clean up selected entry.
2013-01-07 18:42:02 +01:00
self.selectedItem(null);
// Update entries
self.entries(ko.utils.arrayMap(data, ko.mapping.fromJS));
});
};
// Function to load accounts
self.loadAccounts = function() {
$.post("api/entry.php", {action: "get_accounts"}).success(function (data) {
// Update accounts
self.accounts(ko.utils.arrayMap(data, ko.mapping.fromJS));
// Reset selected account to the new instance corresponding to the old one.
if(self.account()) {
var oldId = self.account().id();
// Reset to null
self.account(null);
// Find the new instance of the previously selected account.
$.each(self.accounts(), function(index, account) {
if(account.id() == oldId) {
self.account(account);
}
});
}
// Set selected account to first one if not yet selected
if(!self.account()){
self.account(self.accounts()[0]);
}
// Load months
self.loadMonths(self.account());
});
};
2013-01-07 18:42:02 +01:00
// Function to load months
self.loadMonths = function(account){
$.post("api/entry.php", {action: "get_months", account: account.id()}).success(function (data) {
// Update months
self.months(ko.utils.arrayMap(data, ko.mapping.fromJS));
// Reset selected month to the new instance corresponding to the old one
if(self.month()) {
var oldYear = self.month().year();
var oldMonth = self.month().month();
// Reset to null
self.month(null);
// Find the new instance of the previously selected month.
$.each(self.months(), function(index, month) {
if(month.year() == oldYear && month.month() == oldMonth) {
self.month(month);
}
});
}
// Set selected month to the last one if not yet selected.
if(!self.month()) {
self.month(self.months()[self.months().length - 1]);
}
// Load entries
self.loadEntries(self.account(), self.month());
2013-01-07 18:42:02 +01:00
});
};
2013-01-13 13:32:23 +01:00
// Function to select template in function of selected item.
2013-01-07 18:42:02 +01:00
self.templateToUse = function (item) {
return self.selectedItem() === item ? 'editTmpl' : 'itemsTmpl';
};
2013-01-13 13:32:23 +01:00
// Function to edit an item
2013-01-07 18:42:02 +01:00
self.edit = function(item) {
2013-01-13 13:32:23 +01:00
// Cancel previous editing.
if(self.savedItem) {
2013-01-07 18:42:02 +01:00
self.cancel();
}
2013-01-13 13:32:23 +01:00
// Save current item
self.savedItem=ko.toJS(item);
2013-01-07 18:42:02 +01:00
self.selectedItem(item);
2013-01-13 13:32:23 +01:00
// Initialize date picker for value date column.
$("#value_date").datepicker().on('changeDate', function(ev){
self.selectedItem().value_date(ev.date.format(ev.currentTarget.dataset.dateFormat));
2013-01-07 18:42:02 +01:00
});
2013-01-13 13:32:23 +01:00
// Initialize date picker for operation date column.
$("#operation_date").datepicker().on('changeDate', function(ev){
self.selectedItem().operation_date(ev.date.format(ev.currentTarget.dataset.dateFormat));
});
2013-01-07 18:42:02 +01:00
};
2013-01-13 13:32:23 +01:00
// Function to cancel current editing.
2013-01-07 18:42:02 +01:00
self.cancel = function() {
2013-01-13 13:32:23 +01:00
// Reset selected item fields to saved item ones.
if(self.selectedItem() && self.savedItem) {
self.selectedItem().id(self.savedItem.id); // id should not change, but just in case...
self.selectedItem().operation_date(self.savedItem.operation_date);
self.selectedItem().value_date(self.savedItem.value_date);
self.selectedItem().label(self.savedItem.label);
self.selectedItem().value(self.savedItem.value);
self.selectedItem().account_id(self.savedItem.account_id); // account_id should not change, but just in case...
2013-01-07 18:42:02 +01:00
}
2013-01-13 13:32:23 +01:00
// This item was just added: remove it from the entries array.
2013-01-07 18:42:02 +01:00
if(self.selectedItem() && !self.selectedItem().id()) {
self.entries.remove(self.selectedItem());
}
2013-01-13 13:32:23 +01:00
// Reset saved and selected items to null.
self.savedItem = null;
2013-01-07 18:42:02 +01:00
self.selectedItem(null);
};
2013-01-13 13:32:23 +01:00
// Function to add a new entry.
2013-01-07 18:42:02 +01:00
self.add = function() {
2013-01-13 13:32:23 +01:00
self.entries.unshift(ko.mapping.fromJS({
id: null,
value_date: null,
operation_date: null,
label: null,
value: null,
sold: null,
pointedsold: null,
category: null,
account_id: self.account().id()
}));
self.edit(self.entries()[0]);
2013-01-07 18:42:02 +01:00
};
2013-01-13 13:32:23 +01:00
// Function to save the current selected entry.
2013-01-07 18:42:02 +01:00
self.save = function() {
2013-01-13 13:32:23 +01:00
// Transform selected entry to a javascript object.
var item = ko.toJS(self.selectedItem());
2013-01-07 18:42:02 +01:00
2013-01-13 13:32:23 +01:00
// Ajax call to save the entry.
2013-01-07 18:42:02 +01:00
$.post("api/entry.php", {action: "save_entry", entry:item}).success(function(data) {
message("success", "Save", data.message);
self.selectedItem(null);
2013-01-13 13:32:23 +01:00
self.savedItem = null;
// Reload accounts to update solds.
self.loadAccounts();
2013-01-07 18:42:02 +01:00
});
};
2013-01-13 13:32:23 +01:00
// Function to remove an entry.
2013-01-07 18:42:02 +01:00
self.remove = function (item) {
2013-01-13 13:32:23 +01:00
// Cancel current editing.
self.cancel();
2013-01-07 18:42:02 +01:00
if (item.id()) {
2013-01-13 13:32:23 +01:00
// This entry is saved in database, we show a modal dialog to confirm the removal.
self.removedItem = item;
$('#remove-confirm').modal();
2013-01-07 18:42:02 +01:00
} else {
2013-01-13 13:32:23 +01:00
// This entry was not saved in database yet, we just remove it from the list.
2013-01-07 18:42:02 +01:00
self.entries.remove(item);
}
};
2013-01-13 13:32:23 +01:00
// Function to confirm the removal of an entry.
self.confirmRemove = function() {
2013-01-13 13:32:23 +01:00
var item = self.removedItem;
$.post("api/entry.php", {action: "remove_entry", entry:item}).success(function (result) {
2013-01-13 13:32:23 +01:00
// Reload accounts to update solds.
self.loadAccounts();
}).complete(function (result) {
2013-01-13 13:32:23 +01:00
// Reset removed item to null and hide the modal dialog.
self.removedItem = null;
$('#remove-confirm').modal('hide');
});
};
2013-01-13 13:32:23 +01:00
// Callback function to select a new month.
self.selectMonth = function(month) {
if(month) {
self.month(month);
self.loadEntries(self.account(), month);
}
2013-01-08 18:50:47 +01:00
};
2013-01-13 13:32:23 +01:00
// Callback function to select a new account.
self.selectAccount = function(account) {
if(account) {
self.account(account);
self.loadMonths(account);
}
2013-01-07 18:42:02 +01:00
};
};
drawChart = function(entries, element) {
// clear previous chart
$(element).html("");
if(entries && entries.length > 0) {
var chartValues = [[], []];
chartValues[0] = entries;
var today = new Date();
today.setHours(0);
today.setMinutes(0);
2013-01-13 12:24:33 +01:00
var day = 24 * 60 * 60 * 1000;
var firstDate = new Date(Date.parse(entries[0][0]).valueOf() - day).format('yyyy-mm-dd');
var lastDate = new Date(Date.parse(entries[entries.length -1][0]).valueOf() + day).format('yyyy-mm-dd');
// plot chart
window.chart = $.jqplot(element.id, chartValues, {
title: "&Eacute;volution du solde",
axes:{
xaxis:{
2013-01-13 12:24:33 +01:00
autoscale: true,
renderer:$.jqplot.DateAxisRenderer,
2013-01-13 12:24:33 +01:00
min: firstDate,
max: lastDate,
tickOptions: {formatString: "%F"}
},
yaxis: {
autoscale: true,
}
},
highlighter: {
show:true,
yvalues: 4,
formatString:'<table class="jqplot-highlighter"><tr><td>date:</td><td>%s</td></tr><tr><td>open:</td><td>%s</td></tr><tr><td>hi:</td><td>%s</td></tr><tr><td>low:</td><td>%s</td></tr><tr><td>close:</td><td>%s</td></tr></table>'
},
series: [{
renderer:$.jqplot.OHLCRenderer,
color: "blue",
lineWidth: 3,
rendererOptions:{}
}],
canvasOverlay: {
show: true,
objects: [{
dashedHorizontalLine: {
name: "zero",
y: 0,
lineWidth: 1,
color: "red",
shadow: false
}},
{ dashedVerticalLine: {
name: "today",
x: today,
lineWidth: 1,
color: "gray",
shadow: false
}}]
}
});
2013-01-12 22:14:42 +01:00
} else {
window.chart = null;
}
};
drawPieChart = function(entries, element) {
// clear previous chart
$(element).html("");
if(entries && entries.length > 0) {
var chartValues = [[]];
chartValues[0] = entries;
// plot chart
window.pieChart = $.jqplot(element.id, chartValues, {
title: "D&eacute;penses",
seriesDefaults: {
renderer: $.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true
}
},
legend: {
show: true,
location: 'e'
},
highlighter: {
show: true,
formatString:'%s: %s',
tooltipLocation:'sw',
useAxesFormatters:false
}
});
2013-01-12 22:14:42 +01:00
} else {
window.pieChart = null;
}
};
ko.bindingHandlers.chart = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
// empty - left as placeholder if needed later
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var unwrap = ko.utils.unwrapObservable;
var dataSource = valueAccessor();
//var entries = dataSource ? unwrap(dataSource) : null;
var entries = dataSource ? unwrap(dataSource) : null;
drawChart(entries, element);
}
};
2013-01-07 18:42:02 +01:00
ko.bindingHandlers.pieChart = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
// empty - left as placeholder if needed later
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var unwrap = ko.utils.unwrapObservable;
var dataSource = valueAccessor();
//var entries = dataSource ? unwrap(dataSource) : null;
var entries = dataSource ? unwrap(dataSource) : null;
drawPieChart(entries, element);
}
};
$(document).ajaxError(function(event, xhr, settings) {
message("error", "Error.", xhr.statusText);
});
$(window).resize(function() {
if(window.chart) {
window.chart.replot({resetAxes: true});
}
2013-01-12 22:16:05 +01:00
if(window.pieChart) {
window.pieChart.replot({resetAxes: true});
}
});
var viewModel = new ListViewModel();
ko.applyBindings(viewModel);
$(viewModel.loadAccounts);
2013-01-07 18:42:02 +01:00