/* Skuld — the transaction form of docs/spec.md section 7.3. * * Field order: Generelt, the fields of the type, Avgift, Anna, and the Parti * section that mirrors the automatic pick of the lot method. The server is the * authority: this file only shows what the rules of sections 3.2 and 5.2 say. */ (function () { "use strict"; /* What each type shows, exactly the list of docs/spec.md section 7.3. A slot with one currency shows that unit as plain text; `default` is the currency a slot with a choice opens with. `market` and `fee` say whether those two sections belong to the type. */ var TYPE_FIELDS = { trade: { in: {label: "Kjøp", currencies: ["sats", "nok"], default: "sats"}, out: {label: "Salg/kostnad", currencies: ["sats", "nok"], default: "nok"}, consumes: true, market: true, fee: true }, income: { in: {label: "Inntekt/gevinst", currencies: ["sats"]}, value: {label: "Pris"}, consumes: false, market: true, fee: true }, spend: { out: {label: "Forbruk", currencies: ["sats"]}, value: {label: "Utgangsverdi"}, consumes: true, market: true, fee: true }, loss: { out: {label: "Tap", currencies: ["sats"]}, value: {label: "Pris"}, consumes: true, market: true, fee: true }, transfer_out: { out: {label: "Sendt", currencies: ["sats", "nok"], default: "sats"}, to: true, consumes: true, market: true, fee: true }, transfer_in: { in: {label: "Motteke", currencies: ["sats"]}, consumes: false, market: true, fee: false }, gift_received: { in: {label: "Motteke gåve", currencies: ["sats"]}, value: {label: "Pris"}, consumes: false, market: true, fee: false }, gift_given: { out: {label: "Gjeven gåve", currencies: ["sats"]}, consumes: true, market: true, fee: true }, admin_cost: { out: {label: "Kostnad", currencies: ["nok"]}, consumes: false, market: false, fee: false } }; /* What the owner sees for a currency: sats and whole kroner (section 2). */ var UNIT_LABELS = {sats: "sats", nok: "kr"}; /* Types where a sats fee is taken on top of the amount given away, §3.2. */ var FEE_TAKEN_ON_TOP = ["trade", "spend", "transfer_out"]; var form = document.querySelector("[data-form]"); var title = document.querySelector("[data-title]"); var lotsSection = document.querySelector("[data-lots-section]"); var lotsBody = document.querySelector("[data-lots]"); var saveButton = document.querySelector("[data-save]"); var transactionId = null; var generated = false; var picksDirty = false; var lotMethod = "FIFO"; var lotRows = []; function fieldKey(name) { if (!name) { return null; } if (name.indexOf("leg_in_") === 0) { return "leg_in"; } if (name.indexOf("leg_out_") === 0) { return "leg_out"; } if (name.indexOf("fee_") === 0) { return "fee"; } if (name === "value_ore") { return "value"; } if (name === "to_market_id") { return "to_market"; } return name; } function scoped(error) { return { status: error && error.status, error: (error && error.error) || "Noko gjekk gale. Prøv om att.", field: fieldKey(error && error.field) }; } function group(name) { return document.querySelector('[data-group="' + name + '"]'); } function label(name) { return document.querySelector('[data-label="' + name + '"]'); } function unit(name) { return document.querySelector('[data-unit="' + name + '"]'); } function type() { return Skuld.fieldValue("type"); } function currentType() { return TYPE_FIELDS[type()] || {}; } function legValues(name) { var amount = Skuld.fieldValue(name + "_amount"); if (!amount) { return null; } var currency = Skuld.fieldValue(name + "_currency"); return { field: name + (currency === "sats" ? "_sats" : "_ore"), value: amount }; } function needSats() { var out = legValues("leg_out"); if (!out || out.field !== "leg_out_sats") { return 0; } var sats = Skuld.parseSats(out.value) || 0; if (FEE_TAKEN_ON_TOP.indexOf(type()) !== -1) { sats += Skuld.parseSats(Skuld.fieldValue("fee")) || 0; } return sats; } /* The pick of docs/spec.md section 5.2, for the pre-selection in the form. */ function autoPick(lots, need, method) { var sorted = lots.slice(); if (method === "LIFO") { sorted.sort(function (left, right) { return right.acquired_date.localeCompare(left.acquired_date) || right.id - left.id; }); } else if (method === "HIFO") { sorted.sort(function (left, right) { return right.btc_price_ore - left.btc_price_ore || left.acquired_date.localeCompare(right.acquired_date) || left.id - right.id; }); } var remaining = need; var picked = []; sorted.forEach(function (lot) { if (remaining <= 0) { return; } var take = Math.min(remaining, lot.sats_remaining); if (take > 0) { picked.push({lot: lot, sats: take}); remaining -= take; } }); return picked; } function clearLots() { lotsBody.textContent = ""; lotRows = []; } function buildLotRow(lot) { var row = document.createElement("tr"); row.className = "lot-row"; var pickCell = document.createElement("td"); var checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.addEventListener("change", function () { picksDirty = true; markPicked(); }); pickCell.appendChild(checkbox); row.appendChild(pickCell); var dateCell = document.createElement("td"); dateCell.textContent = Skuld.formatDate(lot.acquired_date); row.appendChild(dateCell); var satsCell = document.createElement("td"); satsCell.className = "numeric"; satsCell.textContent = Skuld.formatSats(lot.sats_remaining); row.appendChild(satsCell); var costCell = document.createElement("td"); costCell.className = "numeric"; costCell.textContent = Skuld.formatKroner(lot.btc_price_ore); row.appendChild(costCell); var amountCell = document.createElement("td"); amountCell.className = "numeric"; var amount = document.createElement("input"); amount.type = "text"; amount.inputMode = "decimal"; amount.className = "lot-amount"; amount.addEventListener("input", function () { picksDirty = true; markPicked(); }); amountCell.appendChild(amount); row.appendChild(amountCell); lotsBody.appendChild(row); return {lot: lot, row: row, checkbox: checkbox, amount: amount}; } function markPicked() { lotRows.forEach(function (item) { item.row.className = "lot-row" + (item.checkbox.checked ? " lot-picked" : ""); }); } function applyAutoPick() { var picked = {}; autoPick(lotRows.map(function (item) { return item.lot; }), needSats(), lotMethod).forEach(function (choice) { picked[choice.lot.id] = choice.sats; }); lotRows.forEach(function (item) { var sats = picked[item.lot.id]; item.checkbox.checked = Boolean(sats); item.amount.value = sats ? Skuld.formatSats(sats) : ""; }); markPicked(); } function showPicks(picks) { picks.forEach(function (pick) { lotRows.forEach(function (item) { if (item.lot.origin_tx_id === pick.origin_tx_id && item.lot.origin_seq === pick.origin_seq) { item.checkbox.checked = true; item.amount.value = Skuld.formatSats(pick.sats); } }); }); markPicked(); } function needsLots() { var spec = currentType(); if (!spec.consumes) { return false; } var out = legValues("leg_out"); return Boolean(out && out.field === "leg_out_sats"); } function loadLots() { if (!needsLots() || !Skuld.fieldValue("market_id")) { lotsSection.hidden = true; clearLots(); return Promise.resolve(); } lotsSection.hidden = false; var query = "/api/lots?market_id=" + encodeURIComponent(Skuld.fieldValue("market_id")) + "&date=" + encodeURIComponent(Skuld.fieldValue("date")); return Skuld.api("GET", query).then(function (lots) { clearLots(); lots.forEach(function (lot) { lotRows.push(buildLotRow(lot)); }); if (!picksDirty) { applyAutoPick(); } return null; }); } /* What depends on the currency of the outgoing leg (docs/spec.md section 3.11). */ function syncDestination() { var spec = currentType(); var destination = document.querySelector('[name="to_market"]'); var kroner = Skuld.fieldValue("leg_out_currency") === "nok"; destination.required = Boolean(spec.to) && !kroner; var destinationHint = document.querySelector("[data-destination-hint]"); if (destinationHint) { destinationHint.hidden = !spec.to || !kroner; } } function applyType() { var spec = currentType(); [["leg_in", spec.in], ["leg_out", spec.out]].forEach(function (pair) { var name = pair[0]; var settings = pair[1]; group(name).hidden = !settings; if (!settings) { Skuld.setFieldValue(name + "_amount", ""); return; } label(name).textContent = settings.label; var choice = settings.currencies.length > 1; var currencySelect = document.querySelector('[name="' + name + '_currency"]'); currencySelect.hidden = !choice; currencySelect.value = settings.default || settings.currencies[0]; var unitSlot = unit(name); unitSlot.hidden = choice; unitSlot.textContent = UNIT_LABELS[settings.currencies[0]]; }); // The price is always in kroner and a fee always in sats (section 7.3). unit("value").textContent = UNIT_LABELS.nok; unit("fee").textContent = UNIT_LABELS.sats; group("value").hidden = !spec.value; if (spec.value) { label("value").textContent = spec.value.label; } else { Skuld.setFieldValue("value", ""); } group("to_market").hidden = !spec.to; if (!spec.to) { Skuld.setFieldValue("to_market", ""); } // An empty destination is a withdrawal, and only kroner can be withdrawn // (docs/spec.md section 3.11). syncDestination(); group("market").hidden = !spec.market; var marketSelect = document.querySelector('[name="market_id"]'); marketSelect.required = Boolean(spec.market); if (!spec.market) { Skuld.setFieldValue("market_id", ""); } group("fee").hidden = !spec.fee; if (!spec.fee) { Skuld.setFieldValue("fee", ""); } } function fillTypes() { var select = document.querySelector('[name="type"]'); Object.keys(Skuld.TYPE_LABELS).forEach(function (key) { var option = document.createElement("option"); option.value = key; option.textContent = Skuld.typeLabel(key); // A generated transfer_in is shown, never chosen (docs/spec.md section 7.3). option.disabled = key === "transfer_in"; select.appendChild(option); }); } var marketList = []; function fillMarkets(markets) { marketList = markets; fillMarketSelects(); } /* The bank is offered only where docs/spec.md section 3.11 allows it: a transfer whose amount is in kroner, as the account it is drawn from or the one it goes to. Everywhere else it is not a choice. */ function bankAllowed() { return type() === "transfer_out" && Skuld.fieldValue("leg_out_currency") === "nok"; } function fillMarketSelects() { var allowBank = bankAllowed(); ["market_id", "to_market"].forEach(function (name) { var select = document.querySelector('[name="' + name + '"]'); var keep = select.value; select.textContent = ""; if (name === "to_market") { var empty = document.createElement("option"); empty.value = ""; empty.textContent = "Vel konto"; select.appendChild(empty); } marketList.forEach(function (market) { if (market.bank && !allowBank) { return; } var option = document.createElement("option"); option.value = String(market.id); option.textContent = market.name; select.appendChild(option); }); select.value = keep; }); } function payload() { var data = { date: Skuld.fieldValue("date"), type: type(), taxable: Skuld.fieldChecked("taxable") ? 1 : 0, note: Skuld.fieldValue("note") }; var marketId = group("market").hidden ? "" : Skuld.fieldValue("market_id"); data.market_id = marketId ? Number(marketId) : null; [legValues("leg_in"), legValues("leg_out")].forEach(function (leg) { if (leg) { data[leg.field] = leg.value; } }); if (!group("value").hidden) { var value = Skuld.fieldValue("value"); if (value) { data.value_ore = value; } } var fee = Skuld.fieldValue("fee"); if (fee) { data.fee_sats = fee; } var toMarket = Skuld.fieldValue("to_market"); if (!group("to_market").hidden && toMarket) { data.to_market_id = Number(toMarket); } if (picksDirty) { data.lot_picks = []; lotRows.forEach(function (item) { var sats = Skuld.parseSats(item.amount.value); if (item.checkbox.checked && sats) { data.lot_picks.push({ origin_tx_id: item.lot.origin_tx_id, origin_seq: item.lot.origin_seq, sats: sats }); } }); } return data; } function fill(transaction) { transactionId = transaction.id; title.textContent = "Endre transaksjon"; Skuld.setFieldValue("date", transaction.date); Skuld.setFieldValue("type", transaction.type); Skuld.setFieldChecked("taxable", Boolean(transaction.taxable)); Skuld.setFieldValue("note", transaction.note); Skuld.setFieldValue("market_id", String(transaction.market_id)); applyType(); if (transaction.leg_in_sats) { Skuld.setFieldValue("leg_in_currency", "sats"); Skuld.setFieldValue("leg_in_amount", Skuld.formatSats(transaction.leg_in_sats)); } else if (transaction.leg_in_ore) { Skuld.setFieldValue("leg_in_currency", "nok"); Skuld.setFieldValue("leg_in_amount", Skuld.formatOre(transaction.leg_in_ore)); } if (transaction.leg_out_sats) { Skuld.setFieldValue("leg_out_currency", "sats"); Skuld.setFieldValue("leg_out_amount", Skuld.formatSats(transaction.leg_out_sats)); } else if (transaction.leg_out_ore) { Skuld.setFieldValue("leg_out_currency", "nok"); Skuld.setFieldValue("leg_out_amount", Skuld.formatOre(transaction.leg_out_ore)); } if (transaction.value_ore) { Skuld.setFieldValue("value", Skuld.formatOre(transaction.value_ore)); } if (transaction.fee_sats) { Skuld.setFieldValue("fee", Skuld.formatSats(transaction.fee_sats)); } if (transaction.to_market_id) { Skuld.setFieldValue("to_market", String(transaction.to_market_id)); } } function showAsGenerated() { generated = true; title.textContent = "Overføring inn"; saveButton.hidden = true; Skuld.setMessage( "Denne overføringa inn vart laga automatisk av ei overføring ut. Ho kan " + "berre sjåast her, og vert endra eller sletta saman med overføringa ut.", false ); Array.prototype.forEach.call(form.querySelectorAll("input, select, button"), function (item) { item.disabled = true; }); } function submit(event) { event.preventDefault(); Skuld.clearErrors(); var path = transactionId ? "/api/transactions/" + transactionId : "/api/transactions"; var method = transactionId ? "PATCH" : "POST"; return Skuld.api(method, path, payload()) .then(function () { window.location.href = "/transaksjonar"; }) .catch(function (error) { Skuld.showError(scoped(error)); }); } Skuld.on("transaction", function () { fillTypes(); var id = new URLSearchParams(window.location.search).get("id"); return Skuld.api("GET", "/api/settings") .then(function (settings) { lotMethod = settings.lot_method || "FIFO"; return Skuld.api("GET", "/api/markets"); }) .then(function (markets) { fillMarkets(markets); if (!id) { document.querySelector('[name="date"]').value = new Date().toISOString().slice(0, 10); Skuld.setFieldValue("type", "trade"); applyType(); return null; } return Skuld.api("GET", "/api/transactions/" + encodeURIComponent(id)) .then(function (data) { fill(data.transaction); if (data.transaction.generated) { showAsGenerated(); return null; } if (data.picks && data.picks.length) { picksDirty = true; } return loadLots().then(function () { if (data.picks && data.picks.length) { showPicks(data.picks); } return null; }); }); }); }); document.querySelector('[name="type"]').addEventListener("change", function () { picksDirty = false; applyType(); loadLots().catch(Skuld.showError); }); document.querySelector('[name="leg_out_currency"]').addEventListener("change", function () { // Only what depends on the currency: applyType() would set the select back to // the default of the type, so the owner could never pick the other currency. syncDestination(); loadLots().catch(Skuld.showError); }); ["leg_out_amount", "fee", "market_id", "date"].forEach(function (name) { document.querySelector('[name="' + name + '"]').addEventListener("change", function () { if (!generated) { loadLots().catch(Skuld.showError); } }); }); document.querySelector("[data-auto]").addEventListener("click", function () { picksDirty = false; applyAutoPick(); }); form.addEventListener("submit", submit); })();