Firefly III: a personal finances manager
PHP accountingbudgetbudgetingbudgetscash-flowcashflowcredit-carddockerexpensesfinancefinancesfinanciallinuxmoneypaycheckpersonal-financephpphp7
/*
* edit.js
* Copyright (c) 2024 [email protected]
*
* 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/>.
*/
import "../../boot/bootstrap.js";
import dates from "../../pages/shared/dates.js";
import Get from "../../api/model/transaction/get.js";
import { parseDownloadedSplits } from "./shared/parse-downloaded-splits.js";
import { addAllAutocompleteToForm } from "./shared/add-autocomplete.js";
import { loadCurrencies } from "./shared/load-currencies.js";
import { loadBudgets } from "./shared/load-budgets.js";
import { loadPiggyBanks } from "./shared/load-piggy-banks.js";
import { processUploadError } from "./shared/process-upload-error.js";
import { loadSubscriptions } from "./shared/load-subscriptions.js";
import i18next from "i18next";
import { defaultErrorSet } from "./shared/create-empty-split.js";
import { parseFromEntries } from "./shared/parse-from-entries.js";
import Put from "../../api/model/transaction/put.js";
import { showMessageOrRedirectUser } from "./shared/show-message-or-redirect.js";
import { processAttachments } from "./shared/process-attachments.js";
import sidebar from "../shared/sidebar.js";
import { disableSplitInputs } from "./shared/disable-split-inputs.js";
import { parseTotalAmount } from "./shared/parse-total-amount.js";
import { keyUpFromCategory } from "./shared/keyup-from-category.js";
import { keyUpFromSource } from "./shared/keyup-from-source.js";
import { keyUpFromDestination } from "./shared/keyup-from-destination.js";
import { keyUpFromDescription } from "./shared/keyup-from-description.js";
import { changedAmount } from "./shared/changed-amount.js";
import { changedForeignAmount } from "./shared/changed-foreign-amount.js";
import { parseErrors } from "./shared/parse-errors.js";
import { addSplit } from "./shared/add-split.js";
import {
clearAmount,
clearCategory,
clearDescription,
clearForeignAmount,
clearDestinationAccount,
clearSourceAccount,
} from "./shared/clear-fields.js";
import { detectTransactionType } from "./shared/detect-transaction-type.js";
import { determineAmountCurrency } from "./shared/determine-amount-currency.js";
import { loadCustomFields } from "./shared/load-custom-fields.js";
import { displayMap } from "./shared/display-map.js";
import { loadDefaultCoordinates } from "./shared/load-default-coordinates.js";
import { renderMap } from "./shared/render-map.js";
import "leaflet/dist/leaflet.css";
import { onMapClick } from "./shared/on-map-click.js";
import { onMapZoom } from "./shared/on-map-zoom.js";
import { clearLocation } from "./shared/clear-location.js";
import { removeSplit } from "./shared/remove-split.js";
import { loadTransactionLinks } from "./shared/load-transaction-links.js";
import { createLinkAutocomplete } from "./shared/create-link-autocomplete.js";
import { editLink } from "./shared/edit-link.js";
import { switchLink } from "./shared/switch-link.js";
import { removeLink } from "./shared/remove-link.js";
import { saveEditedLink } from "./shared/save-edited-link.js";
import { saveNewLink } from "./shared/save-new-link.js";
import { processTransactionLinks } from "./shared/process-transaction-links.js";
import { redirectAfterTransactionLinks } from "./shared/redirect-after-transaction-links.js";
import { addTabListener } from "./shared/add-tab-listener.js";
import { autoStep } from "./shared/auto-step.js";
import { respondToTabSwitch } from "./shared/respond-to-tab-switch.js";
import Alpine from "@alpinejs/csp";
import focusFirstInput from "../../shared/focus-first-input.js";
import filterForeignCurrencies from "./shared/filter-foreign-currencies.js";
window.enableDates = false;
let transactions = function () {
return {
// needed for translations
i18next: null,
// transactions are stored in "entries":
entries: [],
originals: [],
links: [],
// maps are stored in this array so they can be referred to.
maps: [],
markers: [],
// state of the form is stored in formState:
formStates: {
loadingCurrencies: true,
loadingBudgets: true,
loadingPiggyBanks: true,
loadingLinks: null,
loadingSubscriptions: true,
loadingTransaction: true,
isSubmitting: false,
returnHereButton: false,
saveAsNewButton: false, // edit form only
resetButton: true,
rulesButton: true,
webhooksButton: true,
categorySelectVisible: false,
descriptionSelectVisible: false,
sourceSelectVisible: false,
destinationSelectVisible: false,
// some properties that must all be true before the user can be redirected safely.
storedGroup: false,
storedLinks: false,
storedAttachments: false,
},
// form behavior during transaction
formBehaviour: {
formType: "edit",
foreignCurrencyEnabled: true,
categorySelectVisible: false,
customFields: {},
defaultCoordinates: {
loaded: false,
latitude: 30,
longitude: 20,
zoom_level: 9,
},
},
// form data (except transactions) is stored in formData
formData: {
primaryCurrency: null,
amountCurrency: null, // this is the currency of the amount field/**/
enabledCurrencies: [],
primaryCurrencies: [],
foreignCurrencies: [],
budgets: [],
piggyBanks: [],
subscriptions: [],
linkTypes: [],
},
// properties for the entire transaction group
groupProperties: {
transactionType: "unknown",
titleErrors: [],
title: null,
editTitle: null,
id: null,
totalAmount: 0,
},
// notifications
notifications: {
error: {
show: false,
text: "",
url: "",
},
success: {
show: false,
text: "",
url: "",
},
wait: {
show: false,
text: "",
},
},
// shared functions between edit/create
parseTotalAmount: parseTotalAmount,
disableSplitInputs: disableSplitInputs,
processUploadError: processUploadError,
keyUpFromCategory: keyUpFromCategory,
keyUpFromSource: keyUpFromSource,
keyUpFromDestination: keyUpFromDestination,
keyUpFromDescription: keyUpFromDescription,
changedAmount: changedAmount,
changedForeignAmount: changedForeignAmount,
showMessageOrRedirectUser: showMessageOrRedirectUser,
parseErrors: parseErrors,
addSplit: addSplit,
clearSourceAccount: clearSourceAccount,
clearDestinationAccount: clearDestinationAccount,
clearCategory: clearCategory,
clearDescription: clearDescription,
clearAmount: clearAmount,
clearForeignAmount: clearForeignAmount,
detectTransactionType: detectTransactionType,
determineAmountCurrency: determineAmountCurrency,
addAllAutocompleteToForm: addAllAutocompleteToForm,
loadCustomFields: loadCustomFields,
displayMap: displayMap,
loadDefaultCoordinates: loadDefaultCoordinates,
renderMap: renderMap,
onMapClick: onMapClick,
onMapZoom: onMapZoom,
clearLocation: clearLocation,
removeSplit: removeSplit,
createLinkAutocomplete: createLinkAutocomplete,
editLink: editLink,
switchLink: switchLink,
removeLink: removeLink,
saveEditedLink: saveEditedLink,
saveNewLink: saveNewLink,
processTransactionLinks: processTransactionLinks,
redirectAfterTransactionLinks: redirectAfterTransactionLinks,
loadTransactionLinks: loadTransactionLinks,
addTabListener: addTabListener,
autoStep: autoStep,
respondToTabSwitch: respondToTabSwitch,
filterForeignCurrencies: filterForeignCurrencies,
// part of the account selection auto-complete
changedDateTime() {
console.warn("changedDateTime, event is not used");
},
changedGroupTitle() {
console.warn("changedGroupTitle: event is not used.");
},
changedDescription() {
console.warn("changedDescription, event is not used");
},
changedDestinationAccount() {
this.detectTransactionType();
},
changedSourceAccount() {
this.detectTransactionType();
},
getTags(index) {
return this.entries[index].tags ?? [];
},
getTransactionGroup() {
this.entries = [];
const page = window.location.href.split("/");
const groupId = parseInt(page[page.length - 1]);
const getter = new Get();
getter
.show(groupId, {})
.then((response) => {
const data = response.data.data;
this.formStates.loadingTransaction = false;
this.groupProperties.id = parseInt(data.id);
this.groupProperties.transactionType = data.attributes.transactions[0].type.toLowerCase();
this.groupProperties.title =
data.attributes.group_title ?? data.attributes.transactions[0].description;
this.entries = parseDownloadedSplits(data.attributes.transactions, parseInt(data.id));
// set empty arrays
for (let i = 0; i < this.entries.length; i++) {
this.links[i] = []; // empty set of links.
}
// set amountCurrency.
for (let i in this.formData.enabledCurrencies) {
if (Object.hasOwn(this.formData.enabledCurrencies, i)) {
if (this.formData.enabledCurrencies[i].code === this.entries[0].currency_code) {
this.formData.amountCurrency = this.formData.enabledCurrencies[i];
}
}
}
// limit foreignCurrencies to a single one when it's a transfer
if ("transfer" === this.groupProperties.transactionType) {
this.formData.foreignCurrencies = [];
for (let i in this.formData.enabledCurrencies) {
if (Object.hasOwn(this.formData.enabledCurrencies, i)) {
if (this.formData.enabledCurrencies[i].code === this.entries[0].foreign_currency_code) {
this.formData.foreignCurrencies.push(this.formData.enabledCurrencies[i]);
}
}
}
}
this.autoStep();
// remove waiting thing.
this.notifications.wait.show = false;
})
.then(() => {
focusFirstInput();
let tagSelect;
this.groupProperties.totalAmount = 0;
for (let i in this.entries) {
if (Object.hasOwn(this.entries, i)) {
this.groupProperties.totalAmount =
this.groupProperties.totalAmount + parseFloat(this.entries[i].amount);
// add the tags. This is not done in Alpine itself because the combination between
// the Autocomplete library and Alpine breaks for some reason.
tagSelect = document.getElementById("tags_" + i);
if (null !== tagSelect) {
// console.log("Is not null.");
for (let j in this.entries[i].tags) {
if (Object.hasOwn(this.entries[i].tags, j)) {
tagSelect.options.add(
new Option(this.entries[i].tags[j], this.entries[i].tags[j], true, true),
);
}
}
}
}
}
this.autoStep();
});
},
init() {
this.i18next = i18next;
// download translations and get the transaction group.
this.notifications.wait.show = true;
this.notifications.wait.text = i18next.t("firefly.wait_loading_transaction");
// load meta data.
loadCurrencies().then((data) => {
this.formStates.loadingCurrencies = false;
this.formData.primaryCurrency = data.primaryCurrency;
this.formData.enabledCurrencies = data.enabledCurrencies;
this.formData.primaryCurrencies = data.primaryCurrencies;
this.formData.foreignCurrencies = data.foreignCurrencies;
this.autoStep();
this.getTransactionGroup();
this.autoStep();
});
loadBudgets(true).then((data) => {
this.formData.budgets = data;
this.formStates.loadingBudgets = false;
this.autoStep();
});
loadPiggyBanks().then((data) => {
this.formData.piggyBanks = data;
this.formStates.loadingPiggyBanks = false;
this.autoStep();
});
loadSubscriptions(true).then((data) => {
this.formData.subscriptions = data;
this.formStates.loadingSubscriptions = false;
this.autoStep();
});
// load custom field preference and enable/disable those fields.
this.loadCustomFields().then((data) => {
this.formBehaviour.customFields = data;
this.autoStep();
});
document.addEventListener("upload-failed", (event) => {
// console.log('Now in event listener "upload-failed"');
this.processUploadError(event);
});
// add some event listeners
document.addEventListener("upload-success", () => {
// console.log('Trigger on event "upload-success"');
this.processUpload();
document.querySelectorAll("input[type=file]").forEach((input) => (input.value = ""));
});
document.addEventListener("upload-error", (event) => {
this.processUploadError(event);
});
},
// TODO is a duplicate
processUpload() {
this.formStates.storedAttachments = true;
this.showMessageOrRedirectUser("edit.js processUpload");
},
// submit the transaction form.
// basically the same as store.js.
save() {
this.notifications.error.show = false;
this.notifications.success.show = false;
this.notifications.wait.show = false;
this.formStates.isSubmitting = true;
// reset all errors in the entries array:
for (let i in this.entries) {
if (Object.hasOwn(this.entries, i)) {
this.entries[i].errors = defaultErrorSet();
}
}
// parse transaction:
let transactions = parseFromEntries(this.entries, this.originals, this.groupProperties.transactionType);
let submission = {
group_title: this.groupProperties.title,
fire_webhooks: this.formStates.webhooksButton,
apply_rules: this.formStates.rulesButton,
transactions: transactions,
};
// catch for group title:
if (null === this.groupProperties.title && transactions.length > 1) {
submission.group_title = transactions[0].description;
}
if (1 === transactions.length) {
submission.group_title = null;
}
// submit the transaction. Multi-stage process thing going on here!
let putter = new Put();
putter
.put(submission, { id: this.groupProperties.id })
.then((response) => {
this.formStates.storedGroup = true;
const group = response.data.data;
// submission was a success!
this.groupProperties.id = parseInt(group.id);
this.groupProperties.title =
group.attributes.group_title ?? group.attributes.transactions[0].description;
// process transaction links
// submit all transaction links, based on the order of the transaction IDs
let transactions = [];
for (let i = 0; i < group.attributes.transactions.length; i++) {
if (Object.hasOwn(group.attributes.transactions, i)) {
transactions.push(parseInt(group.attributes.transactions[i].transaction_journal_id));
}
}
this.processTransactionLinks(transactions);
// process attachments, if any:
const attachmentCount = processAttachments(this.groupProperties.id, group.attributes.transactions);
if (0 === attachmentCount) {
this.formStates.storedAttachments = true;
}
if (attachmentCount > 0) {
// if count is more than zero, system is processing transactions in the background.
this.notifications.wait.show = true;
this.notifications.wait.text = i18next.t("firefly.wait_attachments");
return;
}
// if not, respond to user options:
this.showMessageOrRedirectUser("edit.js save Put submission");
})
.catch((error) => {
console.error(error);
this.formStates.isSubmitting = false;
if (typeof error.response !== "undefined") {
this.parseErrors(error.response.data);
}
});
},
// exclusive to edit form, used to initialize splits.
addedSplit() {
this.disableSplitInputs();
this.addAllAutocompleteToForm();
this.addTabListener();
},
};
};
let comps = { transactions, sidebar, dates };
function loadPage() {
Object.keys(comps).forEach((comp) => {
// console.log(`Loading page component "${comp}"`);
let data = comps[comp]();
Alpine.data(comp, () => data);
});
Alpine.start();
}
// wait for load until bootstrapped event is received.
document.addEventListener("firefly-iii-bootstrapped", () => {
console.log("Loaded through event listener.");
loadPage();
});
// or is bootstrapped before event is triggered.
if (window.bootstrapped) {
console.log("Loaded through window variable.");
loadPage();
}