Something went wrong. Try again.
Convert CSV banking statements to hledger journals
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359// The csv2journal interface. Deliberately small and framework-free (D1).//// Every value that came from a CSV, a rule name or a diagnostic is written// with textContent, never innerHTML: bank statement text is arbitrary and must// never be interpreted as markup.//// Filtering and searching are done by the server, which is where M1-UI-006's// semantics are defined and tested. This file only asks and renders.
import "./rule-editor.js";import { cells, columnsOf, inColumnOrder, legendEntry } from "./legend.js";import { cornerState, countText, problemEntry } from "./problems.js";import { Draft, stateText } from "./draft.js";import { Api, viewQuery } from "./api.js";import { patternOf } from "./clause.js";import { actionsCell, keyAction } from "./row-actions.js";import { namedRules, openPicker } from "./rule-picker.js";import { openPrompt } from "./rule-prompt.js";import { Selection } from "./selection.js";import { previewOutcome, writeOutcome } from "./journal.js";import { summaryText } from "./summary.js";import { store, stored } from "./theme.js";
let latest = null;
// Whether the problems panel is open. Only a click opens it, and it stays as// chosen while the count comes and goes (§6.6).let problemsOpen = false;
const draft = new Draft();let busy = false;
// The cells of an unmatched row picked for a rule (D12).const selection = new Selection();
const el = (id) => document.getElementById(id);
function cell(text, className) { const td = document.createElement("td"); td.textContent = text; if (className) td.className = className; return td;}
function renderRows(data, columns) { selection.keep(data.rows); const named = namedRules(draft.rules).length > 0; const body = el("rows"); body.replaceChildren(...data.rows.map((row) => { const tr = document.createElement("tr"); tr.append( cell(String(row.row)), cell(row.status, "status-" + row.status), cell(row.rules.join(", ")), cells(row.cells, columns), ); if (row.status === "zero") { tr.dataset.row = String(row.row); markSelectable(tr, row.row); tr.append(actionsCell(selection.holds(row.row), named, { onNewRule: (button) => promptRule(button, row, columns), onExistingRule: (button) => pickRule(button, row, columns), })); } else { tr.append(cell("")); } return tr; })); el("empty").hidden = data.rows.length > 0;}
function renderLegend(fields, columns) { el("fields").replaceChildren(...fields.map((field) => legendEntry(field, columns))); el("legend").hidden = fields.length === 0;}
function renderDiagnostics(data) { const all = data.diagnostics; const count = countText(all.length);
el("diagnostics").replaceChildren(...all.map(problemEntry)); el("problems").hidden = all.length === 0; el("problems-badge").textContent = count; el("problems-title").textContent = count; el("problems-badge").hidden = problemsOpen; el("problems-panel").hidden = !problemsOpen; document.body.dataset.problems = cornerState(all.length, problemsOpen);}
// Focus follows the control, so the keyboard can go back the way it came.function showProblems(open) { problemsOpen = open; renderDiagnostics(latest); el(open ? "problems-header" : "problems-badge").focus();}
// -- the rule editor (M1-UI-008) ---------------------------------------------//// Each rule's fields are a <rule-editor> (rule-editor.js). It reports edits;// this is where they become the draft. One rule is open at a time: opening one// folds the rest (§6.5 of DESIGN_M1.md).
function card(rule, index) { const editor = document.createElement("rule-editor"); editor.rule = rule; editor.complete = (before) => api.complete(before); editor.addEventListener("rule-edit", (event) => { draft.rules[index] = event.detail; renderState(); }); editor.addEventListener("rule-commit", push); editor.addEventListener("rule-open", () => { for (const other of el("rules").children) { if (other !== editor) other.fold(); } }); editor.addEventListener("rule-delete", () => { draft.rules.splice(index, 1); renderEditor(); push(); }); return editor;}
function renderEditor() { el("rules").replaceChildren(...draft.rules.map(card));}
function renderState() { const stale = draft.stale; el("state").textContent = stateText({ busy, stale, latest }); el("save").disabled = busy || !latest || !latest.savable; el("finalize").disabled = busy || !latest || !latest.finalizable; document.body.dataset.stale = String(busy || stale);}
// The four status boxes, without "all".const statusBoxes = () => [...el("filters").querySelectorAll("input[value]")];
// The filter and search the rows are shown under, as the controls say. The// browser's fetch refuses to be called as another object's method, which is// how Api would call it, so it goes in wrapped.const api = new Api((url, init) => fetch(url, init), () => { const checked = statusBoxes().filter((box) => box.checked).map((box) => box.value); return viewQuery(checked, el("search").value);});
// Every API response carries the same state payload, so there is one way to// render an outcome. The status says whether it was accepted.async function send(method, path, body) { busy = true; renderState(); let outcome; try { outcome = await api.send(method, path, body); } finally { busy = false; } latest = outcome.payload; render(); // The filter or search changed while this was out. The answer still says // what became of the request, but its rows are for the view as it was. if (!outcome.current) refresh(); return outcome.accepted;}
// M1-UI-010: one exchange carries the edit and brings back its results, so// there is no moment where the screen shows results for some other draft.async function push() { // Whatever is on screen was generated from the rules as they were. clearJournal(); const body = draft.body; // A refused edit leaves the session holding what it held, so the results on // screen are still not for these fields. if (await send("PUT", "/api/rules", body)) draft.accepted(body); renderState();}
el("add").addEventListener("click", () => { draft.add(); renderEditor(); el("rules").lastElementChild.edit(); renderState();});
// M1-UI-016: the one save action.el("save").addEventListener("click", () => send("POST", "/api/save", ""));
// -- picking cells for a rule (D12) -----------------------------------------//// A click on an aliased cell of a row no rule matches selects it, or unselects// it (selection.js). The row's buttons then add the selected cells' clauses// to a rule (row-actions.js).
// A cell of only whitespace has no clause, so it cannot be picked.function markSelectable(tr, row) { for (const span of tr.querySelectorAll("[data-column]")) { if (patternOf(span.textContent) === null) continue; span.classList.add("selectable"); span.classList.toggle("selected", selection.has(row, Number(span.dataset.column))); span.addEventListener("click", () => { selection.toggle(row, Number(span.dataset.column)); render(); }); }}
// Into the rule at `index` in the draft.function addCells(row, columns, index) { const clauses = selection.clauses(row.cells, columns); selection.clear(); el("rules").children[index].extend(clauses); render();}
const prompt = el("rule-prompt");
// A rule that has its name and target account before it is added, so it can// be pushed at once.function promptRule(button, row, columns) { openPrompt(prompt, button, draft.rules, (fields) => { draft.add(fields); renderEditor(); addCells(row, columns, draft.rules.length - 1); push(); });}
const picker = el("rule-picker");
function pickRule(button, row, columns) { openPicker(picker, button, draft.rules, (index) => addCells(row, columns, index));}
// The keys act on the selected row as its buttons do, by pressing them, so a// disabled one stays inert. Typing in a field, the rule editor's included,// is left alone.addEventListener("keydown", (event) => { const action = keyAction(event); if (action === null || event.composedPath()[0].closest?.("input, textarea, [popover]")) return; const tr = [...el("rows").children].find((row) => selection.holds(Number(row.dataset.row))); if (tr === undefined) return; event.preventDefault(); if (action === "clear") { selection.clear(); render(); } else { tr.querySelector(`[data-action="${action}"]`).click(); }});
// They hang from a row's button, which scrolling moves away from (popover.js).addEventListener("scroll", () => { document.querySelector(".below-button:popover-open")?.hidePopover();});
// -- the journal (M1-UI-014, M1-UI-021) --------------------------------------
// A preview is discarded whenever anything changes, rather than left on screen// next to results it no longer belongs to.function clearJournal() { el("journal").hidden = true; el("journal").textContent = ""; el("draft-note").hidden = true; el("outcome").textContent = "";}
async function showPreview() { el("outcome").textContent = "generating…"; const preview = await api.preview(); clearJournal(); el("outcome").textContent = previewOutcome(preview); if (preview.journal === null) return;
el("journal").textContent = preview.journal; el("journal").hidden = false; // M1-UI-014: visibly non-final while anything still blocks writing it. el("draft-note").hidden = preview.final;}
async function writeJournal() { el("outcome").textContent = "writing…"; const accepted = await send("POST", "/api/finalize", ""); el("outcome").textContent = writeOutcome(accepted, latest.diagnostics);}
el("preview").addEventListener("click", showPreview);el("finalize").addEventListener("click", writeJournal);
async function refresh() { const answer = await api.state(); // Whatever changed the view since has asked again. if (answer === null) return; latest = answer; // The editor is rebuilt only when the draft came from somewhere other than // these fields, which is to say on the first load. if (!draft.loaded) { draft.load(latest.rules); renderEditor(); } render();}
function render() { const fields = inColumnOrder(latest.fields); const columns = columnsOf(fields); el("summary").textContent = summaryText(latest); renderDiagnostics(latest); renderLegend(fields, columns); renderRows(latest, columns); renderState();}
// -- light and dark (D14) ---------------------------------------------------//// index.html has already applied the kept choice. This shows it pressed, and// replaces a kept value that is no choice with "system", which app.css leaves// to the browser, as it does any value that is not light or dark.
const storage = () => localStorage;
function showTheme(choice) { document.documentElement.dataset.theme = choice; for (const button of el("theme").children) { button.setAttribute("aria-pressed", String(button.dataset.choice === choice)); }}
el("theme").addEventListener("click", (event) => { const button = event.target.closest("button"); if (button === null) return; store(storage, button.dataset.choice); showTheme(button.dataset.choice);});
showTheme(stored(storage));
el("problems-badge").addEventListener("click", () => showProblems(true));el("problems-header").addEventListener("click", () => showProblems(false));el("problems-panel").addEventListener("keydown", (event) => { if (event.key === "Escape") showProblems(false);});
el("search").addEventListener("input", refresh);
// "all" is checked exactly when the four are, and checking or unchecking it// does the same to them.el("filters").addEventListener("change", (event) => { const all = el("all"); if (event.target === all) { for (const box of statusBoxes()) box.checked = all.checked; } else { all.checked = statusBoxes().every((box) => box.checked); } refresh();});
refresh();