/* Skuld — shared helpers for every page. * * Loaded after session.js and before the page script. A page script registers * one handler with Skuld.on("", fn); this file calls it once the * document is ready. * * Exported as window.Skuld: * api(method, path, body) fetch JSON, throws {status, error, field} * formatOre(ore) "1 234,50", the exact stored value, for inputs * formatKroner(ore) "1 060 375 kr", whole kroner * formatSats(sats) "1 500 000", whole sats, no unit * formatPercent(value) "33,3 %" * formatDate(iso) "31.12.2025" * parseSats(text) "1 500 000" -> 1500000, null on a decimal * sheetRow(account), totalsRow(totals, sats), gapRow(), totRow(row) * fieldValue(name), fieldChecked(name), setFieldValue(name, value), * setFieldChecked(name, checked), setFieldVisible(name, visible) * setMessage(text, isError), clearErrors(), showError(error) * on(page, handler), start() */ (function () { "use strict"; var THOUSANDS_SEPARATORS = [" ", "\u00a0", "\u202f"]; function group(digits) { var parts = []; var rest = digits; while (rest.length > 3) { parts.unshift(rest.slice(-3)); rest = rest.slice(0, -3); } parts.unshift(rest); return parts.join(" "); } function formatOre(ore) { if (ore === null || ore === undefined || ore === "") { return ""; } var value = String(Math.abs(Number(ore))); while (value.length < 3) { value = "0" + value; } var sign = Number(ore) < 0 ? "-" : ""; return sign + group(value.slice(0, -2)) + "," + value.slice(-2); } /* Whole kroner, halves rounded up, grouped with spaces and the unit. */ function formatKroner(ore) { if (ore === null || ore === undefined || ore === "") { return ""; } var value = Number(ore); var sign = value < 0 ? "-" : ""; return sign + group(String(Math.round(Math.abs(value) / 100))) + " kr"; } /* A whole number of sats, grouped with spaces. No unit and no decimals. */ function formatSats(sats) { if (sats === null || sats === undefined || sats === "") { return ""; } var value = Number(sats); var sign = value < 0 ? "-" : ""; return sign + group(String(Math.abs(value))); } function formatPercent(value) { if (value === null || value === undefined || value === "") { return ""; } return String(value).replace(".", ",") + " %"; } function formatDate(iso) { if (!iso) { return ""; } var parts = String(iso).split("-"); if (parts.length !== 3) { return String(iso); } return parts[2] + "." + parts[1] + "." + parts[0]; } /* Whole sats, with spaces allowed as thousands separators. Anything carrying a decimal separator gives null, like the server does. */ function parseSats(text) { var cleaned = String(text === null || text === undefined ? "" : text); THOUSANDS_SEPARATORS.forEach(function (separator) { cleaned = cleaned.split(separator).join(""); }); if (!/^-?\d+$/.test(cleaned)) { return null; } return Number(cleaned); } /* The stored type names and what the owner sees, docs/spec.md section 7.3. */ var TYPE_LABELS = { trade: "Handel", income: "Inntekt", spend: "Forbruk", loss: "Tap", transfer_out: "Overføring ut", transfer_in: "Overføring inn", gift_received: "Gåve (motteke)", gift_given: "Gåve (gjeven)", admin_cost: "Forvaltningskostnad" }; function typeLabel(type) { return TYPE_LABELS[type] || String(type || ""); } function api(method, path, body) { var options = { method: method, headers: { "Accept": "application/json" } }; if (body !== undefined && body !== null) { options.headers["Content-Type"] = "application/json"; options.body = JSON.stringify(body); } return fetch(path, options).then(function (response) { return response.text().then(function (raw) { var data = null; if (raw) { try { data = JSON.parse(raw); } catch (ignored) { data = null; } } if (!response.ok) { var problem = data && typeof data === "object" ? data : {}; throw { status: response.status, error: problem.error || "Noko gjekk gale. Prøv om att.", field: problem.field || null }; } return data; }); }); } function cell(row, text, className) { var td = document.createElement("td"); td.textContent = text; if (className) { td.className = className; } row.appendChild(td); return td; } /* The main sheet row of docs/spec.md section 7.2, columns in order. */ function sheetRow(account) { var row = document.createElement("tr"); cell(row, account.name, ""); cell(row, formatPercent(account.share_percent), "numeric"); cell(row, formatSats(account.sats), "numeric"); cell(row, formatKroner(account.formue_ore), "numeric"); cell(row, account.gevinst_ore ? formatKroner(account.gevinst_ore) : "-", "numeric"); cell(row, account.tap_ore ? formatKroner(account.tap_ore) : "-", "numeric"); cell(row, formatKroner(account.brukt_ore), "numeric"); cell(row, formatPercent(account.gevinst_percent), "numeric"); return row; } function totalsRow(totals, sats) { var row = sheetRow({ name: "Sum", share_percent: sats ? 100 : 0, sats: sats, formue_ore: totals.formue_ore, gevinst_ore: totals.gevinst_ore, tap_ore: totals.tap_ore, brukt_ore: totals.brukt_ore, gevinst_percent: totals.brukt_ore ? Math.round((totals.gevinst_ore * 1000) / totals.brukt_ore) / 10 : 0 }); row.className = "totals"; return row; } function gapRow() { var row = document.createElement("tr"); row.className = "gap"; cell(row, "", ""); return row; } /* A row that carries the account name and the sats only: the non-taxable accounts of docs/spec.md section 7.2 and the TOT rows. */ function satsOnlyRow(name, sats, className) { var row = document.createElement("tr"); if (className) { row.className = className; } cell(row, name, ""); cell(row, "", "numeric"); cell(row, formatSats(sats), "numeric"); for (var i = 0; i < 5; i += 1) { cell(row, "", "numeric"); } return row; } /* A TOT row: the physical count of one account plus the accounts it holds for. */ function totRow(reconciliation) { return satsOnlyRow("TOT " + reconciliation.name, reconciliation.sats, "tot-row"); } function field(name) { return document.querySelector('[name="' + name + '"]'); } function fieldValue(name) { var input = field(name); return input ? String(input.value).trim() : ""; } function fieldChecked(name) { var input = field(name); return input ? Boolean(input.checked) : false; } function setFieldValue(name, value) { var input = field(name); if (input) { input.value = value === null || value === undefined ? "" : String(value); } } function setFieldChecked(name, checked) { var input = field(name); if (input) { input.checked = Boolean(checked); } } function setFieldVisible(name, visible) { var wrapper = document.querySelector('[data-field="' + name + '"]'); if (wrapper) { wrapper.hidden = !visible; } } function setMessage(text, isError) { var box = document.querySelector("[data-message]"); if (!box) { return; } box.textContent = text || ""; box.className = "message " + (isError ? "message-error" : "message-ok"); box.hidden = !text; } function clearErrors() { Array.prototype.forEach.call( document.querySelectorAll("[data-field].invalid"), function (wrapper) { wrapper.classList.remove("invalid"); } ); Array.prototype.forEach.call( document.querySelectorAll("[data-error]"), function (slot) { slot.textContent = ""; } ); setMessage("", false); } /* Show a validation error next to its field, or as a page message. */ function showError(error) { clearErrors(); var message = (error && error.error) || "Noko gjekk gale. Prøv om att."; if (error && error.field) { var wrapper = document.querySelector('[data-field="' + error.field + '"]'); if (wrapper) { wrapper.classList.add("invalid"); var slot = wrapper.querySelector("[data-error]"); if (slot) { slot.textContent = message; return; } } } setMessage(message, true); } var handlers = {}; function on(page, handler) { handlers[page] = handler; } function start() { var logout = document.querySelector("[data-logout]"); if (logout) { logout.addEventListener("click", function (event) { event.preventDefault(); api("POST", "/api/auth/logout").then(function () { window.location.href = "/login"; }); }); } var page = document.body ? document.body.dataset.page : ""; var handler = handlers[page]; if (!handler) { return; } Promise.resolve() .then(handler) .catch(function (error) { showError(error); }); } window.Skuld = { api: api, formatOre: formatOre, formatKroner: formatKroner, formatSats: formatSats, formatPercent: formatPercent, formatDate: formatDate, parseSats: parseSats, TYPE_LABELS: TYPE_LABELS, typeLabel: typeLabel, sheetRow: sheetRow, totalsRow: totalsRow, gapRow: gapRow, totRow: totRow, satsOnlyRow: satsOnlyRow, fieldValue: fieldValue, fieldChecked: fieldChecked, setFieldValue: setFieldValue, setFieldChecked: setFieldChecked, setFieldVisible: setFieldVisible, setMessage: setMessage, clearErrors: clearErrors, showError: showError, on: on, start: start }; document.addEventListener("DOMContentLoaded", start); })();