Expand autocomplete and remove old code #3150

This commit is contained in:
James Cole
2020-07-23 06:58:00 +02:00
parent 162e791dfd
commit b63e8d60bb
23 changed files with 188 additions and 1131 deletions

View File

@@ -74,7 +74,7 @@ function initExpenseACField(fieldName) {
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'json/expense-accounts?uid=' + uid,
url: 'api/v1/autocomplete/accounts?types=Expense account&uid=' + uid,
filter: function (list) {
return $.map(list, function (name) {
return {name: name};
@@ -82,7 +82,7 @@ function initExpenseACField(fieldName) {
}
},
remote: {
url: 'json/expense-accounts?search=%QUERY&uid=' + uid,
url: 'api/v1/autocomplete/accounts?types=Expense account&query=%QUERY&uid=' + uid,
wildcard: '%QUERY',
filter: function (list) {
return $.map(list, function (name) {
@@ -113,7 +113,7 @@ function initRevenueACField(fieldName) {
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'json/revenue-accounts?uid=' + uid,
url: 'api/v1/autocomplete/accounts?types=Revenue account&uid=' + uid,
filter: function (list) {
return $.map(list, function (name) {
return {name: name};
@@ -121,7 +121,7 @@ function initRevenueACField(fieldName) {
}
},
remote: {
url: 'json/revenue-accounts?search=%QUERY&uid=' + uid,
url: 'api/v1/autocomplete/accounts?types=Revenue account&query=%QUERY&uid=' + uid,
wildcard: '%QUERY',
filter: function (list) {
return $.map(list, function (name) {

View File

@@ -249,7 +249,7 @@ function updateActionInput(selectList) {
break;
case 'set_description':
console.log('Select list value is ' + selectList.val() + ', so input needs auto complete.');
createAutoComplete(inputResult, 'json/transaction-journals/all');
createAutoComplete(inputResult, 'api/v1/autocomplete/transactions');
break;
case 'set_source_account':
console.log('Select list value is ' + selectList.val() + ', so input needs auto complete.');
@@ -277,7 +277,7 @@ function updateActionInput(selectList) {
break;
case 'update_piggy':
console.log('Select list value is ' + selectList.val() + ', so input needs auto complete.');
createAutoComplete(inputResult, 'json/piggy-banks');
createAutoComplete(inputResult, 'api/v1/autocomplete/piggy-banks');
break;
default:
console.log('Select list value is ' + selectList.val() + ', destroy auto complete, do nothing else.');
@@ -328,14 +328,14 @@ function updateTriggerInput(selectList) {
break;
case 'transaction_type':
console.log('Select list value is ' + selectList.val() + ', so input needs auto complete.');
createAutoComplete(inputResult, 'json/transaction-types');
createAutoComplete(inputResult, 'api/v1/autocomplete/transaction-types');
break;
case 'description_starts':
case 'description_ends':
case 'description_contains':
case 'description_is':
console.log('Select list value is ' + selectList.val() + ', so input needs auto complete.');
createAutoComplete(inputResult, 'json/transaction-journals/all');
createAutoComplete(inputResult, 'api/v1/autocomplete/transactions');
break;
case 'has_no_category':
case 'has_any_category':
@@ -352,7 +352,7 @@ function updateTriggerInput(selectList) {
case 'currency_is':
case 'foreign_currency_is':
console.log('Select list value is ' + selectList.val() + ', so input needs auto complete.');
createAutoComplete(inputResult, 'json/currency-names');
createAutoComplete(inputResult, 'api/v1/autocomplete/currencies-with-code');
break;
case 'amount_less':
case 'amount_more':

View File

@@ -39,7 +39,7 @@ function makeRevenueAC() {
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'json/revenue-accounts?uid=' + uid,
url: 'api/v1/autocomplete/accounts?types=Revenue account?uid=' + uid,
filter: function (list) {
return $.map(list, function (object) {
return {name: object.name};
@@ -47,7 +47,7 @@ function makeRevenueAC() {
}
},
remote: {
url: 'json/revenue-accounts?search=%QUERY&uid=' + uid,
url: 'api/v1/autocomplete/accounts?types=Revenue account&query=%QUERY&uid=' + uid,
wildcard: '%QUERY',
filter: function (list) {
return $.map(list, function (object) {

View File

@@ -1,225 +0,0 @@
/*
* create.js
* Copyright (c) 2019 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program 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.
*
* This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** global: autoCompleteUri */
$(function () {
"use strict";
initPage();
});
function initPage() {
// recreate buttons and auto-complete things
autoComplete();
makeButtons();
runModernizer();
}
/**
* Reset all click triggers.
*/
function makeButtons() {
$('.clearDestination').unbind('click').on('click', clearDestination);
$('.clearSource').unbind('click').on('click', clearSource);
$('#addSplitButton').unbind('click').on('click', addSplit);
}
function addSplit() {
// clone the latest
var latest =$($('#transactions').children()[$('#transactions').children().length - 1]);
latest.clone(true).appendTo('#transactions');
initPage();
return false;
}
/**
* Code to handle clearing the source account.
* @param e
*/
function clearSource(e) {
console.log('Now clearing source.');
var button = $(e.currentTarget);
// empty value.
$(button.parent().parent().find('input').get(0)).val('');
// reset source account
setSourceAccount(null);
}
/**
* Code to handle clearing the destination account.
* @param e
*/
function clearDestination(e) {
console.log('Now clearing destination.');
var button = $(e.currentTarget);
// empty value.
$(button.parent().parent().find('input').get(0)).val('');
// reset destination account
setDestinationAccount(null);
}
/**
* Set the new source account (from a suggestion).
*
* @param newAccount
*/
function setSourceAccount(newAccount) {
if (null === newAccount) {
console.log('New source account is now null.');
sourceAccount = null;
setAllowedDestinationAccounts(newAccount);
return;
}
console.log('The new source account is now ' + newAccount.value + 'of type ' + newAccount.data.type);
setAllowedDestinationAccounts(newAccount);
sourceAccount = newAccount;
setTransactionType();
}
/**
* Set the new destination account (from a suggestion).
*
* @param newAccount
*/
function setDestinationAccount(newAccount) {
if (null === newAccount) {
console.log('New destination account is now null.');
destinationAccount = null;
setAllowedSourceAccounts(newAccount);
return;
}
console.log('The new destination account is now ' + newAccount.value + 'of type ' + newAccount.data.type);
setAllowedSourceAccounts(newAccount);
sourceAccount = newAccount;
setTransactionType();
}
/**
* Set a new limit on the allowed destination account.
*
* @param newAccount
*/
function setAllowedDestinationAccounts(newAccount) {
if (null === newAccount) {
console.log('Allowed type for destination account is anything.');
destAllowedAccountTypes = [];
return;
}
destAllowedAccountTypes = allowedOpposingTypes.source[newAccount.data.type];
console.log('The destination account must be of type: ', destAllowedAccountTypes);
// todo if the current destination account is not of this type, reset it.
}
/**
* Set a new limit on the allowed destination account.
*
* @param newAccount
*/
function setAllowedSourceAccounts(newAccount) {
if (null === newAccount) {
console.log('Allowed type for source account is anything.');
sourceAllowedAccountTypes = [];
return;
}
sourceAllowedAccountTypes = allowedOpposingTypes.source[newAccount.data.type];
console.log('The source account must be of type: ', sourceAllowedAccountTypes);
// todo if the current destination account is not of this type, reset it.
}
/**
* Create auto complete.
*/
function autoComplete() {
var options = {
serviceUrl: getSourceAutoCompleteURI,
groupBy: 'type',
onSelect: function (suggestion) {
setSourceAccount(suggestion);
}
};
$('.sourceAccountAC').autocomplete(options);
// also select destination account.
var destinationOptions = {
serviceUrl: getDestinationAutoCompleteURI,
groupBy: 'type',
onSelect: function (suggestion) {
setDestinationAccount(suggestion);
}
};
$('.destinationAccountAC').autocomplete(destinationOptions);
}
function setTransactionType() {
if (sourceAccount === undefined || destinationAccount === undefined || sourceAccount === null || destinationAccount === null) {
$('.transactionTypeIndicator').text('');
$('.transactionTypeIndicatorBlock').hide();
console.warn('Not both accounts are known yet.');
return;
}
$('.transactionTypeIndicatorBlock').show();
var expectedType = accountToTypes[sourceAccount.data.type][destinationAccount.data.type];
$('.transactionTypeIndicator').html(creatingTypes[expectedType]);
console.log('Expected transaction type is ' + expectedType);
}
/**
* Returns the auto complete URI for source accounts.
* @returns {string}
*/
function getSourceAutoCompleteURI() {
console.log('Will filter source accounts', sourceAllowedAccountTypes);
return accountAutoCompleteURI + '?types=' + encodeURI(sourceAllowedAccountTypes.join(','));
}
/**
* Returns the auto complete URI for destination accounts.
* @returns {string}
*/
function getDestinationAutoCompleteURI() {
console.log('Will filter destination accounts', destAllowedAccountTypes);
return accountAutoCompleteURI + '?types=' + encodeURI(destAllowedAccountTypes.join(','));
}
/**
* Give date a datepicker if not natively supported.
*/
function runModernizer() {
if (!Modernizr.inputtypes.date) {
$('input[type="date"]').datepicker(
{
dateFormat: 'yy-mm-dd'
}
);
}
}

View File

@@ -28,7 +28,7 @@ $(document).ready(function () {
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'json/transaction-journals/all?uid=' + uid,
url: 'api/v1/autocomplete/transactions?uid=' + uid,
filter: function (list) {
return $.map(list, function (obj) {
return obj;
@@ -36,7 +36,7 @@ $(document).ready(function () {
}
},
remote: {
url: 'json/transaction-journals/all?search=%QUERY&uid=' + uid,
url: 'api/v1/autocomplete/transactions?query=%QUERY&uid=' + uid,
wildcard: '%QUERY',
filter: function (list) {
return $.map(list, function (obj) {
@@ -55,7 +55,7 @@ $(document).ready(function () {
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'json/expense-accounts?uid=' + uid,
url: 'api/v1/autocomplete/accounts?types=Expense account?uid=' + uid,
filter: function (list) {
return $.map(list, function (obj) {
return obj;
@@ -63,7 +63,7 @@ $(document).ready(function () {
}
},
remote: {
url: 'json/expense-accounts?search=%QUERY&uid=' + uid,
url: 'api/v1/autocomplete/accounts?types=Expense account?query=%QUERY&uid=' + uid,
wildcard: '%QUERY',
filter: function (list) {
return $.map(list, function (obj) {
@@ -83,7 +83,7 @@ $(document).ready(function () {
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'json/revenue-accounts?uid=' + uid,
url: 'api/v1/autocomplete/accounts?types=Revenue account?uid=' + uid,
filter: function (list) {
return $.map(list, function (obj) {
return obj;
@@ -91,7 +91,7 @@ $(document).ready(function () {
}
},
remote: {
url: 'json/revenue-accounts?search=%QUERY&uid=' + uid,
url: 'api/v1/autocomplete/accounts?types=Revenue account?query=%QUERY&uid=' + uid,
wildcard: '%QUERY',
filter: function (list) {
return $.map(list, function (obj) {

View File

@@ -1 +0,0 @@
Options -Indexes

View File

@@ -1,227 +0,0 @@
/*
* common.js
* Copyright (c) 2019 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program 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.
*
* This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** global: Modernizr, accountInfo, currencyInfo, accountInfo, transferInstructions, what */
var countConversions = 0;
$(document).ready(function () {
"use strict";
console.log('in common.js document.ready');
setCommonAutocomplete();
runModernizer();
});
/**
* Give date a datepicker if not natively supported.
*/
function runModernizer() {
if (!Modernizr.inputtypes.date) {
$('input[type="date"]').datepicker(
{
dateFormat: 'yy-mm-dd'
}
);
}
}
/**
* Auto complete things in both edit and create routines:
*/
function setCommonAutocomplete() {
console.log('In setCommonAutoComplete()');
// do destination name (expense accounts):
initExpenseAC();
// do source name (revenue accounts):
initRevenueAC();
// do categories auto complete:
initCategoryAC();
// do tags auto complete:
initTagsAC();
}
/**
* When the user changes the currency in the amount drop down, it may jump from being
* the native currency to a foreign currency. Thi s triggers the display of several
* information things that make sure that the user always supplies the amount in the native currency.
*
* @returns {boolean}
*/
function selectsForeignCurrency() {
console.log('In selectsForeignCurrency()');
var foreignCurrencyId = parseInt($('input[name="amount_currency_id_amount"]').val());
console.log('Foreign currency ID is ' + foreignCurrencyId);
var selectedAccountId = getAccountId();
var nativeCurrencyId = parseInt(accountInfo[selectedAccountId].preferredCurrency);
console.log('Native currency ID is ' + nativeCurrencyId);
if (foreignCurrencyId !== nativeCurrencyId) {
console.log('These are not the same.');
// the input where the native amount is entered gets the symbol for the native currency:
$('.non-selectable-currency-symbol').text(currencyInfo[nativeCurrencyId].symbol);
// the instructions get updated:
$('#ffInput_exchange_rate_instruction').text(getExchangeInstructions());
// both holders are shown to the user:
$('#exchange_rate_instruction_holder').show();
if (what !== 'transfer') {
console.log('Show native amount holder.');
$('#native_amount_holder').show();
}
// if possible the amount is already exchanged for the foreign currency
convertForeignToNative();
}
if (foreignCurrencyId === nativeCurrencyId) {
console.log('These are the same.');
$('#exchange_rate_instruction_holder').hide();
console.log('Hide native amount holder (a)');
$('#native_amount_holder').hide();
// make all other inputs empty
//console.log('Make destination_amount empty!');
//$('input[name="destination_amount"]').val("");
$('input[name="native_amount"]').val("");
}
return false;
}
/**
* Converts any foreign amount to the native currency.
*/
function convertForeignToNative() {
var accountId = getAccountId();
var foreignCurrencyId = parseInt($('input[name="amount_currency_id_amount"]').val());
var nativeCurrencyId = parseInt(accountInfo[accountId].preferredCurrency);
var foreignCurrencyCode = currencyInfo[foreignCurrencyId].code;
var nativeCurrencyCode = currencyInfo[nativeCurrencyId].code;
var date = $('#ffInput_date').val();
var amount = $('#ffInput_amount').val();
var uri = 'json/rate/' + foreignCurrencyCode + '/' + nativeCurrencyCode + '/' + date + '?amount=' + amount;
$.get(uri).done(updateNativeAmount);
}
/**
* Once the data has been grabbed will update the field in the form.
* @param data
*/
function updateNativeAmount(data) {
// if native amount is already filled in, even though we do this for the first time:
// don't overrule it.
if (countConversions === 0 && $('#ffInput_native_amount').val().length > 0) {
countConversions++;
return;
}
console.log('Returned amount is: ' + data.amount);
if (data.amount !== 0) {
$('#ffInput_native_amount').val(data.amount);
}
}
/**
* Instructions for transfers
*/
function getTransferExchangeInstructions() {
var sourceAccount = $('select[name="source_id"]').val();
var destAccount = $('select[name="destination_id"]').val();
var sourceCurrency = accountInfo[sourceAccount].preferredCurrency;
var destinationCurrency = accountInfo[destAccount].preferredCurrency;
return transferInstructions.replace('@source_name', accountInfo[sourceAccount].name)
.replace('@dest_name', accountInfo[destAccount].name)
.replace(/@source_currency/g, currencyInfo[sourceCurrency].name)
.replace(/@dest_currency/g, currencyInfo[destinationCurrency].name);
}
/**
* When the transaction to create is a transfer some more checks are necessary.
*/
function validateCurrencyForTransfer() {
console.log('in validateCurrencyForTransfer()');
if (what !== "transfer") {
console.log('is not a transfer, so return.');
return;
}
$('#source_amount_holder').show();
var sourceAccount = $('select[name="source_id"]').val();
var destAccount = $('select[name="destination_id"]').val();
var sourceCurrency = accountInfo[sourceAccount].preferredCurrency;
var sourceSymbol = currencyInfo[sourceCurrency].symbol;
var destinationCurrency = accountInfo[destAccount].preferredCurrency;
var destinationSymbol = currencyInfo[destinationCurrency].symbol;
$('#source_amount_holder').show().find('.non-selectable-currency-symbol').text(sourceSymbol);
if (sourceCurrency === destinationCurrency) {
$('#destination_amount_holder').hide();
$('#amount_holder').hide();
return;
}
$('#ffInput_exchange_rate_instruction').text(getTransferExchangeInstructions());
$('#exchange_rate_instruction_holder').show();
$('input[name="source_amount"]').val($('input[name="amount"]').val());
convertSourceToDestination();
$('#destination_amount_holder').show().find('.non-selectable-currency-symbol').text(destinationSymbol);
$('#amount_holder').hide();
}
/**
* Convert from source amount currency to destination currency for transfers.
*
*/
function convertSourceToDestination() {
var sourceAccount = $('select[name="source_id"]').val();
var destAccount = $('select[name="destination_id"]').val();
var sourceCurrency = accountInfo[sourceAccount].preferredCurrency;
var destinationCurrency = accountInfo[destAccount].preferredCurrency;
var sourceCurrencyCode = currencyInfo[sourceCurrency].code;
var destinationCurrencyCode = currencyInfo[destinationCurrency].code;
var date = $('#ffInput_date').val();
var amount = $('#ffInput_source_amount').val();
$('#ffInput_amount').val(amount);
var uri = 'json/rate/' + sourceCurrencyCode + '/' + destinationCurrencyCode + '/' + date + '?amount=' + amount;
$.get(uri).done(updateDestinationAmount);
}
/**
* Once the data has been grabbed will update the field (for transfers)
* @param data
*/
function updateDestinationAmount(data) {
console.log('Returned amount is: ' + data.amount);
if (data.amount !== 0) {
$('#ffInput_destination_amount').val(data.amount);
}
}

View File

@@ -1,327 +0,0 @@
/*
* create.js
* Copyright (c) 2019 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program 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.
*
* This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** global: currencyInfo, overruleCurrency,useAccountCurrency, accountInfo, what,Modernizr, title, breadcrumbs, middleCrumbName, button, piggiesLength, txt, middleCrumbUrl,exchangeRateInstructions, convertForeignToNative, convertSourceToDestination, selectsForeignCurrency, accountInfo */
$(document).ready(function () {
"use strict";
// hide ALL exchange things and AMOUNT fields
$('#exchange_rate_instruction_holder').hide();
$('#native_amount_holder').hide();
$('#amount_holder').hide();
$('#source_amount_holder').hide();
$('#destination_amount_holder').hide();
// respond to switch buttons (first time always triggers)
updateButtons();
updateForm();
updateLayout();
updateDescription();
// when user changes source account or destination, native currency may be different.
$('select[name="source_id"]').on('change', function () {
selectsDifferentSource();
// do something for transfers:
validateCurrencyForTransfer();
});
$('select[name="destination_id"]').on('change', function () {
selectsDifferentDestination();
// do something for transfers:
validateCurrencyForTransfer();
});
// convert foreign currency to native currency (when input changes, exchange rate)
$('#ffInput_amount').on('change', convertForeignToNative);
// convert source currency to destination currency (slightly different routine for transfers)
$('#ffInput_source_amount').on('change', convertSourceToDestination);
// when user selects different currency,
$('.currency-option').on('click', selectsForeignCurrency);
// overrule click on currency:
if (useAccountCurrency === false) {
$('.currency-option[data-id="' + overruleCurrency + '"]').click();
$('[data-toggle="dropdown"]').parent().removeClass('open');
}
$('#ffInput_description').focus();
});
/**
* The user selects a different source account. Applies to withdrawals
* and transfers.
*/
function selectsDifferentSource() {
console.log('Now in selectsDifferentSource()');
if (what === "deposit") {
console.log('User is making a deposit. Don\'t bother with source.');
$('input[name="source_account_currency"]').val("0");
return;
}
// store original currency ID of the selected account in a separate var:
var sourceId = $('select[name="source_id"]').val();
var sourceCurrency = accountInfo[sourceId].preferredCurrency;
$('input[name="source_account_currency"]').val(sourceCurrency);
console.log('selectsDifferenctSource(): Set source account currency to ' + sourceCurrency);
// change input thing:
console.log('Emulate click on .currency-option[data-id="' + sourceCurrency + '"]');
$('.currency-option[data-id="' + sourceCurrency + '"]').click();
$('[data-toggle="dropdown"]').parent().removeClass('open');
$('select[name="source_id"]').focus();
}
/**
* The user selects a different source account. Applies to withdrawals
* and transfers.
*/
function selectsDifferentDestination() {
if (what === "withdrawal") {
console.log('User is making a withdrawal. Don\'t bother with destination.');
$('input[name="destination_account_currency"]').val("0");
return;
}
// store original currency ID of the selected account in a separate var:
var destinationId = $('select[name="destination_id"]').val();
var destinationCurrency = accountInfo[destinationId].preferredCurrency;
$('input[name="destination_account_currency"]').val(destinationCurrency);
console.log('selectsDifferentDestination(): Set destinationId account currency to ' + destinationCurrency);
// change input thing:
$('.currency-option[data-id="' + destinationCurrency + '"]').click();
$('[data-toggle="dropdown"]').parent().removeClass('open');
$('select[name="destination_id"]').focus();
}
/**
* This function generates a small helper text to explain the user
* that they have selected a foreign currency.
* @returns {XML|string|void}
*/
function getExchangeInstructions() {
var foreignCurrencyId = parseInt($('input[name="amount_currency_id_amount"]').val());
var selectedAccountId = getAccountId();
var nativeCurrencyId = parseInt(accountInfo[selectedAccountId].preferredCurrency);
var text = exchangeRateInstructions.replace('@name', accountInfo[selectedAccountId].name);
text = text.replace(/@native_currency/g, currencyInfo[nativeCurrencyId].name);
text = text.replace(/@foreign_currency/g, currencyInfo[foreignCurrencyId].name);
return text;
}
/**
*
*/
function updateDescription() {
// do description auto complete:
var journalNames = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'json/transaction-journals/' + what + '?uid=' + uid,
filter: function (list) {
return $.map(list, function (name) {
return {name: name};
});
}
},
remote: {
url: 'json/transaction-journals/' + what + '?search=%QUERY&uid=' + uid,
wildcard: '%QUERY',
filter: function (list) {
return $.map(list, function (name) {
return {name: name};
});
}
}
});
journalNames.initialize();
$('input[name="description"]').typeahead('destroy').typeahead({hint: true, highlight: true,}, {source: journalNames, displayKey: 'name', autoSelect: false});
$('#ffInput_description').focus();
}
/**
*
*/
function updateLayout() {
"use strict";
$('#subTitle').text(title[what]);
$('.breadcrumb .active').text(breadcrumbs[what]);
$('.breadcrumb li:nth-child(2)').html('<a href="' + middleCrumbUrl[what] + '">' + middleCrumbName[what] + '</a>');
$('.transaction-btn').text(button[what]);
}
/**
*
*/
function updateForm() {
"use strict";
console.log('Now in updateForm()');
$('input[name="what"]').val(what);
var destName = $('#ffInput_destination_name');
var srcName = $('#ffInput_source_name');
switch (what) {
case 'withdrawal':
// show source_id and dest_name
document.getElementById('source_id_holder').style.display = 'block';
document.getElementById('destination_name_holder').style.display = 'block';
// hide others:
document.getElementById('source_name_holder').style.display = 'none';
document.getElementById('destination_id_holder').style.display = 'none';
document.getElementById('budget_id_holder').style.display = 'block';
// hide piggy bank:
document.getElementById('piggy_bank_id_holder').style.display = 'none';
// copy destination account name to source account name:
if (destName.val().length > 0) {
srcName.val(destName.val());
}
// exchange / foreign currencies:
// hide explanation, hide source and destination amounts, show normal amount
document.getElementById('exchange_rate_instruction_holder').style.display = 'none';
document.getElementById('source_amount_holder').style.display = 'none';
document.getElementById('destination_amount_holder').style.display = 'none';
document.getElementById('amount_holder').style.display = 'block';
break;
case 'deposit':
// show source_name and dest_id:
document.getElementById('source_name_holder').style.display = 'block';
document.getElementById('destination_id_holder').style.display = 'block';
// hide others:
document.getElementById('source_id_holder').style.display = 'none';
document.getElementById('destination_name_holder').style.display = 'none';
// hide budget
document.getElementById('budget_id_holder').style.display = 'none';
// hide piggy bank
document.getElementById('piggy_bank_id_holder').style.display = 'none';
// copy name
if (srcName.val().length > 0) {
destName.val(srcName.val());
}
// exchange / foreign currencies:
// hide explanation, hide source and destination amounts, show amount
document.getElementById('exchange_rate_instruction_holder').style.display = 'none';
document.getElementById('source_amount_holder').style.display = 'none';
document.getElementById('destination_amount_holder').style.display = 'none';
document.getElementById('amount_holder').style.display = 'block';
break;
case 'transfer':
// show source_id and dest_id:
document.getElementById('source_id_holder').style.display = 'block';
document.getElementById('destination_id_holder').style.display = 'block';
// hide others:
document.getElementById('source_name_holder').style.display = 'none';
document.getElementById('destination_name_holder').style.display = 'none';
// hide budget
document.getElementById('budget_id_holder').style.display = 'none';
// optional piggies
var showPiggies = 'block';
if ($('#ffInput_piggy_bank_id option').length === 0) {
showPiggies = 'none';
}
document.getElementById('piggy_bank_id_holder').style.display = showPiggies;
break;
default:
break;
}
// get instructions all the time.
console.log('End of update form');
selectsDifferentSource();
selectsDifferentDestination();
selectsForeignCurrency();
// do something for transfers:
validateCurrencyForTransfer();
}
/**
*
*/
function updateButtons() {
"use strict";
$('.switch').each(function (i, v) {
var button = $(v);
// remove click event:
button.unbind('click');
// new click event:
button.bind('click', clickButton);
if (button.data('what') === what) {
button.removeClass('btn-default').addClass('btn-info').html('<i class="fa fa-fw fa-check"></i> ' + txt[button.data('what')]);
} else {
button.removeClass('btn-info').addClass('btn-default').text(txt[button.data('what')]);
}
});
}
/**
*
* @param e
* @returns {boolean}
*/
function clickButton(e) {
"use strict";
var button = $(e.target);
var newWhat = button.data('what');
if (newWhat !== what) {
what = newWhat;
updateButtons();
updateForm();
updateLayout();
updateDescription();
}
return false;
}
/**
* Get accountID based on some meta info.
*/
function getAccountId() {
if (what === "withdrawal") {
return $('select[name="source_id"]').val();
}
if (what === "deposit" || what === "transfer") {
return $('select[name="destination_id"]').val();
}
return undefined;
}

View File

@@ -1,241 +0,0 @@
/*
* edit.js
* Copyright (c) 2019 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program 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.
*
* This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** global: what, Modernizr, selectsForeignCurrency, accountInfo, convertForeignToNative, validateCurrencyForTransfer, convertSourceToDestination, journalData, journal, accountInfo, exchangeRateInstructions, currencyInfo */
$(document).ready(function () {
"use strict";
console.log('in edit.js document.ready');
setAutocompletes();
updateInitialPage();
// update the two source account currency ID fields (initial value):
initCurrencyIdValues();
// respond to user input:
$('.currency-option').on('click', function () {
// to display instructions and stuff like that.
selectsForeignCurrency();
});
$('#ffInput_amount').on('change', convertForeignToNative);
// respond to account changes:
$('#ffInput_source_id').on('change', function (e) {
console.log('Event: #ffInput_source_id::change');
validateCurrencyForTransfer();
// update the two source account currency ID fields (initial value):
initCurrencyIdValues();
// call to selectsForeignCurrency
console.log('Extra call to selectsForeignCurrency()');
selectsForeignCurrency();
// update "source_account_currency".
updateSourceAccountCurrency();
});
$('#ffInput_destination_id').on('change', function () {
console.log('Event: #ffInput_destination_id::change');
validateCurrencyForTransfer();
// update the two source account currency ID fields (initial value):
initCurrencyIdValues();
// call to selectsForeignCurrency
console.log('Extra call to selectsForeignCurrency()');
selectsForeignCurrency();
// update "destination_account_currency".
updateDestinationAccountCurrency();
});
// convert source currency to destination currency (slightly different routine for transfers)
$('#ffInput_source_amount').on('change', convertSourceToDestination);
//
});
/**
* Updates the currency ID of the hidden source account field
* to match the selected account.
*/
function updateSourceAccountCurrency() {
var accountId = $('#ffInput_source_id').val();
var currency = parseInt(accountInfo[accountId].preferredCurrency);
console.log('Now in updateSourceAccountCurrency() for account #' + accountId);
console.log('Preferred currency for this account is #' + currency);
$('input[name="source_account_currency"]').val(currency);
}
/**
* Updates the currency ID of the hidden destination account field
* to match the selected account.
*/
function updateDestinationAccountCurrency() {
var accountId = $('#ffInput_destination_id').val();
var currency = parseInt(accountInfo[accountId].preferredCurrency);
console.log('Now in updateDestinationAccountCurrency() for account #' + accountId);
console.log('Preferred currency for this account is #' + currency);
$('input[name="destination_account_currency"]').val(currency);
}
/**
* Fills two hidden variables with the correct currency ID.
*/
function initCurrencyIdValues() {
console.log('in initCurrencyIdValues()');
var currencyId;
if (journal.transaction_type.type === "Withdrawal") {
// update source from page load info:
currencyId = journalData.native_currency.id;
console.log('initCurrencyIdValues() withdrawal: Set source account currency to ' + currencyId);
$('input[name="source_account_currency"]').val(currencyId);
return;
}
if (journal.transaction_type.type === "Deposit") {
// update destination from page load info:
currencyId = $('input[name="amount_currency_id_amount"]').val();
console.log('Set destination account currency to ' + currencyId);
$('input[name="destination_account_currency"]').val(currencyId);
return;
}
var sourceAccount = $('select[name="source_id"]').val();
console.log('Source account is ' + sourceAccount);
var destAccount = $('select[name="destination_id"]').val();
console.log('Destination account is ' + destAccount);
var sourceCurrency = parseInt(accountInfo[sourceAccount].preferredCurrency);
var destCurrency = parseInt(accountInfo[destAccount].preferredCurrency);
console.log('initCurrencyIdValues(): Set source account currency to ' + sourceCurrency);
$('input[name="source_account_currency"]').val(sourceCurrency);
console.log('Set destination account currency to ' + destCurrency);
$('input[name="destination_account_currency"]').val(destCurrency);
}
/**
* Set some initial values for the user to see.
*/
function updateInitialPage() {
console.log('in updateInitialPage()');
if (journal.transaction_type.type === "Transfer") {
$('#native_amount_holder').hide();
$('#amount_holder').hide();
if (journalData.native_currency.id === journalData.destination_currency.id) {
$('#exchange_rate_instruction_holder').hide();
$('#destination_amount_holder').hide();
}
if (journalData.native_currency.id !== journalData.destination_currency.id) {
$('#exchange_rate_instruction_holder').show().find('p').text(getTransferExchangeInstructions());
}
return;
}
$('#source_amount_holder').hide();
$('#destination_amount_holder').hide();
if (journalData.native_currency.id === journalData.currency.id) {
$('#exchange_rate_instruction_holder').hide();
$('#native_amount_holder').hide();
}
if (journalData.native_currency.id !== journalData.currency.id) {
$('#ffInput_exchange_rate_instruction').text(getExchangeInstructions());
}
}
/**
* Get accountID based on some meta info.
*/
function getAccountId() {
console.log('in getAccountId()');
if (journal.transaction_type.type === "Withdrawal") {
return $('select[name="source_id"]').val();
}
if (journal.transaction_type.type === "Deposit") {
return $('select[name="destination_id"]').val();
}
//alert('Cannot handle ' + journal.transaction_type.type);
return undefined;
}
/**
* Set the auto-complete JSON things.
*/
function setAutocompletes() {
// do description auto complete:
var journalNames = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'json/transaction-journals/' + what + '?uid=' + uid,
filter: function (list) {
return $.map(list, function (name) {
return {name: name};
});
}
},
remote: {
url: 'json/transaction-journals/' + what + '?search=%QUERY&uid=' + uid,
wildcard: '%QUERY',
filter: function (list) {
return $.map(list, function (name) {
return {name: name};
});
}
}
});
journalNames.initialize();
$('input[name="description"]').typeahead({hint: true, highlight: true,}, {source: journalNames, displayKey: 'name', autoSelect: false});
}
/**
* This function generates a small helper text to explain the user
* that they have selected a foreign currency.
* @returns {XML|string|void}
*/
function getExchangeInstructions() {
console.log('In getExchangeInstructions()');
var selectedAccountId = getAccountId();
var foreignCurrencyId = parseInt($('input[name="amount_currency_id_amount"]').val());
var nativeCurrencyId = parseInt(accountInfo[selectedAccountId].preferredCurrency);
var text = exchangeRateInstructions.replace('@name', accountInfo[selectedAccountId].name);
text = text.replace(/@native_currency/g, currencyInfo[nativeCurrencyId].name);
text = text.replace(/@foreign_currency/g, currencyInfo[foreignCurrencyId].name);
return text;
}