diff --git a/static/transaction.js b/static/transaction.js new file mode 100644 index 0000000..153cc31 --- /dev/null +++ b/static/transaction.js @@ -0,0 +1,510 @@ +/* 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. Currencies not listed are hidden and fixed. */ + var TYPE_FIELDS = { + trade: { + in: {label: "Kjøp", currencies: ["sats", "nok"]}, + out: {label: "Salg/kostnad", currencies: ["sats", "nok"]}, + consumes: true + }, + income: { + in: {label: "Inntekt/gevinst", currencies: ["sats"]}, + value: {label: "Pris"}, + consumes: false + }, + spend: { + out: {label: "Forbruk", currencies: ["sats"]}, + value: {label: "Utgangsverdi"}, + consumes: true + }, + loss: { + out: {label: "Tap", currencies: ["sats"]}, + value: {label: "Pris", optional: true}, + consumes: true + }, + transfer_out: { + out: {label: "Sendt", currencies: ["sats"]}, + to: true, + consumes: true + }, + gift_received: { + in: {label: "Motteke gåve", currencies: ["sats"]}, + value: {label: "Pris"}, + consumes: false + }, + gift_given: { + out: {label: "Gjeven gåve", currencies: ["sats"]}, + consumes: true + }, + admin_cost: { + out: {label: "Kostnad", currencies: ["sats", "nok"]}, + consumes: true + } + }; + + /* Types where a sats fee is taken on top of the amount given away, §3.2. */ + var FEE_TAKEN_ON_TOP = ["trade", "spend"]; + + 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 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 + && Skuld.fieldValue("fee_currency") === "sats") { + 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.nok_per_btc_ore - left.nok_per_btc_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.nok_per_btc_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; + }); + } + + 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 currencySelect = document.querySelector('[name="' + name + '_currency"]'); + var fixed = settings.currencies.length === 1; + currencySelect.hidden = fixed; + currencySelect.value = settings.currencies[0]; + }); + + group("value").hidden = !spec.value; + if (spec.value) { + label("value").textContent = spec.value.label; + document.querySelector('[name="value"]').placeholder = + spec.value.optional ? "Valfri" : ""; + } else { + Skuld.setFieldValue("value", ""); + } + + group("to_market").hidden = !spec.to; + if (!spec.to) { + Skuld.setFieldValue("to_market", ""); + } + } + + function fillTypes() { + var select = document.querySelector('[name="type"]'); + Object.keys(Skuld.TYPE_LABELS).forEach(function (key) { + if (key === "transfer_in") { + return; + } + var option = document.createElement("option"); + option.value = key; + option.textContent = Skuld.typeLabel(key); + select.appendChild(option); + }); + } + + function fillMarkets(markets) { + markets.forEach(function (market) { + ["market_id", "to_market"].forEach(function (name) { + var option = document.createElement("option"); + option.value = String(market.id); + option.textContent = market.name; + document.querySelector('[name="' + name + '"]').appendChild(option); + }); + }); + } + + function payload() { + var data = { + date: Skuld.fieldValue("date"), + type: type(), + taxable: Skuld.fieldChecked("taxable") ? 1 : 0, + note: Skuld.fieldValue("note") + }; + var marketId = 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[Skuld.fieldValue("fee_currency") === "sats" ? "fee_sats" : "fee_ore"] = 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_currency", "sats"); + Skuld.setFieldValue("fee", Skuld.formatSats(transaction.fee_sats)); + } else if (transaction.fee_ore) { + Skuld.setFieldValue("fee_currency", "nok"); + Skuld.setFieldValue("fee", Skuld.formatOre(transaction.fee_ore)); + } + 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); + }); + + ["leg_out_amount", "fee", "fee_currency", "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); +})();