Other minification.

This commit is contained in:
James Cole
2024-01-02 15:41:14 +01:00
parent 97b65ac44c
commit 786b4c18a1
35 changed files with 1256 additions and 180 deletions

View File

@@ -25,18 +25,141 @@ import {parseFromEntries} from "./shared/parse-from-entries.js";
import formatMoney from "../../util/format-money.js";
import Autocomplete from "bootstrap5-autocomplete";
import Post from "../../api/v2/model/transaction/post.js";
import AttachmentPost from "../../api/v1/attachments/post.js";
import Get from "../../api/v2/model/currency/get.js";
import BudgetGet from "../../api/v2/model/budget/get.js";
import PiggyBankGet from "../../api/v2/model/piggy-bank/get.js";
import SubscriptionGet from "../../api/v2/model/subscription/get.js";
import {getVariable} from "../../store/get-variable.js";
import {I18n} from "i18n-js";
import {loadTranslations} from "../../support/load-translations.js";
import Tags from "bootstrap5-tags";
let i18n;
const urls = {
description: '/api/v2/autocomplete/transaction-descriptions',
account: '/api/v2/autocomplete/accounts',
category: '/api/v2/autocomplete/categories',
tag: '/api/v2/autocomplete/tags',
};
let uploadAttachments = function (id, transactions) {
console.log('Now in uploadAttachments');
// reverse list of transactions?
transactions = transactions.reverse();
// array of all files to be uploaded:
let toBeUploaded = [];
let count = 0;
// array with all file data.
let fileData = [];
// all attachments
let attachments = document.querySelectorAll('input[name="attachments[]"]');
console.log(attachments);
// loop over all attachments, and add references to this array:
for (const key in attachments) {
if (attachments.hasOwnProperty(key) && /^0$|^[1-9]\d*$/.test(key) && key <= 4294967294) {
console.log('Now at attachment #' + key);
for (const fileKey in attachments[key].files) {
if (attachments[key].files.hasOwnProperty(fileKey) && /^0$|^[1-9]\d*$/.test(fileKey) && fileKey <= 4294967294) {
// include journal thing.
console.log('Will upload #' + fileKey + ' from attachment #' + key + ' to transaction #' + transactions[key].transaction_journal_id);
toBeUploaded.push({
journal: transactions[key].transaction_journal_id, file: attachments[key].files[fileKey]
});
count++;
}
}
}
}
console.log('Found ' + count + ' attachments.');
// loop all uploads.
for (const key in toBeUploaded) {
if (toBeUploaded.hasOwnProperty(key) && /^0$|^[1-9]\d*$/.test(key) && key <= 4294967294) {
console.log('Create file reader for file #' + key);
// create file reader thing that will read all of these uploads
(function (f, key) {
let fileReader = new FileReader();
fileReader.onloadend = function (evt) {
if (evt.target.readyState === FileReader.DONE) { // DONE == 2
console.log('Done reading file #' + key);
fileData.push({
name: toBeUploaded[key].file.name,
journal: toBeUploaded[key].journal,
content: new Blob([evt.target.result])
});
if (fileData.length === count) {
console.log('Done reading file #' + key);
uploadFiles(fileData, id);
}
}
};
fileReader.readAsArrayBuffer(f.file);
})(toBeUploaded[key], key,);
}
}
return count;
}
let uploadFiles = function (fileData, id) {
let count = fileData.length;
let uploads = 0;
console.log('Will now upload ' + count + ' file(s) to journal with id #' + id);
for (const key in fileData) {
if (fileData.hasOwnProperty(key) && /^0$|^[1-9]\d*$/.test(key) && key <= 4294967294) {
console.log('Creating attachment #' + key);
let poster = new AttachmentPost();
poster.post(fileData[key].name, 'TransactionJournal', fileData[key].journal).then(response => {
let attachmentId = parseInt(response.data.data.id);
console.log('Created attachment #' + attachmentId + ' for key #' + key);
console.log('Uploading attachment #' + key);
poster.upload(attachmentId, fileData[key].content).then(attachmentResponse => {
// console.log('Uploaded attachment #' + key);
uploads++;
if (uploads === count) {
// finally we can redirect the user onwards.
console.log('FINAL UPLOAD, redirect user to new transaction or reset form or whatever.');
const event = new CustomEvent('upload-success', {some: 'details'});
document.dispatchEvent(event);
return;
}
console.log('Upload complete!');
// return true here.
}).catch(error => {
console.error('Could not upload');
console.error(error);
// console.log('Uploaded attachment #' + key);
uploads++;
if (uploads === count) {
// finally we can redirect the user onwards.
console.log('FINAL UPLOAD, redirect user to new transaction or reset form or whatever.');
//this.redirectUser(groupId, transactionData);
}
// console.log('Upload complete!');
// return false;
// return false here
});
}).catch(error => {
console.error('Could not create upload.');
console.error(error);
uploads++;
if (uploads === count) {
// finally we can redirect the user onwards.
// console.log('FINAL UPLOAD');
console.log('FINAL UPLOAD, redirect user to new transaction or reset form or whatever.');
// this.redirectUser(groupId, transactionData);
}
// console.log('Upload complete!');
//return false;
});
}
}
}
let transactions = function () {
return {
count: 0,
@@ -44,22 +167,34 @@ let transactions = function () {
transactionType: 'unknown',
showSuccessMessage: false,
showErrorMessage: false,
entries: [],
loadingCurrencies: true,
defaultCurrency: {},
entries: [], // loading things
loadingCurrencies: true,
loadingBudgets: true,
loadingPiggyBanks: true,
loadingSubscriptions: true,
// data sets
enabledCurrencies: [],
nativeCurrencies: [],
foreignCurrencies: [],
budgets: [],
piggyBanks: {},
subscriptions: [],
foreignAmountEnabled: true,
filters: {
source: [],
destination: [],
source: [], destination: [],
},
errorMessageText: '',
successMessageLink: '#',
successMessageText: '',
successMessageText: '', // error and success messages:
showError: false,
showSuccess: false,
showWaitMessage: false,
// four buttons
returnHereButton: false,
returnHereButton: true,
resetButton: false,
resetButtonEnabled: false,
rulesButton: true,
@@ -68,6 +203,10 @@ let transactions = function () {
// state of the form
submitting: false,
// used to display the success message
newGroupTitle: '',
newGroupId: 0,
detectTransactionType() {
const sourceType = this.entries[0].source_account.type ?? 'unknown';
@@ -85,7 +224,8 @@ let transactions = function () {
// this also locks the amount into the amount of the source account
// and the foreign amount (if different) in that of the destination account.
console.log('filter down currencies for transfer.');
this.filterNativeCurrencies(this.entries[0].source_account.currency_code);
this.filterForeignCurrencies(this.entries[0].destination_account.currency_code);
return;
}
// withdrawals:
@@ -124,17 +264,47 @@ let transactions = function () {
},
selectSourceAccount(item, ac) {
const index = parseInt(ac._searchInput.attributes['data-index'].value);
document.querySelector('#form')._x_dataStack[0].$data.entries[index].source_account =
{
id: item.id,
name: item.name,
alpine_name: item.name,
type: item.type,
currency_code: item.currency_code,
};
document.querySelector('#form')._x_dataStack[0].$data.entries[index].source_account = {
id: item.id,
name: item.name,
alpine_name: item.name,
type: item.type,
currency_code: item.currency_code,
};
console.log('Changed source account into a known ' + item.type.toLowerCase());
document.querySelector('#form')._x_dataStack[0].detectTransactionType();
},
filterForeignCurrencies(code) {
console.log('filterForeignCurrencies("' + code + '")');
let list = [];
let currency;
for (let i in this.enabledCurrencies) {
if (this.enabledCurrencies.hasOwnProperty(i)) {
let current = this.enabledCurrencies[i];
if (current.code === code) {
currency = current;
}
}
}
list.push(currency);
this.foreignCurrencies = list;
// is he source account currency anyway:
if (1 === list.length && list[0].code === this.entries[0].source_account.currency_code) {
console.log('Foreign currency is same as source currency. Disable foreign amount.');
this.foreignAmountEnabled = false;
}
if (1 === list.length && list[0].code !== this.entries[0].source_account.currency_code) {
console.log('Foreign currency is NOT same as source currency. Enable foreign amount.');
this.foreignAmountEnabled = true;
}
// this also forces the currency_code on ALL entries.
for (let i in this.entries) {
if (this.entries.hasOwnProperty(i)) {
this.entries[i].foreign_currency_code = code;
}
}
},
filterNativeCurrencies(code) {
console.log('filterNativeCurrencies("' + code + '")');
let list = [];
@@ -169,22 +339,28 @@ let transactions = function () {
},
selectDestAccount(item, ac) {
const index = parseInt(ac._searchInput.attributes['data-index'].value);
document.querySelector('#form')._x_dataStack[0].$data.entries[index].destination_account =
{
id: item.id,
name: item.name,
alpine_name: item.name,
type: item.type,
currency_code: item.currency_code,
};
document.querySelector('#form')._x_dataStack[0].$data.entries[index].destination_account = {
id: item.id,
name: item.name,
alpine_name: item.name,
type: item.type,
currency_code: item.currency_code,
};
console.log('Changed destination account into a known ' + item.type.toLowerCase());
document.querySelector('#form')._x_dataStack[0].detectTransactionType();
},
loadCurrencies() {
this.enabledCurrencies = [];
this.nativeCurrencies = [];
this.foreignCurrencies = [];
this.foreignCurrencies.push({
id: 0, name: '(no foreign currency)', code: '', default: false, symbol: '', decimal_places: 2,
});
console.log('Loading user currencies.');
let params = {
page: 1,
limit: 1337
page: 1, limit: 1337
};
let getter = new Get();
getter.list({}).then((response) => {
@@ -208,11 +384,123 @@ let transactions = function () {
}
this.enabledCurrencies.push(obj);
this.nativeCurrencies.push(obj);
this.foreignCurrencies.push(obj);
}
}
}
this.loadingCurrencies = false;
console.log(this.enabledCurrencies);
});
},
loadBudgets() {
this.budgets = [];
this.budgets.push({
id: 0, name: '(no budget)',
});
console.log('Loading user budgets.');
let params = {
page: 1, limit: 1337
};
let getter = new BudgetGet();
getter.list({}).then((response) => {
for (let i in response.data.data) {
if (response.data.data.hasOwnProperty(i)) {
let current = response.data.data[i];
let obj = {
id: current.id, name: current.attributes.name,
};
this.budgets.push(obj);
}
}
this.loadingBudgets = false;
console.log(this.budgets);
});
},
loadPiggyBanks() {
this.piggyBanks = {};
let tempObject = {
'0': {
id: 0, name: '(no group)', order: 0, piggyBanks: [{
id: 0, name: '(no piggy bank)', order: 0,
}]
}
};
console.log('Loading user piggy banks.');
let params = {
page: 1, limit: 1337
};
let getter = new PiggyBankGet();
getter.list({}).then((response) => {
for (let i in response.data.data) {
if (response.data.data.hasOwnProperty(i)) {
let current = response.data.data[i];
let objectGroupId = current.attributes.object_group_id ?? '0';
let objectGroupTitle = current.attributes.object_group_title ?? '(no group)';
let piggyBank = {
id: current.id, name: current.attributes.name, order: current.attributes.order,
};
if (!tempObject.hasOwnProperty(objectGroupId)) {
tempObject[objectGroupId] = {
id: objectGroupId,
name: objectGroupTitle,
order: current.attributes.object_group_order ?? 0,
piggyBanks: []
};
}
tempObject[objectGroupId].piggyBanks.push(piggyBank);
tempObject[objectGroupId].piggyBanks.sort((a, b) => a.order - b.order);
}
}
//tempObject.sort((a,b) => a.order - b.order);
this.loadingPiggyBanks = false;
this.piggyBanks = Object.keys(tempObject).sort().reduce((obj, key) => {
obj[key] = tempObject[key];
return obj;
}, {});
});
},
loadSubscriptions() {
this.subscriptions = {};
let tempObject = {
'0': {
id: 0, name: '(no group)', order: 0, subscriptions: [{
id: 0, name: '(no subscription)', order: 0,
}]
}
};
console.log('Loading user suscriptions.');
let params = {
page: 1, limit: 1337
};
let getter = new SubscriptionGet();
getter.list({}).then((response) => {
for (let i in response.data.data) {
if (response.data.data.hasOwnProperty(i)) {
let current = response.data.data[i];
let objectGroupId = current.attributes.object_group_id ?? '0';
let objectGroupTitle = current.attributes.object_group_title ?? '(no group)';
let piggyBank = {
id: current.id, name: current.attributes.name, order: current.attributes.order,
};
if (!tempObject.hasOwnProperty(objectGroupId)) {
tempObject[objectGroupId] = {
id: objectGroupId,
name: objectGroupTitle,
order: current.attributes.object_group_order ?? 0,
subscriptions: []
};
}
tempObject[objectGroupId].subscriptions.push(piggyBank);
tempObject[objectGroupId].subscriptions.sort((a, b) => a.order - b.order);
}
}
//tempObject.sort((a,b) => a.order - b.order);
this.loadingSubscriptions = false;
this.subscriptions = Object.keys(tempObject).sort().reduce((obj, key) => {
obj[key] = tempObject[key];
return obj;
}, {});
});
},
changeSourceAccount(item, ac) {
@@ -225,11 +513,9 @@ let transactions = function () {
document.querySelector('#form')._x_dataStack[0].detectTransactionType();
return;
}
document.querySelector('#form')._x_dataStack[0].$data.entries[index].source_account =
{
name: ac._searchInput.value,
alpine_name: ac._searchInput.value,
};
document.querySelector('#form')._x_dataStack[0].$data.entries[index].source_account = {
name: ac._searchInput.value, alpine_name: ac._searchInput.value,
};
console.log('Changed source account into a unknown account called "' + ac._searchInput.value + '"');
document.querySelector('#form')._x_dataStack[0].detectTransactionType();
@@ -246,20 +532,32 @@ let transactions = function () {
document.querySelector('#form')._x_dataStack[0].detectTransactionType();
return;
}
document.querySelector('#form')._x_dataStack[0].$data.entries[index].destination_account =
{
name: ac._searchInput.value,
alpine_name: ac._searchInput.value,
};
document.querySelector('#form')._x_dataStack[0].$data.entries[index].destination_account = {
name: ac._searchInput.value, alpine_name: ac._searchInput.value,
};
console.log('Changed destination account into a unknown account called "' + ac._searchInput.value + '"');
document.querySelector('#form')._x_dataStack[0].detectTransactionType();
}
},
changeCategory(item, ac) {
const index = parseInt(ac._searchInput.attributes['data-index'].value);
if (typeof item !== 'undefined' && item.name) {
//this.entries[0].category_name = object.name;
document.querySelector('#form')._x_dataStack[0].$data.entries[index].category_name = item.name;
return;
}
document.querySelector('#form')._x_dataStack[0].$data.entries[index].category_name = ac._searchInput.value;
},
// error and success messages:
showError: false,
showSuccess: false,
changeDescription(item, ac) {
const index = parseInt(ac._searchInput.attributes['data-index'].value);
if (typeof item !== 'undefined' && item.description) {
//this.entries[0].category_name = object.name;
document.querySelector('#form')._x_dataStack[0].$data.entries[index].description = item.description;
return;
}
document.querySelector('#form')._x_dataStack[0].$data.entries[index].description = ac._searchInput.value;
},
addedSplit() {
console.log('addedSplit');
@@ -285,6 +583,20 @@ let transactions = function () {
}
});
Autocomplete.init("input.ac-category", {
server: urls.category,
fetchOptions: {
headers: {
'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content
}
},
valueField: "id",
labelField: "name",
highlightTyped: true,
onSelectItem: this.changeCategory,
onChange: this.changeCategory,
});
Autocomplete.init("input.ac-dest", {
server: urls.account,
serverParams: {
@@ -316,11 +628,17 @@ let transactions = function () {
valueField: "id",
labelField: "description",
highlightTyped: true,
onSelectItem: console.log,
onSelectItem: this.changeDescription,
onChange: this.changeDescription,
});
},
processUpload(event) {
console.log('I am ALSO event listener for upload-success!');
console.log(event);
this.showBarOrRedirect();
},
init() {
Promise.all([getVariable('language', 'en_US')]).then((values) => {
@@ -333,6 +651,14 @@ let transactions = function () {
});
this.loadCurrencies();
this.loadBudgets();
this.loadPiggyBanks();
this.loadSubscriptions();
document.addEventListener('upload-success', (event) => {
this.processUpload(event);
});
// source can never be expense account
this.filters.source = ['Asset account', 'Loan', 'Debt', 'Mortgage', 'Revenue account'];
@@ -340,54 +666,72 @@ let transactions = function () {
this.filters.destination = ['Expense account', 'Loan', 'Debt', 'Mortgage', 'Asset account'];
},
submitTransaction() {
// reset all views:
this.submitting = true;
this.showSuccessMessage = false;
this.showErrorMessage = false;
this.showWaitmessage = false;
this.detectTransactionType();
// parse transaction:
let transactions = parseFromEntries(this.entries, this.transactionType);
let submission = {
// todo process all options
group_title: null,
fire_webhooks: false,
apply_rules: false,
transactions: transactions
group_title: null, fire_webhooks: false, apply_rules: false, transactions: transactions
};
if (transactions.length > 1) {
// todo improve me
submission.group_title = transactions[0].description;
}
// submit the transaction. Multi-stage process thing going on here!
let poster = new Post();
console.log(submission);
poster.post(submission).then((response) => {
this.submitting = false;
console.log(response);
const id = parseInt(response.data.data.id);
if (this.returnHereButton) {
// todo create success banner
this.showSuccessMessage = true;
this.successMessageLink = 'transactions/show/' + id;
this.successMessageText = i18n.t('firefly.stored_journal_js', {description: submission.group_title ?? submission.transactions[0].description});
// todo clear out form if necessary
if(this.resetButton) {
this.entries = [];
this.addSplit();
this.totalAmount = 0;
}
}
if (!this.returnHereButton) {
window.location = 'transactions/show/' + id + '?transaction_group_id=' + id + '&message=created';
// submission was a success.
this.newGroupId = parseInt(response.data.data.id);
this.newGroupTitle = submission.group_title ?? submission.transactions[0].description
const attachmentCount = uploadAttachments(this.newGroupId, response.data.data.attributes.transactions);
// upload transactions? then just show the wait message and do nothing else.
if (attachmentCount > 0) {
this.showWaitMessage = true;
return;
}
// if not, respond to user options:
this.showBarOrRedirect();
}).catch((error) => {
this.submitting = false;
console.log(error);
// todo put errors in form
this.parseErrors(error.response.data);
if (typeof error.response !== 'undefined') {
this.parseErrors(error.response.data);
}
});
},
showBarOrRedirect() {
this.showWaitMessage = false;
this.submitting = false;
if (this.returnHereButton) {
// todo create success banner
this.showSuccessMessage = true;
this.successMessageLink = 'transactions/show/' + this.newGroupId;
this.successMessageText = i18n.t('firefly.stored_journal_js', {description: this.newGroupTitle});
// todo clear out form if necessary
if (this.resetButton) {
this.entries = [];
this.addSplit();
this.totalAmount = 0;
}
}
if (!this.returnHereButton) {
window.location = 'transactions/show/' + this.newGroupId + '?transaction_group_id=' + this.newGroupId + '&message=created';
}
},
parseErrors(data) {
this.setDefaultErrors();
this.showErrorMessage = true;
@@ -421,27 +765,22 @@ let transactions = function () {
break;
case 'source_name':
case 'source_id':
this.entries[transactionIndex].errors.source_account =
this.entries[transactionIndex].errors.source_account.concat(data.errors[key]);
this.entries[transactionIndex].errors.source_account = this.entries[transactionIndex].errors.source_account.concat(data.errors[key]);
break;
case 'destination_name':
case 'destination_id':
this.entries[transactionIndex].errors.destination_account =
this.entries[transactionIndex].errors.destination_account.concat(data.errors[key]);
this.entries[transactionIndex].errors.destination_account = this.entries[transactionIndex].errors.destination_account.concat(data.errors[key]);
break;
case 'foreign_amount':
case 'foreign_currency_id':
this.entries[transactionIndex].errors.foreign_amount =
this.entries[transactionIndex].errors.foreign_amount.concat(data.errors[key]);
this.entries[transactionIndex].errors.foreign_amount = this.entries[transactionIndex].errors.foreign_amount.concat(data.errors[key]);
break;
}
}
// unique some things
if (typeof this.entries[transactionIndex] !== 'undefined') {
this.entries[transactionIndex].errors.source_account =
Array.from(new Set(this.entries[transactionIndex].errors.source_account));
this.entries[transactionIndex].errors.destination_account =
Array.from(new Set(this.entries[transactionIndex].errors.destination_account));
this.entries[transactionIndex].errors.source_account = Array.from(new Set(this.entries[transactionIndex].errors.source_account));
this.entries[transactionIndex].errors.destination_account = Array.from(new Set(this.entries[transactionIndex].errors.destination_account));
}
}
}
@@ -452,6 +791,22 @@ let transactions = function () {
},
addSplit() {
this.entries.push(createEmptySplit());
setTimeout(() => {
Tags.init('select.ac-tags', {
allowClear: true,
server: urls.tag,
liveServer: true,
clearEnd: true,
notFoundMessage: '(nothing found)',
noCache: true,
fetchOptions: {
headers: {
'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content
}
}
});
}, 250);
},
removeSplit(index) {
this.entries.splice(index, 1);
@@ -476,6 +831,15 @@ function loadPage() {
Alpine.start();
}
document.addEventListener('upload-success', (event) => {
console.log('I am event listener for upload-success');
console.log(event);
//Alpine.
});
// <button x-data @click="$dispatch('custom-event', 'Hello World!')">
// wait for load until bootstrapped event is received.
document.addEventListener('firefly-iii-bootstrapped', () => {
console.log('Loaded through event listener.');