openvibers/openvibe.finance serverstore.js
store.js
| 1 | ; |
| 2 | /** |
| 3 | * A person's accounts and transactions (migrations/0001_finance.sql). Every function takes the person (owner, a usr_ |
| 4 | * subject) and reads or writes only their rows; payees and memos are sealed with their key (server/crypto.js) on the |
| 5 | * way in and opened on the way out. |
| 6 | * |
| 7 | * const store = createStore({ db, vault }); |
| 8 | * accounts(owner) → [{ id, name, kind, currency, balance_cents, count, last_on }] |
| 9 | * account(owner, id) → one, or null |
| 10 | * addAccount(owner, { name, kind, currency, opening_cents }) |
| 11 | * transactions(owner, accountId, { month }) → [{ id, posted_on, amount_cents, payee, memo, category, category_from }] |
| 12 | * addTransaction(owner, accountId, { posted_on, amount_cents, payee, memo, category }) |
| 13 | * setCategory(owner, id, category, { from }) a correction: a new revision, category_from 'you' (or 'ai': an agent the |
| 14 | * person allowed to write; it never overwrites one they set themselves) |
| 15 | * removeTransaction(owner, id) |
| 16 | * importRows(owner, accountId, rows) → { import_id, read, added, skipped } (the same row twice is one) |
| 17 | * month(owner, 'YYYY-MM') → { month, income_cents, spent_cents, by_category: [{ category, cents, count }] } |
| 18 | * rules(owner) → [{ id, match, category }] (longest words first) |
| 19 | * addRule(owner, { match, category }) the same words again replace the category; applied to the past |
| 20 | * removeRule(owner, id) |
| 21 | * budgets(owner) → [{ category, monthly_cents }] |
| 22 | * setBudget(owner, category, cents|null) a monthly limit for a category; null or 0 removes it |
| 23 | * goals(owner) → [{ id, name, target_cents, target_on, account_id, saved_cents, have_cents }] |
| 24 | * addGoal(owner, { name, target_cents, target_on, account_id, saved_cents }) / setGoalSaved(owner, id, cents) / removeGoal |
| 25 | * setDebt(owner, accountId, { apr_bps, payment_cents }) a loan's or card's rate and monthly payment |
| 26 | * ahead(owner) → { accounts: [{ id, kind, opening_cents, balance_cents }], moves: [{ account_id, month, cents }] } |
| 27 | * exportAll(owner) → everything, opened (the person's own copy) |
| 28 | * removeAll(owner) → everything of theirs deleted |
| 29 | */ |
| 30 | const crypto = require('node:crypto'); |
| 31 | |
| 32 | const KINDS = ['checking', 'savings', 'credit', 'cash', 'loan', 'investment', 'other']; |
| 33 | const CATEGORIES = ['Income', 'Housing', 'Utilities', 'Groceries', 'Eating out', 'Transport', 'Health', 'Insurance', 'Shopping', |
| 34 | 'Subscriptions', 'Entertainment', 'Travel', 'Education', 'Gifts and giving', 'Fees', 'Transfers', 'Savings', 'Debt payments', 'Taxes', 'Other', 'Uncategorized']; |
| 35 | const newId = (prefix) => `${prefix}_${crypto.randomBytes(12).toString('base64url')}`; |
| 36 | const MONTH = /^\d{4}-(0[1-9]|1[0-2])$/; |
| 37 | const DAY = /^\d{4}-\d{2}-\d{2}$/; |
| 38 | |
| 39 | class FinanceError extends Error { |
| 40 | constructor(status, code, message) { super(message); this.status = status; this.code = code; } |
| 41 | } |
| 42 | const fail = (status, code, message) => { throw new FinanceError(status, code, message); }; |
| 43 | |
| 44 | function cleanCategory(c) { |
| 45 | const t = String(c || '').replace(/\s+/g, ' ').trim().slice(0, 60); |
| 46 | return t || 'Uncategorized'; |
| 47 | } |
| 48 | |
| 49 | /** Words for matching: lower case, one space, no digits-only runs (card and reference numbers change every time). */ |
| 50 | const matchable = (t) => String(t || '').toLowerCase().replace(/\b\d{3,}\b/g, ' ').replace(/[^a-z0-9&'.\- ]+/g, ' ').replace(/\s+/g, ' ').trim(); |
| 51 | |
| 52 | function createStore({ db, vault }) { |
| 53 | const own = (owner) => { if (!/^usr_[0-9A-Za-z]{10,40}$/.test(String(owner || ''))) fail(401, 'finance.person', 'Sign in first.'); return owner; }; |
| 54 | const open = (owner, row) => ({ |
| 55 | id: row.id, account_id: row.account_id, posted_on: row.posted_on, amount_cents: Number(row.amount_cents), |
| 56 | payee: vault.open(owner, row.payee_enc), memo: vault.open(owner, row.memo_enc), |
| 57 | category: row.category, category_from: row.category_from, revision: row.revision, |
| 58 | }); |
| 59 | |
| 60 | async function accounts(owner) { |
| 61 | own(owner); |
| 62 | const rows = await db.many(`SELECT a.id, a.name, a.kind, a.currency, a.opening_cents, a.apr_bps, a.payment_cents, |
| 63 | COALESCE(SUM(t.amount_cents), 0)::bigint AS moved, COUNT(t.id)::int AS count, MAX(t.posted_on) AS last_on |
| 64 | FROM finance_accounts a LEFT JOIN finance_transactions t ON t.account_id = a.id |
| 65 | WHERE a.owner = $1 AND a.archived_at IS NULL GROUP BY a.id ORDER BY a.created_at, a.id`, [owner]); |
| 66 | return rows.map((r) => ({ id: r.id, name: r.name, kind: r.kind, currency: r.currency, balance_cents: Number(r.opening_cents) + Number(r.moved), count: r.count, last_on: r.last_on || null, |
| 67 | apr_bps: r.apr_bps == null ? null : Number(r.apr_bps), payment_cents: r.payment_cents == null ? null : Number(r.payment_cents) })); |
| 68 | } |
| 69 | |
| 70 | /** Every transaction of the person from the last `days` days, across their accounts, opened (recurring, scenarios). */ |
| 71 | async function recent(owner, { days = 400, limit = 20000 } = {}) { |
| 72 | own(owner); |
| 73 | const rows = await db.many(`SELECT t.* FROM finance_transactions t JOIN finance_accounts a ON a.id = t.account_id AND a.archived_at IS NULL |
| 74 | WHERE t.owner = $1 AND t.posted_on >= (CURRENT_DATE - $2::int) ORDER BY t.posted_on, t.id LIMIT ${Math.max(1, Math.min(50000, Number(limit) || 20000))}`, [owner, Math.max(1, Math.min(2000, Number(days) || 400))]); |
| 75 | return rows.map((r) => open(owner, r)); |
| 76 | } |
| 77 | |
| 78 | async function account(owner, id) { |
| 79 | own(owner); |
| 80 | const r = await db.maybe('SELECT id, name, kind, currency, opening_cents FROM finance_accounts WHERE id = $1 AND owner = $2 AND archived_at IS NULL', [String(id || ''), owner]); |
| 81 | return r ? { ...r, opening_cents: Number(r.opening_cents) } : null; |
| 82 | } |
| 83 | |
| 84 | async function addAccount(owner, input = {}) { |
| 85 | own(owner); |
| 86 | const name = String(input.name || '').replace(/\s+/g, ' ').trim().slice(0, 80); |
| 87 | if (!name) fail(422, 'finance.account.name', 'Give the account a name.'); |
| 88 | const kind = KINDS.includes(input.kind) ? input.kind : 'checking'; |
| 89 | const currency = /^[A-Z]{3}$/.test(String(input.currency || '').toUpperCase()) ? String(input.currency).toUpperCase() : 'USD'; |
| 90 | const opening = Number.isSafeInteger(input.opening_cents) ? input.opening_cents : 0; |
| 91 | const count = Number(await db.value('SELECT count(*) FROM finance_accounts WHERE owner = $1 AND archived_at IS NULL', [owner])); |
| 92 | if (count >= 100) fail(422, 'finance.account.limit', 'A hundred accounts is the most for now.'); |
| 93 | const id = newId('acc'); |
| 94 | await db.exec('INSERT INTO finance_accounts (id, owner, name, kind, currency, opening_cents) VALUES ($1, $2, $3, $4, $5, $6)', [id, owner, name, kind, currency, opening]); |
| 95 | return account(owner, id); |
| 96 | } |
| 97 | |
| 98 | async function transactions(owner, accountId, { month = null, limit = 500 } = {}) { |
| 99 | own(owner); |
| 100 | const args = [owner, String(accountId || '')]; |
| 101 | let where = 'owner = $1 AND account_id = $2'; |
| 102 | if (month) { |
| 103 | if (!MONTH.test(month)) fail(422, 'finance.month', 'A month is YYYY-MM.'); |
| 104 | args.push(`${month}-01`); |
| 105 | where += ` AND posted_on >= $3::date AND posted_on < ($3::date + interval '1 month')`; |
| 106 | } |
| 107 | const rows = await db.many(`SELECT * FROM finance_transactions WHERE ${where} ORDER BY posted_on DESC, created_at DESC, id LIMIT ${Math.max(1, Math.min(2000, Number(limit) || 500))}`, args); |
| 108 | return rows.map((r) => open(owner, r)); |
| 109 | } |
| 110 | |
| 111 | function checkRow(input) { |
| 112 | const posted_on = String(input.posted_on || ''); |
| 113 | if (!DAY.test(posted_on) || Number.isNaN(Date.parse(`${posted_on}T00:00:00Z`))) fail(422, 'finance.transaction.date', 'A date is YYYY-MM-DD.'); |
| 114 | if (!Number.isSafeInteger(input.amount_cents) || Math.abs(input.amount_cents) > 1e13) fail(422, 'finance.transaction.amount', 'An amount is a number of cents.'); |
| 115 | return { |
| 116 | posted_on, amount_cents: input.amount_cents, |
| 117 | payee: String(input.payee || '').replace(/\s+/g, ' ').trim().slice(0, 300), |
| 118 | memo: String(input.memo || '').replace(/\s+/g, ' ').trim().slice(0, 500), |
| 119 | category: cleanCategory(input.category), |
| 120 | }; |
| 121 | } |
| 122 | |
| 123 | async function addTransaction(owner, accountId, input = {}) { |
| 124 | own(owner); |
| 125 | const acc = await account(owner, accountId); |
| 126 | if (!acc) fail(404, 'finance.account.not_found', 'No such account of yours.'); |
| 127 | const r = checkRow(input); |
| 128 | const id = newId('txn'); |
| 129 | await db.exec(`INSERT INTO finance_transactions (id, owner, account_id, posted_on, amount_cents, payee_enc, memo_enc, category, category_from) |
| 130 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, |
| 131 | [id, owner, acc.id, r.posted_on, r.amount_cents, vault.seal(owner, r.payee), vault.seal(owner, r.memo), r.category, r.category === 'Uncategorized' ? 'none' : 'you']); |
| 132 | return open(owner, await db.one('SELECT * FROM finance_transactions WHERE id = $1', [id])); |
| 133 | } |
| 134 | |
| 135 | async function setCategory(owner, id, category, { from = 'you' } = {}) { |
| 136 | own(owner); |
| 137 | const c = cleanCategory(category); |
| 138 | const by = from === 'ai' ? 'ai' : 'you'; |
| 139 | const n = await db.exec(`UPDATE finance_transactions SET category = $3, category_from = $4, revision = revision + 1, updated_at = now() |
| 140 | WHERE id = $1 AND owner = $2 AND ($4 = 'you' OR category_from <> 'you')`, [String(id || ''), owner, c, by]); |
| 141 | if (!n) { |
| 142 | const row = await db.maybe('SELECT category_from FROM finance_transactions WHERE id = $1 AND owner = $2', [String(id || ''), owner]); |
| 143 | if (!row) fail(404, 'finance.transaction.not_found', 'No such transaction of yours.'); |
| 144 | fail(409, 'finance.transaction.yours', 'You set this category yourself: an agent leaves it as it is.'); |
| 145 | } |
| 146 | return open(owner, await db.one('SELECT * FROM finance_transactions WHERE id = $1', [String(id)])); |
| 147 | } |
| 148 | |
| 149 | async function removeTransaction(owner, id) { |
| 150 | own(owner); |
| 151 | await db.exec('DELETE FROM finance_transactions WHERE id = $1 AND owner = $2', [String(id || ''), owner]); |
| 152 | } |
| 153 | |
| 154 | async function importRows(owner, accountId, rows) { |
| 155 | own(owner); |
| 156 | const acc = await account(owner, accountId); |
| 157 | if (!acc) fail(404, 'finance.account.not_found', 'No such account of yours.'); |
| 158 | const list = Array.isArray(rows) ? rows.slice(0, 20000) : []; |
| 159 | const importId = newId('imp'); |
| 160 | const known = await rules(owner); |
| 161 | let added = 0; |
| 162 | await db.tx(async (t) => { |
| 163 | await t.exec('INSERT INTO finance_imports (id, owner, account_id, format, rows_read) VALUES ($1, $2, $3, $4, $5)', [importId, owner, acc.id, 'csv', list.length]); |
| 164 | // The same row twice in one file is two transactions (two coffees on one day); the same file twice is not. |
| 165 | const seen = new Map(); |
| 166 | for (const input of list) { |
| 167 | const r = checkRow(input); |
| 168 | let from = r.category === 'Uncategorized' ? 'none' : 'file'; |
| 169 | if (from === 'none') { const hit = ruleFor(known, r.payee); if (hit) { r.category = hit.category; from = 'rule'; } } |
| 170 | const key = `${acc.id}|${r.posted_on}|${r.amount_cents}|${r.payee.toLowerCase()}`; |
| 171 | const nth = (seen.get(key) || 0) + 1; |
| 172 | seen.set(key, nth); |
| 173 | // The bank's own transaction id (an OFX/QFX FITID) is exact: the same download twice, or two that |
| 174 | // overlap, add each transaction once. |
| 175 | const fitid = typeof input.fitid === 'string' && input.fitid.trim() ? input.fitid.trim().slice(0, 255) : null; |
| 176 | const out = await t.exec(`INSERT INTO finance_transactions (id, owner, account_id, posted_on, amount_cents, payee_enc, memo_enc, category, category_from, import_id, dedupe) |
| 177 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) ON CONFLICT (account_id, dedupe) WHERE dedupe IS NOT NULL DO NOTHING`, |
| 178 | [newId('txn'), owner, acc.id, r.posted_on, r.amount_cents, vault.seal(owner, r.payee), vault.seal(owner, r.memo), r.category, |
| 179 | from, importId, vault.mark(owner, fitid ? `fitid|${acc.id}|${fitid}` : `${key}|${nth}`)]); |
| 180 | if (out) added++; |
| 181 | } |
| 182 | await t.exec('UPDATE finance_imports SET rows_added = $2, rows_skipped = $3 WHERE id = $1', [importId, added, list.length - added]); |
| 183 | }); |
| 184 | return { import_id: importId, read: list.length, added, skipped: list.length - added }; |
| 185 | } |
| 186 | |
| 187 | async function month(owner, m) { |
| 188 | own(owner); |
| 189 | if (!MONTH.test(String(m || ''))) fail(422, 'finance.month', 'A month is YYYY-MM.'); |
| 190 | // In and out by each transaction's sign, never a category's net: a paycheck and a coffee in one category are $2,500 |
| 191 | // in and $4.50 out, not $2,495.50 in. |
| 192 | const rows = await db.many(`SELECT t.category, |
| 193 | SUM(CASE WHEN t.amount_cents > 0 THEN t.amount_cents ELSE 0 END)::bigint AS in_cents, |
| 194 | SUM(CASE WHEN t.amount_cents < 0 THEN -t.amount_cents ELSE 0 END)::bigint AS out_cents, COUNT(*)::int AS count |
| 195 | FROM finance_transactions t JOIN finance_accounts a ON a.id = t.account_id AND a.archived_at IS NULL |
| 196 | WHERE t.owner = $1 AND t.posted_on >= $2::date AND t.posted_on < ($2::date + interval '1 month') AND t.category <> 'Transfers' |
| 197 | GROUP BY t.category ORDER BY 3 DESC, 2 DESC`, [owner, `${m}-01`]); |
| 198 | let income = 0, spent = 0; |
| 199 | const by = rows.map((r) => { |
| 200 | const i = Number(r.in_cents), o = Number(r.out_cents); |
| 201 | income += i; spent += o; |
| 202 | return { category: r.category, in_cents: i, out_cents: o, cents: i - o, count: r.count }; |
| 203 | }); |
| 204 | return { month: m, income_cents: income, spent_cents: spent, by_category: by }; |
| 205 | } |
| 206 | |
| 207 | async function rules(owner) { |
| 208 | own(owner); |
| 209 | const rows = await db.many('SELECT id, match_enc, category FROM finance_rules WHERE owner = $1', [owner]); |
| 210 | return rows.map((r) => ({ id: r.id, match: vault.open(owner, r.match_enc), category: r.category })).sort((a, b) => b.match.length - a.match.length); |
| 211 | } |
| 212 | /** The rule a payee falls under: the longest words it contains. */ |
| 213 | const ruleFor = (list, payee) => { const p = matchable(payee); return p ? list.find((r) => p.includes(r.match)) || null : null; }; |
| 214 | |
| 215 | /** Put every uncategorised transaction of the person (or of one account) under the rules. → how many changed. */ |
| 216 | async function applyRules(owner, list = null) { |
| 217 | const all = list || await rules(owner); |
| 218 | if (!all.length) return 0; |
| 219 | const rows = await db.many("SELECT id, payee_enc FROM finance_transactions WHERE owner = $1 AND category_from = 'none' LIMIT 20000", [owner]); |
| 220 | let changed = 0; |
| 221 | for (const r of rows) { |
| 222 | const hit = ruleFor(all, vault.open(owner, r.payee_enc)); |
| 223 | if (!hit) continue; |
| 224 | changed += await db.exec(`UPDATE finance_transactions SET category = $3, category_from = 'rule', revision = revision + 1, updated_at = now() |
| 225 | WHERE id = $1 AND owner = $2 AND category_from = 'none'`, [r.id, owner, hit.category]); |
| 226 | } |
| 227 | return changed; |
| 228 | } |
| 229 | |
| 230 | async function addRule(owner, input = {}) { |
| 231 | own(owner); |
| 232 | const match = matchable(input.match).slice(0, 120); |
| 233 | if (match.length < 2) fail(422, 'finance.rule.match', 'A rule needs a few words of the payee.'); |
| 234 | const category = cleanCategory(input.category); |
| 235 | if (category === 'Uncategorized') fail(422, 'finance.rule.category', 'Say which category it is.'); |
| 236 | const count = Number(await db.value('SELECT count(*) FROM finance_rules WHERE owner = $1', [owner])); |
| 237 | const mark = vault.mark(owner, `rule|${match}`); |
| 238 | const known = await db.maybe('SELECT id FROM finance_rules WHERE owner = $1 AND match_mark = $2', [owner, mark]); |
| 239 | if (!known && count >= 500) fail(422, 'finance.rule.limit', 'Five hundred rules is the most for now.'); |
| 240 | const id = known ? known.id : newId('rul'); |
| 241 | await db.exec(`INSERT INTO finance_rules (id, owner, match_enc, match_mark, category) VALUES ($1, $2, $3, $4, $5) |
| 242 | ON CONFLICT (owner, match_mark) DO UPDATE SET category = EXCLUDED.category`, [id, owner, vault.seal(owner, match), mark, category]); |
| 243 | const applied = await applyRules(owner); |
| 244 | return { id, match, category, applied }; |
| 245 | } |
| 246 | |
| 247 | async function removeRule(owner, id) { |
| 248 | own(owner); |
| 249 | await db.exec('DELETE FROM finance_rules WHERE id = $1 AND owner = $2', [String(id || ''), owner]); |
| 250 | } |
| 251 | |
| 252 | async function budgets(owner) { |
| 253 | own(owner); |
| 254 | const rows = await db.many('SELECT category, monthly_cents FROM finance_budgets WHERE owner = $1 ORDER BY category', [owner]); |
| 255 | return rows.map((r) => ({ category: r.category, monthly_cents: Number(r.monthly_cents) })); |
| 256 | } |
| 257 | |
| 258 | async function setBudget(owner, category, cents) { |
| 259 | own(owner); |
| 260 | const c = cleanCategory(category); |
| 261 | if (c === 'Uncategorized' || c === 'Income' || c === 'Transfers') fail(422, 'finance.budget.category', `A budget is for a category of spending, not ${c}.`); |
| 262 | if (cents == null || cents === 0) { await db.exec('DELETE FROM finance_budgets WHERE owner = $1 AND category = $2', [owner, c]); return null; } |
| 263 | if (!Number.isSafeInteger(cents) || cents < 0 || cents > 1e11) fail(422, 'finance.budget.amount', 'A budget is an amount of money a month.'); |
| 264 | const count = Number(await db.value('SELECT count(*) FROM finance_budgets WHERE owner = $1', [owner])); |
| 265 | if (count >= 100) fail(422, 'finance.budget.limit', 'A hundred budgets is the most for now.'); |
| 266 | await db.exec(`INSERT INTO finance_budgets (owner, category, monthly_cents) VALUES ($1, $2, $3) |
| 267 | ON CONFLICT (owner, category) DO UPDATE SET monthly_cents = EXCLUDED.monthly_cents, updated_at = now()`, [owner, c, cents]); |
| 268 | return { category: c, monthly_cents: cents }; |
| 269 | } |
| 270 | |
| 271 | async function goals(owner) { |
| 272 | own(owner); |
| 273 | const rows = await db.many('SELECT * FROM finance_goals WHERE owner = $1 ORDER BY created_at, id', [owner]); |
| 274 | const balances = new Map((await accounts(owner)).map((a) => [a.id, a.balance_cents])); |
| 275 | return rows.map((g) => ({ |
| 276 | id: g.id, name: g.name, target_cents: Number(g.target_cents), target_on: g.target_on || null, account_id: g.account_id || null, |
| 277 | saved_cents: Number(g.saved_cents), have_cents: g.account_id && balances.has(g.account_id) ? balances.get(g.account_id) : Number(g.saved_cents), |
| 278 | })); |
| 279 | } |
| 280 | |
| 281 | async function addGoal(owner, input = {}) { |
| 282 | own(owner); |
| 283 | const name = String(input.name || '').replace(/\s+/g, ' ').trim().slice(0, 80); |
| 284 | if (!name) fail(422, 'finance.goal.name', 'Give the goal a name.'); |
| 285 | if (!Number.isSafeInteger(input.target_cents) || input.target_cents <= 0) fail(422, 'finance.goal.target', 'A goal is an amount to reach.'); |
| 286 | const on = input.target_on ? String(input.target_on) : null; |
| 287 | if (on && (!DAY.test(on) || Number.isNaN(Date.parse(`${on}T00:00:00Z`)))) fail(422, 'finance.goal.date', 'A date is YYYY-MM-DD.'); |
| 288 | let accountId = input.account_id ? String(input.account_id) : null; |
| 289 | if (accountId && !(await account(owner, accountId))) fail(404, 'finance.account.not_found', 'No such account of yours.'); |
| 290 | const saved = Number.isSafeInteger(input.saved_cents) && input.saved_cents > 0 ? input.saved_cents : 0; |
| 291 | if (Number(await db.value('SELECT count(*) FROM finance_goals WHERE owner = $1', [owner])) >= 50) fail(422, 'finance.goal.limit', 'Fifty goals is the most for now.'); |
| 292 | const id = newId('gol'); |
| 293 | await db.exec('INSERT INTO finance_goals (id, owner, name, target_cents, target_on, account_id, saved_cents) VALUES ($1, $2, $3, $4, $5, $6, $7)', [id, owner, name, input.target_cents, on, accountId, saved]); |
| 294 | return (await goals(owner)).find((g) => g.id === id); |
| 295 | } |
| 296 | |
| 297 | async function setGoalSaved(owner, id, cents) { |
| 298 | own(owner); |
| 299 | if (!Number.isSafeInteger(cents) || cents < 0) fail(422, 'finance.goal.saved', 'An amount saved is a number.'); |
| 300 | const n = await db.exec('UPDATE finance_goals SET saved_cents = $3, updated_at = now() WHERE id = $1 AND owner = $2', [String(id || ''), owner, cents]); |
| 301 | if (!n) fail(404, 'finance.goal.not_found', 'No such goal of yours.'); |
| 302 | } |
| 303 | |
| 304 | async function removeGoal(owner, id) { |
| 305 | own(owner); |
| 306 | await db.exec('DELETE FROM finance_goals WHERE id = $1 AND owner = $2', [String(id || ''), owner]); |
| 307 | } |
| 308 | |
| 309 | async function setDebt(owner, accountId, { apr_bps = null, payment_cents = null } = {}) { |
| 310 | own(owner); |
| 311 | const acc = await db.maybe('SELECT id, kind FROM finance_accounts WHERE id = $1 AND owner = $2 AND archived_at IS NULL', [String(accountId || ''), owner]); |
| 312 | if (!acc) fail(404, 'finance.account.not_found', 'No such account of yours.'); |
| 313 | if (!['loan', 'credit'].includes(acc.kind)) fail(422, 'finance.debt.kind', 'Only a loan or a credit card has a rate and a payment.'); |
| 314 | if (apr_bps != null && (!Number.isInteger(apr_bps) || apr_bps < 0 || apr_bps > 10000)) fail(422, 'finance.debt.rate', 'A yearly rate is between 0% and 100%.'); |
| 315 | if (payment_cents != null && (!Number.isSafeInteger(payment_cents) || payment_cents <= 0)) fail(422, 'finance.debt.payment', 'A monthly payment is an amount of money.'); |
| 316 | await db.exec('UPDATE finance_accounts SET apr_bps = $3, payment_cents = $4, updated_at = now() WHERE id = $1 AND owner = $2', [acc.id, owner, apr_bps, payment_cents]); |
| 317 | } |
| 318 | |
| 319 | /** What net worth over time and the what-if are worked out from (server/ahead.js): no payee is opened. */ |
| 320 | async function ahead(owner) { |
| 321 | own(owner); |
| 322 | const accs = await db.many('SELECT id, kind, opening_cents FROM finance_accounts WHERE owner = $1 AND archived_at IS NULL', [owner]); |
| 323 | const moves = await db.many(`SELECT t.account_id, to_char(date_trunc('month', t.posted_on), 'YYYY-MM') AS month, SUM(t.amount_cents)::bigint AS cents |
| 324 | FROM finance_transactions t JOIN finance_accounts a ON a.id = t.account_id AND a.archived_at IS NULL |
| 325 | WHERE t.owner = $1 GROUP BY 1, 2`, [owner]); |
| 326 | const moved = new Map(); |
| 327 | for (const m of moves) moved.set(m.account_id, (moved.get(m.account_id) || 0) + Number(m.cents)); |
| 328 | return { |
| 329 | accounts: accs.map((a) => ({ id: a.id, kind: a.kind, opening_cents: Number(a.opening_cents), balance_cents: Number(a.opening_cents) + (moved.get(a.id) || 0) })), |
| 330 | moves: moves.map((m) => ({ account_id: m.account_id, month: m.month, cents: Number(m.cents) })), |
| 331 | }; |
| 332 | } |
| 333 | |
| 334 | async function exportAll(owner) { |
| 335 | own(owner); |
| 336 | const accs = await db.many('SELECT id, name, kind, currency, opening_cents, apr_bps, payment_cents, created_at, archived_at FROM finance_accounts WHERE owner = $1 ORDER BY created_at', [owner]); |
| 337 | const txns = await db.many('SELECT * FROM finance_transactions WHERE owner = $1 ORDER BY posted_on, created_at', [owner]); |
| 338 | return { |
| 339 | exported_at: new Date().toISOString(), format: 'openvibe.finance.export@1', |
| 340 | accounts: accs.map((a) => ({ ...a, opening_cents: Number(a.opening_cents) })), |
| 341 | transactions: txns.map((r) => open(owner, r)), |
| 342 | rules: (await rules(owner)).map((r) => ({ match: r.match, category: r.category })), |
| 343 | budgets: await budgets(owner), |
| 344 | goals: (await goals(owner)).map(({ have_cents, ...g }) => g), |
| 345 | }; |
| 346 | } |
| 347 | |
| 348 | async function removeAll(owner) { |
| 349 | own(owner); |
| 350 | await db.tx(async (t) => { |
| 351 | await t.exec('DELETE FROM finance_transactions WHERE owner = $1', [owner]); |
| 352 | await t.exec('DELETE FROM finance_imports WHERE owner = $1', [owner]); |
| 353 | await t.exec('DELETE FROM finance_rules WHERE owner = $1', [owner]); |
| 354 | await t.exec('DELETE FROM finance_budgets WHERE owner = $1', [owner]); |
| 355 | await t.exec('DELETE FROM finance_goals WHERE owner = $1', [owner]); |
| 356 | await t.exec('DELETE FROM finance_accounts WHERE owner = $1', [owner]); |
| 357 | }); |
| 358 | } |
| 359 | |
| 360 | return { recent, accounts, account, addAccount, transactions, addTransaction, setCategory, removeTransaction, importRows, month, rules, addRule, removeRule, applyRules, budgets, setBudget, goals, addGoal, setGoalSaved, removeGoal, setDebt, ahead, exportAll, removeAll }; |
| 361 | } |
| 362 | |
| 363 | module.exports = { createStore, FinanceError, KINDS, CATEGORIES, matchable }; |
| 364 |